actual/packages/api/app/bundle.api.js
2022-04-28 22:44:38 -04:00

69607 lines
2.4 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // object to store loaded chunks
/******/ // "0" means "already loaded"
/******/ var installedChunks = {
/******/ "main": 0
/******/ };
/******/
/******/ // 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 = "";
/******/
/******/ // uncaught error handler for webpack runtime
/******/ __webpack_require__.oe = function(err) {
/******/ process.nextTick(function() {
/******/ throw err; // catch this error by using import().catch()
/******/ });
/******/ };
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./packages/loot-core/src/server/main.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/@jlongster/mixpanel/lib/groups.js":
/*!********************************************************!*\
!*** ./node_modules/@jlongster/mixpanel/lib/groups.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/**
* Group profile methods. Learn more: https://help.mixpanel.com/hc/en-us/articles/360025333632
*/
const _require = __webpack_require__(/*! ./profile_helpers */ "./node_modules/@jlongster/mixpanel/lib/profile_helpers.js"),
ProfileHelpers = _require.ProfileHelpers;
class MixpanelGroups extends ProfileHelpers() {
constructor(mp_instance) {
super();
this.mixpanel = mp_instance;
this.endpoint = '/groups';
}
/** groups.set_once(group_key, group_id, prop, to, modifiers, callback)
---
The same as groups.set, but adds a property value to a group only if it has not been set before.
*/
set_once(group_key, group_id, prop, to, modifiers, callback) {
const identifiers = {
$group_key: group_key,
$group_id: group_id
};
this._set(prop, to, modifiers, callback, {
identifiers,
set_once: true
});
}
/**
groups.set(group_key, group_id, prop, to, modifiers, callback)
---
set properties on a group profile
usage:
mixpanel.groups.set('company', 'Acme Inc.', '$name', 'Acme Inc.');
mixpanel.groups.set('company', 'Acme Inc.', {
'Industry': 'widgets',
'$name': 'Acme Inc.',
});
*/
set(group_key, group_id, prop, to, modifiers, callback) {
const identifiers = {
$group_key: group_key,
$group_id: group_id
};
this._set(prop, to, modifiers, callback, {
identifiers
});
}
/**
groups.delete_group(group_key, group_id, modifiers, callback)
---
delete a group profile permanently
usage:
mixpanel.groups.delete_group('company', 'Acme Inc.');
*/
delete_group(group_key, group_id, modifiers, callback) {
const identifiers = {
$group_key: group_key,
$group_id: group_id
};
this._delete_profile({
identifiers,
modifiers,
callback
});
}
/**
groups.remove(group_key, group_id, data, modifiers, callback)
---
remove a value from a list-valued group profile property.
usage:
mixpanel.groups.remove('company', 'Acme Inc.', {'products': 'anvil'});
mixpanel.groups.remove('company', 'Acme Inc.', {
'products': 'anvil',
'customer segments': 'coyotes'
});
*/
remove(group_key, group_id, data, modifiers, callback) {
const identifiers = {
$group_key: group_key,
$group_id: group_id
};
this._remove({
identifiers,
data,
modifiers,
callback
});
}
/**
groups.union(group_key, group_id, data, modifiers, callback)
---
merge value(s) into a list-valued group profile property.
usage:
mixpanel.groups.union('company', 'Acme Inc.', {'products': 'anvil'});
mixpanel.groups.union('company', 'Acme Inc.', {'products': ['anvil'], 'customer segments': ['coyotes']});
*/
union(group_key, group_id, data, modifiers, callback) {
const identifiers = {
$group_key: group_key,
$group_id: group_id
};
this._union({
identifiers,
data,
modifiers,
callback
});
}
/**
groups.unset(group_key, group_id, prop, modifiers, callback)
---
delete a property on a group profile
usage:
mixpanel.groups.unset('company', 'Acme Inc.', 'products');
mixpanel.groups.unset('company', 'Acme Inc.', ['products', 'customer segments']);
*/
unset(group_key, group_id, prop, modifiers, callback) {
const identifiers = {
$group_key: group_key,
$group_id: group_id
};
this._unset({
identifiers,
prop,
modifiers,
callback
});
}
}
exports.MixpanelGroups = MixpanelGroups;
/***/ }),
/***/ "./node_modules/@jlongster/mixpanel/lib/mixpanel-node.js":
/*!***************************************************************!*\
!*** ./node_modules/@jlongster/mixpanel/lib/mixpanel-node.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/*
Heavily inspired by the original js library copyright Mixpanel, Inc.
(http://mixpanel.com/)
Copyright (c) 2012 Carl Sverre
Released under the MIT license.
*/
const _require = __webpack_require__(/*! ./utils */ "./node_modules/@jlongster/mixpanel/lib/utils.js"),
async_all = _require.async_all,
ensure_timestamp = _require.ensure_timestamp;
const _require2 = __webpack_require__(/*! ./groups */ "./node_modules/@jlongster/mixpanel/lib/groups.js"),
MixpanelGroups = _require2.MixpanelGroups;
const _require3 = __webpack_require__(/*! ./people */ "./node_modules/@jlongster/mixpanel/lib/people.js"),
MixpanelPeople = _require3.MixpanelPeople;
const DEFAULT_CONFIG = {
test: false,
debug: false,
verbose: false,
host: 'api.mixpanel.com',
protocol: 'https',
path: ''
};
function base64(str) {
return typeof btoa !== 'undefined' ? btoa(str) : Buffer.from(str).toString('base64');
}
var create_client = function (token, config) {
if (!token) {
throw new Error("The Mixpanel Client needs a Mixpanel token: `init(token)`");
} // mixpanel constants
const MAX_BATCH_SIZE = 50;
const TRACK_AGE_LIMIT = 60 * 60 * 24 * 5;
const metrics = {
token,
config: _objectSpread({}, DEFAULT_CONFIG)
};
/**
* sends an async GET or POST request to mixpanel
* for batch processes data must be send in the body of a POST
* @param {object} options
* @param {string} options.endpoint
* @param {object} options.data the data to send in the request
* @param {string} [options.method] e.g. `get` or `post`, defaults to `get`
* @param {function} callback called on request completion or error
*/
metrics.send_request = function (options, callback) {
callback = callback || function () {};
let content = base64(JSON.stringify(options.data));
const endpoint = options.endpoint;
const method = (options.method || 'GET').toUpperCase();
let query_params = {
'ip': 0,
'verbose': metrics.config.verbose ? 1 : 0
};
const key = metrics.config.key;
const secret = metrics.config.secret;
let request_options = {
headers: {}
};
let request;
let request_base = `${metrics.config.protocol}://${metrics.config.host}`;
if (metrics.config.port) {
request_base += `:${metrics.config.port}`;
}
if (method === 'POST') {
content = 'data=' + content;
request_options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
request_options.headers['Content-Length'] = content.length;
} else if (method === 'GET') {
query_params.data = content;
} // add auth params
if (secret) {
if (metrics.config.protocol !== 'https') {
throw new Error("Must use HTTPS if authenticating with API Secret");
}
const encoded = base64(secret + ':');
request_options.headers['Authorization'] = 'Basic ' + encoded;
} else if (key) {
query_params.api_key = key;
} else if (endpoint === '/import') {
throw new Error("The Mixpanel Client needs a Mixpanel API Secret when importing old events: `init(token, { secret: ... })`");
}
if (metrics.config.test) {
query_params.test = 1;
}
request_options.path = metrics.config.path + endpoint + "?" + new URLSearchParams(query_params).toString();
fetch(request_base + request_options.path, {
method,
headers: request_options.headers,
body: method !== 'GET' ? content : null
}).then(res => {
return res.text();
}).then(text => {
var e;
if (metrics.config.verbose) {
try {
var result = JSON.parse(text);
if (result.status != 1) {
e = new Error("Mixpanel Server Error: " + result.error);
}
} catch (ex) {
e = new Error("Could not parse response from Mixpanel");
}
} else {
e = text !== '1' ? new Error("Mixpanel Server Error: " + text) : undefined;
}
callback(e);
}).catch(e => {
console.log('error', e);
if (metrics.config.debug) {
console.log("Got Error: " + e.message);
}
callback(e);
});
};
/**
* Send an event to Mixpanel, using the specified endpoint (e.g., track/import)
* @param {string} endpoint - API endpoint name
* @param {string} event - event name
* @param {object} properties - event properties
* @param {Function} [callback] - callback for request completion/error
*/
metrics.send_event_request = function (endpoint, event, properties, callback) {
properties.token = metrics.token;
properties.mp_lib = "node";
var data = {
event: event,
properties: properties
};
if (metrics.config.debug) {
console.log("Sending the following event to Mixpanel:\n", data);
}
metrics.send_request({
method: "GET",
endpoint: endpoint,
data: data
}, callback);
};
/**
* breaks array into equal-sized chunks, with the last chunk being the remainder
* @param {Array} arr
* @param {number} size
* @returns {Array}
*/
var chunk = function (arr, size) {
var chunks = [],
i = 0,
total = arr.length;
while (i < total) {
chunks.push(arr.slice(i, i += size));
}
return chunks;
};
/**
* sends events in batches
* @param {object} options
* @param {[{}]} options.event_list array of event objects
* @param {string} options.endpoint e.g. `/track` or `/import`
* @param {number} [options.max_concurrent_requests] limits concurrent async requests over the network
* @param {number} [options.max_batch_size] limits number of events sent to mixpanel per request
* @param {Function} [callback] callback receives array of errors if any
*
*/
var send_batch_requests = function (options, callback) {
var event_list = options.event_list,
endpoint = options.endpoint,
max_batch_size = options.max_batch_size ? Math.min(MAX_BATCH_SIZE, options.max_batch_size) : MAX_BATCH_SIZE,
// to maintain original intention of max_batch_size; if max_batch_size is greater than 50, we assume the user is trying to set max_concurrent_requests
max_concurrent_requests = options.max_concurrent_requests || options.max_batch_size > MAX_BATCH_SIZE && Math.ceil(options.max_batch_size / MAX_BATCH_SIZE),
event_batches = chunk(event_list, max_batch_size),
request_batches = max_concurrent_requests ? chunk(event_batches, max_concurrent_requests) : [event_batches],
total_event_batches = event_batches.length,
total_request_batches = request_batches.length;
/**
* sends a batch of events to mixpanel through http api
* @param {Array} batch
* @param {Function} cb
*/
function send_event_batch(batch, cb) {
if (batch.length > 0) {
batch = batch.map(function (event) {
var properties = event.properties;
if (endpoint === '/import' || event.properties.time) {
// usually there will be a time property, but not required for `/track` endpoint
event.properties.time = ensure_timestamp(event.properties.time);
}
event.properties.token = event.properties.token || metrics.token;
return event;
}); // must be a POST
metrics.send_request({
method: "POST",
endpoint: endpoint,
data: batch
}, cb);
}
}
/**
* Asynchronously sends batches of requests
* @param {number} index
*/
function send_next_request_batch(index) {
var request_batch = request_batches[index],
cb = function (errors, results) {
index += 1;
if (index === total_request_batches) {
callback && callback(errors, results);
} else {
send_next_request_batch(index);
}
};
async_all(request_batch, send_event_batch, cb);
} // init recursive function
send_next_request_batch(0);
if (metrics.config.debug) {
console.log("Sending " + event_list.length + " events to Mixpanel in " + total_event_batches + " batches of events and " + total_request_batches + " batches of requests");
}
};
/**
track(event, properties, callback)
---
this function sends an event to mixpanel.
event:string the event name
properties:object additional event properties to send
callback:function(err:Error) callback is called when the request is
finished or an error occurs
*/
metrics.track = function (event, properties, callback) {
if (!properties || typeof properties === "function") {
callback = properties;
properties = {};
} // time is optional for `track` but must be less than 5 days old if set
if (properties.time) {
properties.time = ensure_timestamp(properties.time);
if (properties.time < Date.now() / 1000 - TRACK_AGE_LIMIT) {
throw new Error("`track` not allowed for event more than 5 days old; use `mixpanel.import()`");
}
}
metrics.send_event_request("/track", event, properties, callback);
};
/**
* send a batch of events to mixpanel `track` endpoint: this should only be used if events are less than 5 days old
* @param {Array} event_list array of event objects to track
* @param {object} [options]
* @param {number} [options.max_concurrent_requests] number of concurrent http requests that can be made to mixpanel
* @param {number} [options.max_batch_size] number of events that can be sent to mixpanel per request
* @param {Function} [callback] callback receives array of errors if any
*/
metrics.track_batch = function (event_list, options, callback) {
options = options || {};
if (typeof options === 'function') {
callback = options;
options = {};
}
var batch_options = {
event_list: event_list,
endpoint: "/track",
max_concurrent_requests: options.max_concurrent_requests,
max_batch_size: options.max_batch_size
};
send_batch_requests(batch_options, callback);
};
/**
import(event, time, properties, callback)
---
This function sends an event to mixpanel using the import
endpoint. The time argument should be either a Date or Number,
and should signify the time the event occurred.
It is highly recommended that you specify the distinct_id
property for each event you import, otherwise the events will be
tied to the IP address of the sending machine.
For more information look at:
https://mixpanel.com/docs/api-documentation/importing-events-older-than-31-days
event:string the event name
time:date|number the time of the event
properties:object additional event properties to send
callback:function(err:Error) callback is called when the request is
finished or an error occurs
*/
metrics.import = function (event, time, properties, callback) {
if (!properties || typeof properties === "function") {
callback = properties;
properties = {};
}
properties.time = ensure_timestamp(time);
metrics.send_event_request("/import", event, properties, callback);
};
/**
import_batch(event_list, options, callback)
---
This function sends a list of events to mixpanel using the import
endpoint. The format of the event array should be:
[
{
"event": "event name",
"properties": {
"time": new Date(), // Number or Date; required for each event
"key": "val",
...
}
},
{
"event": "event name",
"properties": {
"time": new Date() // Number or Date; required for each event
}
},
...
]
See import() for further information about the import endpoint.
Options:
max_batch_size: the maximum number of events to be transmitted over
the network simultaneously. useful for capping bandwidth
usage.
max_concurrent_requests: the maximum number of concurrent http requests that
can be made to mixpanel; also useful for capping bandwidth.
N.B.: the Mixpanel API only accepts 50 events per request, so regardless
of max_batch_size, larger lists of events will be chunked further into
groups of 50.
event_list:array list of event names and properties
options:object optional batch configuration
callback:function(error_list:array) callback is called when the request is
finished or an error occurs
*/
metrics.import_batch = function (event_list, options, callback) {
var batch_options;
if (typeof options === "function" || !options) {
callback = options;
options = {};
}
batch_options = {
event_list: event_list,
endpoint: "/import",
max_concurrent_requests: options.max_concurrent_requests,
max_batch_size: options.max_batch_size
};
send_batch_requests(batch_options, callback);
};
/**
alias(distinct_id, alias)
---
This function creates an alias for distinct_id
For more information look at:
https://mixpanel.com/docs/integration-libraries/using-mixpanel-alias
distinct_id:string the current identifier
alias:string the future alias
*/
metrics.alias = function (distinct_id, alias, callback) {
var properties = {
distinct_id: distinct_id,
alias: alias
};
metrics.track('$create_alias', properties, callback);
};
metrics.identify = function (identified_id, anon_id, callback) {
var properties = {
distinct_id: identified_id,
$identified_id: identified_id,
$anon_id: anon_id
};
metrics.track('$identify', properties, callback);
};
metrics.groups = new MixpanelGroups(metrics);
metrics.people = new MixpanelPeople(metrics);
/**
set_config(config)
---
Modifies the mixpanel config
config:object an object with properties to override in the
mixpanel client config
*/
metrics.set_config = function (config) {
Object.assign(metrics.config, config);
if (config.host) {
// Split host into host and port
const _config$host$split = config.host.split(':'),
_config$host$split2 = _slicedToArray(_config$host$split, 2),
host = _config$host$split2[0],
port = _config$host$split2[1];
metrics.config.host = host;
if (port) {
metrics.config.port = Number(port);
}
}
};
if (config) {
metrics.set_config(config);
}
return metrics;
}; // module exporting
module.exports = {
Client: function (token) {
console.warn("The function `Client(token)` is deprecated. It is now called `init(token)`.");
return create_client(token);
},
init: create_client
};
/***/ }),
/***/ "./node_modules/@jlongster/mixpanel/lib/people.js":
/*!********************************************************!*\
!*** ./node_modules/@jlongster/mixpanel/lib/people.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
const _require = __webpack_require__(/*! ./profile_helpers */ "./node_modules/@jlongster/mixpanel/lib/profile_helpers.js"),
merge_modifiers = _require.merge_modifiers,
ProfileHelpers = _require.ProfileHelpers;
class MixpanelPeople extends ProfileHelpers() {
constructor(mp_instance) {
super();
this.mixpanel = mp_instance;
this.endpoint = '/engage';
}
/** people.set_once(distinct_id, prop, to, modifiers, callback)
---
The same as people.set but in the words of mixpanel:
mixpanel.people.set_once
" This method allows you to set a user attribute, only if
it is not currently set. It can be called multiple times
safely, so is perfect for storing things like the first date
you saw a user, or the referrer that brought them to your
website for the first time. "
*/
set_once(distinct_id, prop, to, modifiers, callback) {
const identifiers = {
$distinct_id: distinct_id
};
this._set(prop, to, modifiers, callback, {
identifiers,
set_once: true
});
}
/**
people.set(distinct_id, prop, to, modifiers, callback)
---
set properties on an user record in engage
usage:
mixpanel.people.set('bob', 'gender', 'm');
mixpanel.people.set('joe', {
'company': 'acme',
'plan': 'premium'
});
*/
set(distinct_id, prop, to, modifiers, callback) {
const identifiers = {
$distinct_id: distinct_id
};
this._set(prop, to, modifiers, callback, {
identifiers
});
}
/**
people.increment(distinct_id, prop, by, modifiers, callback)
---
increment/decrement properties on an user record in engage
usage:
mixpanel.people.increment('bob', 'page_views', 1);
// or, for convenience, if you're just incrementing a counter by 1, you can
// simply do
mixpanel.people.increment('bob', 'page_views');
// to decrement a counter, pass a negative number
mixpanel.people.increment('bob', 'credits_left', -1);
// like mixpanel.people.set(), you can increment multiple properties at once:
mixpanel.people.increment('bob', {
counter1: 1,
counter2: 3,
counter3: -2
});
*/
increment(distinct_id, prop, by, modifiers, callback) {
// TODO extract to ProfileHelpers
var $add = {};
if (typeof prop === 'object') {
if (typeof by === 'object') {
callback = modifiers;
modifiers = by;
} else {
callback = by;
}
for (const _ref of Object.entries(prop)) {
var _ref2 = _slicedToArray(_ref, 2);
const key = _ref2[0];
const val = _ref2[1];
if (isNaN(parseFloat(val))) {
if (this.mixpanel.config.debug) {
console.error("Invalid increment value passed to mixpanel.people.increment - must be a number");
console.error("Passed " + key + ":" + val);
}
} else {
$add[key] = val;
}
}
;
} else {
if (typeof by === 'number' || !by) {
by = by || 1;
$add[prop] = by;
if (typeof modifiers === 'function') {
callback = modifiers;
}
} else if (typeof by === 'function') {
callback = by;
$add[prop] = 1;
} else {
callback = modifiers;
modifiers = typeof by === 'object' ? by : {};
$add[prop] = 1;
}
}
var data = {
'$add': $add,
'$token': this.mixpanel.token,
'$distinct_id': distinct_id
};
data = merge_modifiers(data, modifiers);
if (this.mixpanel.config.debug) {
console.log("Sending the following data to Mixpanel (Engage):");
console.log(data);
}
this.mixpanel.send_request({
method: "GET",
endpoint: "/engage",
data: data
}, callback);
}
/**
people.append(distinct_id, prop, value, modifiers, callback)
---
Append a value to a list-valued people analytics property.
usage:
// append a value to a list, creating it if needed
mixpanel.people.append('bob', 'pages_visited', 'homepage');
// like mixpanel.people.set(), you can append multiple properties at once:
mixpanel.people.append('bob', {
list1: 'bob',
list2: 123
});
*/
append(distinct_id, prop, value, modifiers, callback) {
// TODO extract to ProfileHelpers
var $append = {};
if (typeof prop === 'object') {
if (typeof value === 'object') {
callback = modifiers;
modifiers = value;
} else {
callback = value;
}
Object.keys(prop).forEach(function (key) {
$append[key] = prop[key];
});
} else {
$append[prop] = value;
if (typeof modifiers === 'function') {
callback = modifiers;
}
}
var data = {
'$append': $append,
'$token': this.mixpanel.token,
'$distinct_id': distinct_id
};
data = merge_modifiers(data, modifiers);
if (this.mixpanel.config.debug) {
console.log("Sending the following data to Mixpanel (Engage):");
console.log(data);
}
this.mixpanel.send_request({
method: "GET",
endpoint: "/engage",
data: data
}, callback);
}
/**
people.track_charge(distinct_id, amount, properties, modifiers, callback)
---
Record that you have charged the current user a certain
amount of money.
usage:
// charge a user $29.99
mixpanel.people.track_charge('bob', 29.99);
// charge a user $19 on the 1st of february
mixpanel.people.track_charge('bob', 19, { '$time': new Date('feb 1 2012') });
*/
track_charge(distinct_id, amount, properties, modifiers, callback) {
if (typeof properties === 'function' || !properties) {
callback = properties || function () {};
properties = {};
} else {
if (typeof modifiers === 'function' || !modifiers) {
callback = modifiers || function () {};
if (properties.$ignore_time || properties.hasOwnProperty("$ip")) {
modifiers = {};
Object.keys(properties).forEach(function (key) {
modifiers[key] = properties[key];
delete properties[key];
});
}
}
}
if (typeof amount !== 'number') {
amount = parseFloat(amount);
if (isNaN(amount)) {
console.error("Invalid value passed to mixpanel.people.track_charge - must be a number");
return;
}
}
properties.$amount = amount;
if (properties.hasOwnProperty('$time')) {
var time = properties.$time;
if (Object.prototype.toString.call(time) === '[object Date]') {
properties.$time = time.toISOString();
}
}
var data = {
'$append': {
'$transactions': properties
},
'$token': this.mixpanel.token,
'$distinct_id': distinct_id
};
data = merge_modifiers(data, modifiers);
if (this.mixpanel.config.debug) {
console.log("Sending the following data to Mixpanel (Engage):");
console.log(data);
}
this.mixpanel.send_request({
method: "GET",
endpoint: "/engage",
data: data
}, callback);
}
/**
people.clear_charges(distinct_id, modifiers, callback)
---
Clear all the current user's transactions.
usage:
mixpanel.people.clear_charges('bob');
*/
clear_charges(distinct_id, modifiers, callback) {
var data = {
'$set': {
'$transactions': []
},
'$token': this.mixpanel.token,
'$distinct_id': distinct_id
};
if (typeof modifiers === 'function') {
callback = modifiers;
}
data = merge_modifiers(data, modifiers);
if (this.mixpanel.config.debug) {
console.log("Clearing this user's charges:", distinct_id);
}
this.mixpanel.send_request({
method: "GET",
endpoint: "/engage",
data: data
}, callback);
}
/**
people.delete_user(distinct_id, modifiers, callback)
---
delete an user record in engage
usage:
mixpanel.people.delete_user('bob');
*/
delete_user(distinct_id, modifiers, callback) {
const identifiers = {
$distinct_id: distinct_id
};
this._delete_profile({
identifiers,
modifiers,
callback
});
}
/**
people.remove(distinct_id, data, modifiers, callback)
---
remove a value from a list-valued user profile property.
usage:
mixpanel.people.remove('bob', {'browsers': 'firefox'});
mixpanel.people.remove('bob', {'browsers': 'chrome', 'os': 'linux'});
*/
remove(distinct_id, data, modifiers, callback) {
const identifiers = {
'$distinct_id': distinct_id
};
this._remove({
identifiers,
data,
modifiers,
callback
});
}
/**
people.union(distinct_id, data, modifiers, callback)
---
merge value(s) into a list-valued people analytics property.
usage:
mixpanel.people.union('bob', {'browsers': 'firefox'});
mixpanel.people.union('bob', {'browsers': ['chrome'], os: ['linux']});
*/
union(distinct_id, data, modifiers, callback) {
const identifiers = {
$distinct_id: distinct_id
};
this._union({
identifiers,
data,
modifiers,
callback
});
}
/**
people.unset(distinct_id, prop, modifiers, callback)
---
delete a property on an user record in engage
usage:
mixpanel.people.unset('bob', 'page_views');
mixpanel.people.unset('bob', ['page_views', 'last_login']);
*/
unset(distinct_id, prop, modifiers, callback) {
const identifiers = {
$distinct_id: distinct_id
};
this._unset({
identifiers,
prop,
modifiers,
callback
});
}
}
;
exports.MixpanelPeople = MixpanelPeople;
/***/ }),
/***/ "./node_modules/@jlongster/mixpanel/lib/profile_helpers.js":
/*!*****************************************************************!*\
!*** ./node_modules/@jlongster/mixpanel/lib/profile_helpers.js ***!
\*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* Mixin with profile-related helpers (for people and groups)
*/
const _require = __webpack_require__(/*! ./utils */ "./node_modules/@jlongster/mixpanel/lib/utils.js"),
ensure_timestamp = _require.ensure_timestamp;
function merge_modifiers(data, modifiers) {
if (modifiers) {
if (modifiers.$ignore_alias) {
data.$ignore_alias = modifiers.$ignore_alias;
}
if (modifiers.$ignore_time) {
data.$ignore_time = modifiers.$ignore_time;
}
if (modifiers.hasOwnProperty("$ip")) {
data.$ip = modifiers.$ip;
}
if (modifiers.hasOwnProperty("$time")) {
data.$time = ensure_timestamp(modifiers.$time);
}
}
return data;
}
;
exports.merge_modifiers = merge_modifiers;
exports.ProfileHelpers = (Base = Object) => class extends Base {
get token() {
return this.mixpanel.token;
}
get config() {
return this.mixpanel.config;
}
_set(prop, to, modifiers, callback, {
identifiers,
set_once = false
}) {
let $set = {};
if (typeof prop === 'object') {
if (typeof to === 'object') {
callback = modifiers;
modifiers = to;
} else {
callback = to;
}
$set = prop;
} else {
$set[prop] = to;
if (typeof modifiers === 'function' || !modifiers) {
callback = modifiers;
}
}
let data = _objectSpread({
'$token': this.token
}, identifiers);
const set_key = set_once ? "$set_once" : "$set";
data[set_key] = $set;
if ('ip' in $set) {
data.$ip = $set.ip;
delete $set.ip;
}
if ($set.$ignore_time) {
data.$ignore_time = $set.$ignore_time;
delete $set.$ignore_time;
}
data = merge_modifiers(data, modifiers);
if (this.config.debug) {
console.log(`Sending the following data to Mixpanel (${this.endpoint}):`);
console.log(data);
}
this.mixpanel.send_request({
method: "GET",
endpoint: this.endpoint,
data
}, callback);
}
_delete_profile({
identifiers,
modifiers,
callback
}) {
let data = _objectSpread({
'$delete': '',
'$token': this.token
}, identifiers);
if (typeof modifiers === 'function') {
callback = modifiers;
}
data = merge_modifiers(data, modifiers);
if (this.config.debug) {
console.log(`Deleting profile ${JSON.stringify(identifiers)}`);
}
this.mixpanel.send_request({
method: "GET",
endpoint: this.endpoint,
data
}, callback);
}
_remove({
identifiers,
data,
modifiers,
callback
}) {
let $remove = {};
if (typeof data !== 'object' || Array.isArray(data)) {
if (this.config.debug) {
console.error("Invalid value passed to #remove - data must be an object with scalar values");
}
return;
}
for (const _ref of Object.entries(data)) {
var _ref2 = _slicedToArray(_ref, 2);
const key = _ref2[0];
const val = _ref2[1];
if (typeof val === 'string' || typeof val === 'number') {
$remove[key] = val;
} else {
if (this.config.debug) {
console.error("Invalid argument passed to #remove - values must be scalar");
console.error("Passed " + key + ':', val);
}
return;
}
}
if (Object.keys($remove).length === 0) {
return;
}
data = _objectSpread({
'$remove': $remove,
'$token': this.token
}, identifiers);
if (typeof modifiers === 'function') {
callback = modifiers;
}
data = merge_modifiers(data, modifiers);
if (this.config.debug) {
console.log(`Sending the following data to Mixpanel (${this.endpoint}):`);
console.log(data);
}
this.mixpanel.send_request({
method: "GET",
endpoint: this.endpoint,
data
}, callback);
}
_union({
identifiers,
data,
modifiers,
callback
}) {
let $union = {};
if (typeof data !== 'object' || Array.isArray(data)) {
if (this.config.debug) {
console.error("Invalid value passed to #union - data must be an object with scalar or array values");
}
return;
}
for (const _ref3 of Object.entries(data)) {
var _ref4 = _slicedToArray(_ref3, 2);
const key = _ref4[0];
const val = _ref4[1];
if (Array.isArray(val)) {
var merge_values = val.filter(function (v) {
return typeof v === 'string' || typeof v === 'number';
});
if (merge_values.length > 0) {
$union[key] = merge_values;
}
} else if (typeof val === 'string' || typeof val === 'number') {
$union[key] = [val];
} else {
if (this.config.debug) {
console.error("Invalid argument passed to #union - values must be a scalar value or array");
console.error("Passed " + key + ':', val);
}
}
}
if (Object.keys($union).length === 0) {
return;
}
data = _objectSpread({
'$union': $union,
'$token': this.token
}, identifiers);
if (typeof modifiers === 'function') {
callback = modifiers;
}
data = merge_modifiers(data, modifiers);
if (this.config.debug) {
console.log(`Sending the following data to Mixpanel (${this.endpoint}):`);
console.log(data);
}
this.mixpanel.send_request({
method: "GET",
endpoint: this.endpoint,
data
}, callback);
}
_unset({
identifiers,
prop,
modifiers,
callback
}) {
let $unset = [];
if (Array.isArray(prop)) {
$unset = prop;
} else if (typeof prop === 'string') {
$unset = [prop];
} else {
if (this.config.debug) {
console.error("Invalid argument passed to #unset - must be a string or array");
console.error("Passed: " + prop);
}
return;
}
let data = _objectSpread({
'$unset': $unset,
'$token': this.token
}, identifiers);
if (typeof modifiers === 'function') {
callback = modifiers;
}
data = merge_modifiers(data, modifiers);
if (this.config.debug) {
console.log(`Sending the following data to Mixpanel (${this.endpoint}):`);
console.log(data);
}
this.mixpanel.send_request({
method: "GET",
endpoint: this.endpoint,
data
}, callback);
}
};
/***/ }),
/***/ "./node_modules/@jlongster/mixpanel/lib/utils.js":
/*!*******************************************************!*\
!*** ./node_modules/@jlongster/mixpanel/lib/utils.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
/**
* helper to wait for all callbacks to complete; similar to `Promise.all`
* exposed to metrics object for unit tests
* @param {Array} requests
* @param {Function} handler
* @param {Function} callback
*/
exports.async_all = function (requests, handler, callback) {
var total = requests.length,
errors = null,
results = [],
done = function (err, result) {
if (err) {
// errors are `null` unless there is an error, which allows for promisification
errors = errors || [];
errors.push(err);
}
results.push(result);
if (--total === 0) {
callback(errors, results);
}
};
if (total === 0) {
callback(errors, results);
} else {
for (var i = 0, l = requests.length; i < l; i++) {
handler(requests[i], done);
}
}
};
/**
* Validate type of time property, and convert to Unix timestamp if necessary
* @param {Date|number} time - value to check
* @returns {number} Unix timestamp
*/
exports.ensure_timestamp = function (time) {
if (!(time instanceof Date || typeof time === "number")) {
throw new Error("`time` property must be a Date or Unix timestamp and is only required for `import` endpoint");
}
return time instanceof Date ? Math.floor(time.getTime() / 1000) : time;
};
/***/ }),
/***/ "./node_modules/@rschedule/core/es2015/generators.js":
/*!***********************************************************!*\
!*** ./node_modules/@rschedule/core/es2015/generators.js ***!
\***********************************************************/
/*! exports provided: AddOperator, Calendar, Collection, CollectionIterator, Dates, IntersectionOperator, MergeDurationOperator, MergeDurationOperatorError, OccurrenceGenerator, OccurrenceIterator, Operator, Rule, RuleBase, Schedule, ScheduleBase, SplitDurationOperator, SplitDurationOperatorError, SubtractOperator, UniqueOperator, add, intersection, mergeDuration, splitDuration, subtract, unique */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AddOperator", function() { return AddOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Calendar", function() { return Calendar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Collection", function() { return Collection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollectionIterator", function() { return CollectionIterator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Dates", function() { return Dates; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IntersectionOperator", function() { return IntersectionOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeDurationOperator", function() { return MergeDurationOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeDurationOperatorError", function() { return MergeDurationOperatorError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OccurrenceGenerator", function() { return OccurrenceGenerator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OccurrenceIterator", function() { return OccurrenceIterator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Operator", function() { return Operator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Rule", function() { return Rule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RuleBase", function() { return RuleBase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Schedule", function() { return Schedule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScheduleBase", function() { return ScheduleBase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SplitDurationOperator", function() { return SplitDurationOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SplitDurationOperatorError", function() { return SplitDurationOperatorError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubtractOperator", function() { return SubtractOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UniqueOperator", function() { return UniqueOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "add", function() { return add; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "intersection", function() { return intersection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeDuration", function() { return mergeDuration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "splitDuration", function() { return splitDuration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subtract", function() { return subtract; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unique", function() { return unique; });
/* harmony import */ var _rschedule_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @rschedule/core */ "./node_modules/@rschedule/core/es2015/main.js");
class OccurrenceGenerator {
constructor(args = {}) {
this.timezone = args.timezone !== undefined ? args.timezone : null;
this.maxDuration = args.maxDuration || 0;
}
/** Returns the first occurrence or, if there are no occurrences, null. */
get firstDate() {
if (this._firstDate !== undefined) return this._firstDate;
const start = this._run().next().value;
this._firstDate = start ? this.dateAdapter.fromDateTime(start) : null;
return this._firstDate;
}
/** If generator is infinite, returns `null`. Otherwise returns the end date */
get lastDate() {
if (this._lastDate !== undefined) return this._lastDate;
if (this.isInfinite) {
this._lastDate = null;
return null;
}
const end = this._run({
reverse: true
}).next().value;
this._lastDate = end ? this.dateAdapter.fromDateTime(end) : null;
return this._lastDate;
}
pipe(...operators) {
return operators.reduce((prev, curr) => curr({
base: prev,
timezone: this.timezone
}), this);
}
/**
* Processes the object's rules/dates and returns an iterable for the occurrences.
*
* Options object:
* - `start` the date to begin iteration on
* - `end` the date to end iteration on
* - `take` the max number of dates to take before ending iteration
* - `reverse` whether to iterate in reverse or not
*
* Examples:
*
* ```
* const iterator = schedule.occurrences({ start: new Date(), take: 5 });
* for (const date of iterator) {
* // do stuff
* }
* iterator.toArray() // returns Date array
* iterator.next().value // returns next Date
* ```
*
*/
occurrences(args = {}) {
return new OccurrenceIterator(this, this.normalizeOccurrencesArgs(args));
}
/**
* Iterates over the object's occurrences and bundles them into collections
* with a specified granularity (default is `"YEARLY"`). Make sure to
* read about each option & combination of options below.
*
* Options object:
* - start?: DateAdapter
* - end?: DateAdapter
* - take?: number
* - reverse?: NOT SUPPORTED
* - granularity?: CollectionsGranularity
* - weekStart?: DateAdapter.Weekday
* - skipEmptyPeriods?: boolean
*
* Returned `Collection` object:
*
* - `dates` property containing an array of DateAdapter objects.
* - `granularity` property containing the granularity.
* - `CollectionsGranularity` === `RuleOptions.Frequency`.
* - default is `"YEARLY"`
* - `periodStart` property containing a DateAdapter equal to the period's
* start time.
* - `periodEnd` property containing a DateAdapter equal to the period's
* end time.
*
* #### Details:
*
* `collections()` always returns full periods. This means that the `start` argument is
* transformed to be the start of whatever period the `start` argument is in, and the
* `end` argument is transformed to be the end of whatever period the `end` argument is
* in.
*
* - Example: with granularity `"YEARLY"`, the `start` argument will be transformed to be the
* start of the year passed in the `start` argument, and the `end` argument will be transformed
* to be the end of the year passed in the `end` argument.
*
* By default, the `periodStart` value of `Collection` objects produced by this method increments linearly.
* This means the returned `Collection#dates` property may have length 0. This can be changed by
* passing the `skipEmptyPeriods: true` option, in which case the `periodStart` from one collection to the
* next can "jump".
*
* - Example 1: if your object's first occurrence is 2019/2/1 (February 1st) and you call
* `collection({skipEmptyPeriods: true, granularity: 'DAILY', start: new Date(2019,0,1)})`
* (so starting on January 1st), the first Collection produced will have a `periodStart` in February.
*
* - Example 2: if your object's first occurrence is 2019/2/1 (February 1st) and you call
* `collection({granularity: 'DAILY', start: new Date(2019,0,1)})`
* (so starting on January 1st), the first collection produced will have a `Collection#periodStart`
* of January 1st and have `Collection#dates === []`. Similarly, the next 30 collections produced
* (Jan 2nd - 31st) will all contain an empty array for the `dates` property. Then the February 1st
* `Collection` will contain dates.
*
* When giving a `take` argument to `collections()`, you are specifying
* the number of `Collection` objects to return (rather than occurrences).
*
* When choosing a granularity of `"WEEKLY"`, the `weekStart` option is required.
*
* When choosing a granularity of `"MONTHLY"`:
*
* - If the `weekStart` option *is not* present, will generate collections with
* the `periodStart` and `periodEnd` at the beginning and end of each month.
*
* - If the `weekStart` option *is* present, will generate collections with the
* `periodStart` equal to the start of the first week of the month, and the
* `periodEnd` equal to the end of the last week of the month. This behavior could be
* desired when rendering opportunities in a calendar view, where the calendar renders
* full weeks (which may result in the calendar displaying dates in the
* previous or next months).
*
*/
collections(args = {}) {
return new CollectionIterator(this, this.normalizeCollectionsArgs(args));
}
/**
* Returns true if an occurrence starts on or between the provided start/end
* datetimes. If the `excludeEnds` option is provided, then occurrences
* equal to the start/end times are ignored.
*
* If the occurrence generator has a duration, and `excludeEnds !== true`,
* and a `maxDuration` argument is supplied (either in the constructor or
* here), then any occurrence that's time overlaps with the start/end times
* return true.
*/
occursBetween(startInput, endInput, options = {}) {
const start = this.normalizeDateInput(startInput);
const end = this.normalizeDateInput(endInput);
if (this.hasDuration && !options.excludeEnds) {
const maxDuration = this.getMaxDuration('occursBetween', options);
const iterator = this._run({
start: start.subtract(maxDuration, 'millisecond'),
end,
reverse: true
});
for (const day of iterator) {
if (day.end.isBefore(start)) continue;
return true;
}
return false;
}
for (const day of this._run({
start,
end
})) {
if (options.excludeEnds) {
if (day.isEqual(start)) {
continue;
}
if (day.isEqual(end)) {
break;
}
}
return true;
}
return false;
}
occursOn(rawArgs) {
const args = this.normalizeOccursOnArgs(rawArgs);
if (args.weekday) {
if (this.isInfinite && !args.before) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ArgumentError"]('When calling `occursOn()` with a `weekday` argument ' + 'and an occurrence object that has infinite occurrences, ' + 'you must include a `before` argument as well.');
}
const start = args.after && (args.excludeEnds ? args.after.add(1, 'day') : args.after);
const end = args.before && (args.excludeEnds ? args.before.subtract(1, 'day') : args.before);
const iterator = this._run({
start,
end
});
let date = iterator.next().value;
if (!date) return false;
while (date) {
if (date.get('weekday') === args.weekday) {
return true;
}
date = iterator.next({
skipToDate: date.add(Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["getDifferenceBetweenWeekdays"])(date.get('weekday'), args.weekday), 'day').granularity('day')
}).value;
}
return false;
}
if (!args.date) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ArgumentError"](`"occursOn()" must be called with either a "date" or "weekday" argument`);
}
if (this.hasDuration) {
const maxDuration = this.getMaxDuration('occursOn', args);
const iterator = this._run({
start: args.date.subtract(maxDuration, 'millisecond'),
end: args.date
});
for (const date of iterator) {
if (date.end.isBefore(args.date)) continue;
if (date.isAfter(args.date)) return false;
return true;
}
return false;
}
for (const day of this._run({
start: args.date,
end: args.date
})) {
return !!day;
}
return false;
}
/**
* Returns true if an occurrence starts after the provided datetime.
* If the `excludeStart` option is provided, then occurrences
* equal to the provided datetime are ignored.
*
* If the occurrence generator has a duration, and `excludeStart !== true`,
* and a `maxDuration` argument is supplied (either in the constructor or
* here), then any occurrence that's end time is after/equal to the provided
* datetime return true.
*/
occursAfter(date, options = {}) {
const adapter = this.normalizeDateInput(date);
if (this.hasDuration && !options.excludeStart) {
const maxDuration = this.getMaxDuration('occursAfter', options);
const iterator = this._run({
start: adapter.subtract(maxDuration, 'millisecond')
});
for (const date of iterator) {
if (date.end.isBefore(adapter)) continue;
return true;
}
return false;
}
for (const day of this._run({
start: adapter
})) {
if (options.excludeStart && day.isEqual(adapter)) {
continue;
}
return true;
}
return false;
}
/**
* Returns true if an occurrence starts before the provided datetime.
* If the `excludeStart` option is provided, then occurrences
* equal to the provided datetime are ignored.
*
* If the occurrence generator has a duration, and `excludeStart` is
* also provided, then this will only return true if an occurrence
* both starts and ends before the provided datetime.
*/
occursBefore(date, options = {}) {
const adapter = this.normalizeDateInput(date);
if (this.hasDuration && options.excludeStart) {
for (const day of this._run({
end: adapter,
reverse: true
})) {
if (day.end.isAfterOrEqual(adapter)) continue;
return true;
}
return false;
}
for (const day of this._run({
end: adapter,
reverse: true
})) {
if (options.excludeStart && day.isEqual(adapter)) {
continue;
}
return true;
}
return false;
}
get dateAdapter() {
return _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapterBase"].adapter;
}
normalizeOccurrencesArgs(rawArgs) {
return Object.assign(Object.assign({}, rawArgs), {
start: this.normalizeDateInput(rawArgs.start),
end: this.normalizeDateInput(rawArgs.end)
});
}
normalizeCollectionsArgs(rawArgs) {
if (rawArgs.reverse !== undefined) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ArgumentError"]('`collections()` does not support the `reverse` option at this time.');
}
return Object.assign(Object.assign({}, rawArgs), {
start: this.normalizeDateInput(rawArgs.start),
end: this.normalizeDateInput(rawArgs.end)
});
}
normalizeOccursOnArgs(rawArgs = {}) {
return Object.assign(Object.assign({}, rawArgs), {
date: this.normalizeDateInput(rawArgs.date),
after: this.normalizeDateInput(rawArgs.after),
before: this.normalizeDateInput(rawArgs.before),
excludeDates: rawArgs.excludeDates && rawArgs.excludeDates.map(date => this.normalizeDateInput(date))
});
}
normalizeRunArgs(args) {
return Object.assign(Object.assign({}, args), {
start: this.normalizeDateInput(args.start),
end: this.normalizeDateInput(args.end)
});
}
normalizeDateInput(date) {
return date ? Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["dateInputToDateTime"])(date, this.timezone) : undefined;
}
normalizeDateInputToAdapter(date) {
if (!date) return;
return Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["dateInputToDateAdapter"])(date);
}
normalizeRunOutput(date) {
return Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["normalizeDateTimeTimezone"])(date, this.timezone);
}
getMaxDuration(method, options) {
const maxDuration = options.maxDuration || this.maxDuration;
if (!Number.isInteger(maxDuration)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ArgumentError"](`When an occurrence generator ` + `has a duration, a 'maxDuration' argument must be supplied ` + `to ${method}().`);
}
return maxDuration;
}
}
class OccurrenceIterator {
constructor(iterable, args) {
this.iterable = iterable;
this.args = args; // Need to assert the return type of these methods to prevent typescript from
// incorrectly reducing them to `DateAdapterBase & { generators: G }`.
this[Symbol.iterator] = () => this.occurrenceIterator();
this.iterator = iterable._run(args);
this.isInfinite = iterable.isInfinite;
}
next(args) {
return this.occurrenceIterator(args).next();
}
toArray() {
if (this.args.end || this.args.take || !this.isInfinite) {
return Array.from(this.occurrenceIterator());
}
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InfiniteLoopError"]('OccurrenceIterator#toArray() can only be called if the iterator ' + 'is not infinite, or you provide and `end` argument, or you provide ' + 'a `take` argument.');
}
*occurrenceIterator(rawArgs) {
let args = this.normalizeRunArgs(rawArgs);
let date = this.iterator.next(args).value;
while (date) {
const yieldArgs = yield this.normalizeDateOutput(date);
args = this.normalizeRunArgs(yieldArgs);
date = this.iterator.next(args).value;
}
return undefined;
}
normalizeRunArgs(args) {
return {
skipToDate: this.normalizeDateInput(args && args.skipToDate)
};
}
normalizeDateInput(date) {
return date ? Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["dateInputToDateTime"])(date, this.iterable.timezone) : undefined;
}
normalizeDateOutput(date) {
if (!date) return;
return date ? _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapterBase"].adapter.fromDateTime(date) : undefined;
}
}
class Collection {
constructor(dates = [], granularity, periodStart, periodEnd) {
this.dates = dates;
this.granularity = granularity;
this.periodStart = periodStart;
this.periodEnd = periodEnd;
}
}
class CollectionIterator {
constructor(iterable, args) {
this.iterable = iterable;
this.args = args;
this.granularity = 'year';
this[Symbol.iterator] = () => this.iterator;
if (args.granularity) {
this.granularity = args.granularity;
if (this.granularity === 'week' && !args.weekStart) {
throw new Error('"week" granularity requires `weekStart` arg');
}
}
if (args.weekStart) {
this.weekStart = args.weekStart;
}
if (args.reverse) {
throw new Error('`OccurrenceGenerator#collections()` does not support iterating in reverse. ' + 'Though `OccurrenceGenerator#occurrences()` does support iterating in reverse.');
} // Set the end arg, if present, to the end of the period.
this.args = Object.assign(Object.assign({}, args), {
start: args.start || iterable._run().next().value,
end: args.end && this.getPeriod(args.end).end
});
this.startDate = this.args.start && this.normalizeDateOutput(this.getPeriod(this.args.start).start) || null;
this.iterator = this.collectionIterator();
}
next() {
return this.iterator.next();
}
/**
* While `next()` and `[Symbol.iterator]` both share state,
* `toArray()` does not share state and always returns the whole
* collections array.
*/
toArray() {
if (this.args.end || this.args.take || !this.iterable.isInfinite) {
const collections = [];
for (const collection of this.collectionIterator()) {
collections.push(collection);
}
return collections;
}
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InfiniteLoopError"]('CollectionIterator#toArray() can only be called if the iterator ' + 'is not infinite, or you provide and `end` argument, or you provide ' + 'a `take` argument.');
}
normalizeDateOutput(date) {
if (!date) return;
return _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapterBase"].adapter.fromDateTime(date);
}
*collectionIterator() {
if (!this.startDate) return;
let iterator = this.occurrenceIterator();
let date = iterator.next().value;
if (!date) return; // `period` === `periodStart` unless the granularity
// is `MONTHLY` and a `weekStart` param was provided. In this case,
// period holds a date === the first of the current month while
// periodStart holds a date === the beginning of the first week of the month
// (which might be in the the previous month). Read the
// `OccurrenceGenerator#collections()` description for more info.
let period = this.getPeriod(this.args.start);
let dates = [];
let index = 0;
while (date && (this.args.take === undefined || this.args.take > index)) {
while (date && date.isBeforeOrEqual(period.end)) {
dates.push(date);
date = iterator.next().value;
}
yield new Collection(dates.map(date => this.normalizeDateOutput(date)), this.granularity, this.normalizeDateOutput(period.start), this.normalizeDateOutput(period.end));
if (!date) return;
dates = [];
period = !this.args.skipEmptyPeriods ? this.getPeriod(this.incrementPeriod(period.period)) : this.getPeriod(date); // With these args, periods may overlap and the same date may show up
// in two periods. Because of this, we need to reset the iterator
// (otherwise it won't return a date it has already returned).
if (this.granularity === 'month' && this.weekStart) {
iterator = this.iterable._run({
start: period.start,
end: this.args.end
});
date = iterator.next().value;
}
index++;
}
}
getPeriod(date) {
let start;
let end;
let period;
if (this.granularity === 'month' && this.weekStart) {
start = date.granularity('month').granularity('week', {
weekStart: this.weekStart
});
end = date.endGranularity('month').endGranularity('week', {
weekStart: this.weekStart
});
period = date.granularity('month');
} else {
start = date.granularity(this.granularity, {
weekStart: this.weekStart
});
end = date.endGranularity(this.granularity, {
weekStart: this.weekStart
});
period = start;
}
return {
start,
end,
period
};
}
incrementPeriod(date) {
return date.add(1, this.granularity);
}
occurrenceIterator() {
let start = this.args.start || this.iterable._run().next().value;
if (!start) return this.iterable._run(this.args);
start = this.getPeriod(start).start;
return this.iterable._run({
start,
end: this.args.end
});
}
}
class Operator extends OccurrenceGenerator {
constructor(streams, config) {
super(config);
this.streams = streams;
this.config = config;
this.timezone = config.timezone;
this.streams = streams.map(stream => stream instanceof Operator ? stream : stream.set('timezone', this.timezone));
this.isInfinite = this.calculateIsInfinite();
this.hasDuration = this.calculateHasDuration();
}
normalizeDateInput(date) {
if (!date) return;
return Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["dateInputToDateTime"])(date, this.timezone);
}
normalizeRunOutput(date) {
return Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["normalizeDateTimeTimezone"])(date, this.timezone);
}
}
/**
* Simple class that lets us access the `value`, `runArgs`, and `done`
* status of an OccurrenceGenerator iterator
*/
class IterableWrapper {
constructor(generator, runArgs) {
this.runArgs = runArgs;
this.stream = generator._run(this.runArgs);
this.next();
}
next(args) {
const _this$stream$next = this.stream.next(args),
done = _this$stream$next.done,
value = _this$stream$next.value;
this.done = typeof done === 'boolean' ? done : true;
this.value = value;
return {
done,
value
};
}
}
function processYieldArgs(streams, options = {}, yieldArgs = {}) {
if (!yieldArgs.skipToDate || streams.length === 0) return; // check for invalid `skipToDate` option
if (options.reverse ? streams.every(s => s.value.isBeforeOrEqual(yieldArgs.skipToDate)) : streams.every(s => s.value.isAfterOrEqual(yieldArgs.skipToDate))) {
throw new Error('A provided `skipToDate` option must be greater than the last yielded date ' + '(or smaller, in the case of reverse iteration)');
}
for (const stream of streams) {
if (stream.done) continue; // no point in calling `next()`
if (options.reverse ? stream.value.isBeforeOrEqual(yieldArgs.skipToDate) : stream.value.isAfterOrEqual(yieldArgs.skipToDate)) {
// This can happen there are two streams and one stream starts after the other finishes.
// Or, when iterating in reverse, when one stream ends before the other starts.
// In this case we don't want to call `next()` because it will throw an error.
// In both of these cases, calling `next()` won't do anything anyway.
continue;
}
stream.next(yieldArgs);
}
}
/** sorts ascending with completed iterables at the end */
function streamsComparer(a, b) {
if (a.done && b.done) return 0;
if (a.done) return 1;
if (b.done) return -1;
if (a.value.isAfter(b.value)) return 1;
return -1;
}
/** sorts descending with completed iterables at the start */
function streamsReverseComparer(a, b) {
if (a.done && b.done) return 0;
if (a.done) return -1;
if (b.done) return 1;
if (a.value.isAfter(b.value)) return -1;
return 1;
}
function selectNextIterable(streams, options = {}, yieldArgs = {}) {
processYieldArgs(streams, options, yieldArgs);
return streams.sort(options.reverse ? streamsReverseComparer : streamsComparer).filter(s => !s.done).shift();
}
function selectLastIterable(streams, options = {}, yieldArgs = {}) {
processYieldArgs(streams, options, yieldArgs);
return streams.sort(options.reverse ? streamsReverseComparer : streamsComparer).filter(s => !s.done).pop();
}
/**
* An operator function which accepts a spread of occurrence generators
* and adds their occurrences to the output.
*
* @param streams a spread of occurrence generators
*/
function add(...streams) {
return options => new AddOperator(streams, options);
}
class AddOperator extends Operator {
set(_, value) {
return new AddOperator(this.streams.map(stream => stream.set('timezone', value)), Object.assign(Object.assign({}, this.config), {
base: this.config.base && this.config.base.set('timezone', value),
timezone: value
}));
}
*_run(args = {}) {
const wrappedStreams = this.streams.map(input => new IterableWrapper(input, args));
if (this.config.base) {
wrappedStreams.push(new IterableWrapper(this.config.base, args));
}
if (wrappedStreams.length === 0) return;
let stream = selectNextIterable(wrappedStreams, args);
while (stream && !stream.done) {
// yield the current stream's value
const yieldArgs = yield this.normalizeRunOutput(stream.value);
if (!(yieldArgs && yieldArgs.skipToDate)) {
// iterate the current stream
stream.next();
} // select the next stream
stream = selectNextIterable(wrappedStreams, args, yieldArgs);
}
}
calculateIsInfinite() {
return this.config.base && this.config.base.isInfinite || this.streams.some(stream => stream.isInfinite);
}
calculateHasDuration() {
const streamsDuration = this.streams.every(stream => stream.hasDuration);
if (!this.config.base) return streamsDuration;
return this.config.base.hasDuration && streamsDuration;
}
}
class Calendar extends OccurrenceGenerator {
/**
*
* Create a new Calendar object with the specified options.
*
* ### Options
*
* - **timezone**: The timezone that yielded occurrences should be *displayed* in.
* Note, this one affects the *displayed* timezone of yielded occurrences.
* For rules, occurrences are first found using the unmodified rule
* config (including whatever timezone the `start` datetime is defined
* in), and then converted to the timezone specified here before being
* yielded. By default, the timezone is *local* time (`null`). So if you don't
* want your rules to be displayed in local time, you must supply a
* timezone argument.
* - **data**: arbitrary data you can associate with this Calendar. This
* is the only mutable property of `Calendar` objects.
* - **maxDuration**: currently unused.
* - **schedules**: either an occurrence generator, or an array of occurrence generators, which should
* be used to build up this Calendar's occurrences. The Calendar will display the union of occurrences
* its schedules produce.
*
*/
constructor(args = {}) {
super(args);
this.schedules = [];
this.data = args.data;
if (args.schedules) {
this.schedules = Array.isArray(args.schedules) ? args.schedules : [args.schedules];
this.schedules = this.schedules.map(schedule => schedule.set('timezone', this.timezone));
}
this.isInfinite = this.schedules.some(schedule => schedule.isInfinite);
this.hasDuration = this.schedules.every(schedule => schedule.hasDuration);
}
occurrences(args = {}) {
return new OccurrenceIterator(this, this.normalizeOccurrencesArgs(args));
}
collections(args = {}) {
return new CollectionIterator(this, this.normalizeCollectionsArgs(args));
}
set(prop, value, options) {
if (prop === 'timezone') {
return new Calendar({
schedules: this.schedules.map(schedule => schedule.set(prop, value, options)),
data: this.data,
timezone: value,
maxDuration: this.maxDuration
});
} else if (prop === 'schedules') {
return new Calendar({
schedules: Array.isArray(value) ? value : [value],
data: this.data,
timezone: this.timezone,
maxDuration: this.maxDuration
});
}
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ArgumentError"]('Unknown value for `prop`: ' + `"${prop}"`);
}
*_run(args = {}) {
if (this.schedules.length === 0) return;
const count = args.take;
delete args.take;
let iterator;
if (this.schedules.length === 1) {
iterator = this.schedules[0]._run(args);
} else {
iterator = new AddOperator(this.schedules, {
timezone: this.timezone
})._run(args);
}
let date = iterator.next().value;
let index = 0;
while (date && (count === undefined || count > index)) {
date = date.add(this, 'generator');
const yieldArgs = yield this.normalizeRunOutput(date);
date = iterator.next(yieldArgs).value;
index++;
}
return undefined;
}
}
class Dates extends OccurrenceGenerator {
constructor(args = {}) {
super(args);
this.adapters = [];
this.isInfinite = false;
this.maxDuration = 0;
this.datetimes = [];
this.data = args.data;
if (args.dates) {
this.adapters = args.dates.map(date => {
let adapter = this.normalizeDateInputToAdapter(date);
if (args.duration && !adapter.duration) {
adapter = adapter.set('duration', args.duration);
}
return adapter.set('timezone', this.timezone);
});
this.datetimes = this.adapters.map(adapter => adapter.toDateTime());
}
this.hasDuration = this.datetimes.every(date => !!date.duration);
if (this.hasDuration) {
this.maxDuration = this.adapters.reduce((prev, curr) => curr.duration > prev ? curr.duration : prev, 0);
}
}
get length() {
return this.adapters.length;
}
/** Returns the first occurrence or, if there are no occurrences, null. */
get firstDate() {
return this.adapters[0] || null;
}
/** Returns the last occurrence or, if there are no occurrences, null. */
get lastDate() {
return this.adapters[this.length - 1] || null;
}
occurrences(args = {}) {
return new OccurrenceIterator(this, this.normalizeOccurrencesArgs(args));
}
collections(args = {}) {
return new CollectionIterator(this, this.normalizeCollectionsArgs(args));
}
add(value) {
return new Dates({
dates: [...this.adapters, value],
timezone: this.timezone,
data: this.data
});
}
remove(value) {
const dates = this.adapters.slice();
const input = this.normalizeDateInputToAdapter(value);
const index = dates.findIndex(date => date.valueOf() === input.valueOf());
if (index >= 0) {
dates.splice(index, 1);
}
return new Dates({
dates,
timezone: this.timezone,
data: this.data
});
}
set(prop, value, options = {}) {
let timezone = this.timezone;
let dates = this.adapters.slice();
if (prop === 'timezone') {
if (value === this.timezone) return this;else if (options.keepLocalTime) {
dates = this.adapters.map(adapter => {
const json = adapter.toJSON();
json.timezone = value;
return this.dateAdapter.fromJSON(json);
});
}
timezone = value;
} else if (prop === 'dates') {
dates = value;
} else if (prop === 'duration') {
dates = dates.map(date => date.set('duration', value || 0));
} else {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ArgumentError"](`Unexpected prop argument "${prop}". Accepted values are "timezone" or "dates"`);
}
return new Dates({
dates,
data: this.data,
timezone
});
}
filter(fn) {
return new Dates({
dates: this.adapters.filter(fn),
data: this.data,
timezone: this.timezone
});
}
*_run(args = {}) {
let dates = this.datetimes.sort(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["dateTimeSortComparer"]);
if (args.start) {
dates = dates.filter(date => date.isAfterOrEqual(args.start));
}
if (args.end) {
dates = dates.filter(date => date.isBeforeOrEqual(args.end));
}
if (args.reverse) {
dates = dates.slice().reverse();
}
if (args.take) {
dates = dates.slice(0, args.take);
}
const dateCache = dates.slice();
let date = dateCache.shift();
let yieldArgs;
while (date) {
if (yieldArgs && yieldArgs.skipToDate && (args.reverse ? yieldArgs.skipToDate.isBefore(date) : yieldArgs.skipToDate.isAfter(date))) {
date = dateCache.shift();
continue;
}
date = date.add(this, 'generator');
yieldArgs = yield this.normalizeRunOutput(date); // Here, we are matching the behavior of the RecurrenceRulesIterator
if (yieldArgs && yieldArgs.skipToDate && (args.reverse ? yieldArgs.skipToDate.isAfterOrEqual(date) : yieldArgs.skipToDate.isBeforeOrEqual(date))) {
throw new Error('A provided `skipToDate` option must be greater than the last yielded date ' + '(or smaller, in the case of reverse iteration)');
}
date = dateCache.shift();
}
return undefined;
}
}
class InvalidDateAdapterError extends Error {}
let dateAdapterConfig;
class DateAdapterBase {
constructor(_date, options) {
this.duration = options && options.duration || 0;
this.generators = options && options.generators && options.generators.slice() || [];
if (!Number.isInteger(this.duration) || this.duration < 0) {
throw new InvalidDateAdapterError('duration must be a non-negative integer');
}
}
static set adapter(value) {
if (dateAdapterConfig) {
throw new Error(`"${dateAdapterConfig.name}" has already been configured.`);
}
dateAdapterConfig = value;
}
static get adapter() {
if (!dateAdapterConfig) {
throw new Error('No date adapter has been configured. See rSchedule docs.');
}
return dateAdapterConfig;
}
static isDate(_object) {
throw unimplementedError('isDate()');
}
static fromDate(_date, _options) {
throw unimplementedError('fromDate()');
}
static fromJSON(_json) {
throw unimplementedError('fromJSON()');
}
static fromDateTime(_datetime) {
throw unimplementedError('fromDateTime()');
}
toDateTime() {
const date = DateTime.fromJSON(Object.assign(Object.assign({}, this.toJSON()), {
generators: this.generators
}));
return date;
}
}
DateAdapterBase.hasTimezoneSupport = false;
function unimplementedError(name) {
return new Error(`You must implement the "${name}" method for this DateAdapter class`);
}
var DateAdapter;
(function (DateAdapter) {
DateAdapter.WEEKDAYS = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];
DateAdapter.MILLISECONDS_IN_SECOND = 1000;
DateAdapter.MILLISECONDS_IN_MINUTE = DateAdapter.MILLISECONDS_IN_SECOND * 60;
DateAdapter.MILLISECONDS_IN_HOUR = DateAdapter.MILLISECONDS_IN_MINUTE * 60;
DateAdapter.MILLISECONDS_IN_DAY = DateAdapter.MILLISECONDS_IN_HOUR * 24;
DateAdapter.MILLISECONDS_IN_WEEK = DateAdapter.MILLISECONDS_IN_DAY * 7;
})(DateAdapter || (DateAdapter = {}));
class InvalidDateTimeError extends Error {}
class DateTime {
constructor(date, timezone, duration, generators) {
this.date = new Date(date);
this.timezone = timezone || null;
this.duration = duration || 0;
this.generators = generators && generators.slice() || [];
if (!Number.isInteger(this.duration) || this.duration < 0) {
throw new InvalidDateTimeError('duration must be a non-negative integer');
}
this.assertIsValid();
} // /**
// * Similar to `Array.isArray()`, `isInstance()` provides a surefire method
// * of determining if an object is a `DateTime` by checking against the
// * global symbol registry.
// */
// static isInstance(object: any): object is DateTime {
// return !!(object && object[DATETIME_ID]);
// }
static fromJSON(json) {
const date = new Date(Date.UTC(json.year, json.month - 1, json.day, json.hour, json.minute, json.second, json.millisecond));
return new DateTime(date, json.timezone, json.duration, json.generators);
}
static fromDateAdapter(adapter) {
return DateTime.fromJSON(Object.assign(Object.assign({}, adapter.toJSON()), {
generators: adapter.generators
}));
}
/**
* Returns `undefined` if `duration` is `0`. Else returns
* the `end` date.
*/
get end() {
if (!this.duration) return;
if (this._end) return this._end;
this._end = this.add(this.duration, 'millisecond');
return this._end;
} // While we constrain the argument to be another DateAdapter in typescript
// we handle the case of someone passing in another type of object in javascript
isEqual(object) {
if (!object) {
return false;
}
assertSameTimeZone(this, object);
return this.valueOf() === object.valueOf();
}
isBefore(object) {
assertSameTimeZone(this, object);
return this.valueOf() < object.valueOf();
}
isBeforeOrEqual(object) {
assertSameTimeZone(this, object);
return this.valueOf() <= object.valueOf();
}
isAfter(object) {
assertSameTimeZone(this, object);
return this.valueOf() > object.valueOf();
}
isAfterOrEqual(object) {
assertSameTimeZone(this, object);
return this.valueOf() >= object.valueOf();
}
isOccurring(object) {
if (!this.duration) {
throw new Error('DateTime#isOccurring() is only applicable to DateTimes with durations');
}
assertSameTimeZone(this, object);
return object.isAfterOrEqual(this) && object.isBeforeOrEqual(this.add(this.duration, 'millisecond'));
}
add(amount, unit) {
switch (unit) {
case 'generator':
{
const generators = this.generators.slice();
generators.unshift(amount);
return new DateTime(this.date, this.timezone, this.duration, generators);
}
case 'year':
return this.forkDateTime(addUTCYears(this.date, amount));
case 'month':
return this.forkDateTime(addUTCMonths(this.date, amount));
case 'week':
return this.forkDateTime(addUTCWeeks(this.date, amount));
case 'day':
return this.forkDateTime(addUTCDays(this.date, amount));
case 'hour':
return this.forkDateTime(addUTCHours(this.date, amount));
case 'minute':
return this.forkDateTime(addUTCMinutes(this.date, amount));
case 'second':
return this.forkDateTime(addUTCSeconds(this.date, amount));
case 'millisecond':
return this.forkDateTime(addUTCMilliseconds(this.date, amount));
default:
throw new Error('Invalid unit provided to `DateTime#add`');
}
}
subtract(amount, unit) {
switch (unit) {
case 'year':
return this.forkDateTime(subUTCYears(this.date, amount));
case 'month':
return this.forkDateTime(subUTCMonths(this.date, amount));
case 'week':
return this.forkDateTime(subUTCWeeks(this.date, amount));
case 'day':
return this.forkDateTime(subUTCDays(this.date, amount));
case 'hour':
return this.forkDateTime(subUTCHours(this.date, amount));
case 'minute':
return this.forkDateTime(subUTCMinutes(this.date, amount));
case 'second':
return this.forkDateTime(subUTCSeconds(this.date, amount));
case 'millisecond':
return this.forkDateTime(subUTCMilliseconds(this.date, amount));
default:
throw new Error('Invalid unit provided to `DateTime#subtract`');
}
}
get(unit) {
switch (unit) {
case 'year':
return this.date.getUTCFullYear();
case 'month':
return this.date.getUTCMonth() + 1;
case 'yearday':
return getUTCYearDay(this.date);
case 'weekday':
return DateAdapter.WEEKDAYS[this.date.getUTCDay()];
case 'day':
return this.date.getUTCDate();
case 'hour':
return this.date.getUTCHours();
case 'minute':
return this.date.getUTCMinutes();
case 'second':
return this.date.getUTCSeconds();
case 'millisecond':
return this.date.getUTCMilliseconds();
default:
throw new Error('Invalid unit provided to `DateTime#set`');
}
}
set(unit, value) {
if (unit === 'duration') {
return new DateTime(this.date, this.timezone, value, this.generators);
}
if (unit === 'generators') {
return new DateTime(this.date, this.timezone, this.duration, value);
}
let date = new Date(this.date);
switch (unit) {
case 'year':
date.setUTCFullYear(value);
break;
case 'month':
{
// If the current day of the month
// is greater than days in the month we are moving to, we need to also
// set the day to the end of that month.
const length = monthLength(value, date.getUTCFullYear());
const day = date.getUTCDate();
if (day > length) {
date.setUTCDate(1);
date.setUTCMonth(value);
date = subUTCDays(date, 1);
} else {
date.setUTCMonth(value - 1);
}
break;
}
case 'day':
date.setUTCDate(value);
break;
case 'hour':
date.setUTCHours(value);
break;
case 'minute':
date.setUTCMinutes(value);
break;
case 'second':
date.setUTCSeconds(value);
break;
case 'millisecond':
date.setUTCMilliseconds(value);
break;
default:
throw new Error('Invalid unit provided to `DateTime#set`');
}
return this.forkDateTime(date);
}
granularity(granularity, opt = {}) {
let date = this.forkDateTime(this.date);
switch (granularity) {
case 'year':
date = date.set('month', 1);
case 'month':
date = date.set('day', 1);
break;
case 'week':
date = setDateToStartOfWeek(date, opt.weekStart);
}
switch (granularity) {
case 'year':
case 'month':
case 'week':
case 'day':
date = date.set('hour', 0);
case 'hour':
date = date.set('minute', 0);
case 'minute':
date = date.set('second', 0);
case 'second':
date = date.set('millisecond', 0);
case 'millisecond':
return date;
default:
throw new Error('Invalid granularity provided to `DateTime#granularity`: ' + granularity);
}
}
endGranularity(granularity, opt = {}) {
let date = this.forkDateTime(this.date);
switch (granularity) {
case 'year':
date = date.set('month', 12);
case 'month':
date = date.set('day', monthLength(date.get('month'), date.get('year')));
break;
case 'week':
date = setDateToEndOfWeek(date, opt.weekStart);
}
switch (granularity) {
case 'year':
case 'month':
case 'week':
case 'day':
date = date.set('hour', 23);
case 'hour':
date = date.set('minute', 59);
case 'minute':
date = date.set('second', 59);
case 'second':
date = date.set('millisecond', 999);
case 'millisecond':
return date;
default:
throw new Error('Invalid granularity provided to `DateTime#granularity`: ' + granularity);
}
}
toISOString() {
return this.date.toISOString();
}
toDateTime() {
return this;
}
toJSON() {
const json = {
timezone: this.timezone,
year: this.get('year'),
month: this.get('month'),
day: this.get('day'),
hour: this.get('hour'),
minute: this.get('minute'),
second: this.get('second'),
millisecond: this.get('millisecond')
};
if (this.duration) {
json.duration = this.duration;
}
return json;
}
valueOf() {
return this.date.valueOf();
}
assertIsValid() {
if (isNaN(this.valueOf())) {
throw new InvalidDateTimeError('DateTime has invalid date.');
}
return true;
}
forkDateTime(date) {
return new DateTime(date, this.timezone, this.duration, this.generators);
}
}
function assertSameTimeZone(x, y) {
if (x.timezone !== y.timezone) {
throw new InvalidDateTimeError('Attempted to compare a datetime to another date in a different timezone: ' + JSON.stringify(x) + ' and ' + JSON.stringify(y));
}
return true;
}
function setDateToStartOfWeek(date, wkst) {
const index = orderedWeekdays(wkst).indexOf(date.get('weekday'));
return date.subtract(index, 'day');
}
function setDateToEndOfWeek(date, wkst) {
const index = orderedWeekdays(wkst).indexOf(date.get('weekday'));
return date.add(6 - index, 'day');
}
function orderedWeekdays(wkst = 'SU') {
const wkdays = DateAdapter.WEEKDAYS.slice();
let index = wkdays.indexOf(wkst);
while (index !== 0) {
shiftArray(wkdays);
index--;
}
return wkdays;
}
function shiftArray(array, from = 'first') {
if (array.length === 0) {
return array;
} else if (from === 'first') {
array.push(array.shift());
} else {
array.unshift(array.pop());
}
return array;
}
/**
* Returns the days in the given month.
*
* @param month base-1
* @param year
*/
function monthLength(month, year) {
const block = {
1: 31,
2: getDaysInFebruary(year),
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
};
return block[month];
}
function getDaysInFebruary(year) {
return isLeapYear(year) ? 29 : 28;
} // taken from date-fn
function isLeapYear(year) {
return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
}
function getUTCYearDay(now) {
const start = new Date(Date.UTC(now.getUTCFullYear(), 0, 1));
const diff = now.valueOf() - start.valueOf();
return 1 + Math.floor(diff / DateAdapter.MILLISECONDS_IN_DAY);
}
/**
* These functions are basically lifted from `date-fns`, but changed
* to use the UTC date methods, which `date-fns` doesn't support.
*/
function toInteger(input) {
if (input === null || input === true || input === false) {
return NaN;
}
const int = Number(input);
if (isNaN(int)) {
return int;
}
return int < 0 ? Math.ceil(int) : Math.floor(int);
}
function addMilliseconds(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
const timestamp = dirtyDate.valueOf();
const amount = toInteger(dirtyAmount);
return new Date(timestamp + amount);
}
function addUTCYears(date, input) {
const amount = toInteger(input);
return addUTCMonths(date, amount * 12);
}
function addUTCMonths(date, input) {
const amount = toInteger(input);
date = new Date(date);
const desiredMonth = date.getUTCMonth() + amount;
const dateWithDesiredMonth = new Date(0);
dateWithDesiredMonth.setUTCFullYear(date.getUTCFullYear(), desiredMonth, 1);
dateWithDesiredMonth.setUTCHours(0, 0, 0, 0);
const daysInMonth = monthLength(dateWithDesiredMonth.getUTCMonth() + 1, dateWithDesiredMonth.getUTCFullYear()); // Set the last day of the new month
// if the original date was the last day of the longer month
date.setUTCMonth(desiredMonth, Math.min(daysInMonth, date.getUTCDate()));
return date;
}
function addUTCWeeks(date, input) {
const amount = toInteger(input);
const days = amount * 7;
return addUTCDays(date, days);
}
function addUTCDays(date, input) {
// by adding milliseconds rather than days, we supress the native Date object's automatic
// daylight savings time conversions which we don't want in UTC mode
return addUTCMilliseconds(date, toInteger(input) * DateAdapter.MILLISECONDS_IN_DAY);
}
function addUTCHours(date, input) {
const amount = toInteger(input);
return addMilliseconds(date, amount * DateAdapter.MILLISECONDS_IN_HOUR);
}
function addUTCMinutes(date, input) {
const amount = toInteger(input);
return addMilliseconds(date, amount * DateAdapter.MILLISECONDS_IN_MINUTE);
}
function addUTCSeconds(date, input) {
const amount = toInteger(input);
return addMilliseconds(date, amount * DateAdapter.MILLISECONDS_IN_SECOND);
}
function addUTCMilliseconds(date, input) {
const amount = toInteger(input);
const timestamp = date.getTime();
return new Date(timestamp + amount);
}
function subUTCYears(date, amount) {
return addUTCYears(date, -amount);
}
function subUTCMonths(date, amount) {
return addUTCMonths(date, -amount);
}
function subUTCWeeks(date, amount) {
return addUTCWeeks(date, -amount);
}
function subUTCDays(date, amount) {
return addUTCDays(date, -amount);
}
function subUTCHours(date, amount) {
return addUTCHours(date, -amount);
}
function subUTCMinutes(date, amount) {
return addUTCMinutes(date, -amount);
}
function subUTCSeconds(date, amount) {
return addUTCSeconds(date, -amount);
}
function subUTCMilliseconds(date, amount) {
return addUTCMilliseconds(date, -amount);
} // export function normalizeDateInput<T extends DateAdapter>(
// dateAdapter: DateAdapterConstructor<T>,
// input: DateInput<T>,
// timezone: string | null,
// ): DateTime {
// if (input instanceof DateTime) {
// if (input.timezone !== timezone) {
// return dateAdapter
// .fromDateTime(input)
// .set('timezone', timezone)
// .toDateTime();
// }
// return input;
// }
// return input instanceof DateAdapter
// ? input.set('timezone', timezone).toDateTime()
// : new dateAdapter(input).toDateTime();
// }
function normalizeDateTimeTimezone(date, timezone) {
if (date.timezone !== timezone) {
return DateAdapterBase.adapter.fromDateTime(date).set('timezone', timezone).toDateTime();
}
return date;
}
class RuleBase extends OccurrenceGenerator {
constructor(recurrenceRules, config, options = {}) {
super(options);
this.recurrenceRules = recurrenceRules;
this.options = Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["cloneRuleOptions"])(config);
this.normOptions = Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["normalizeRuleOptions"])(this.recurrenceRules, this.options);
this.timezone = options.timezone !== undefined ? options.timezone : this.normOptions.start.timezone;
this.data = options.data;
this.hasDuration = !!config.duration;
if (this.hasDuration) this.duration = config.duration;
this.isInfinite = this.normOptions.end === undefined && this.normOptions.count === undefined;
}
occurrences(args = {}) {
return new OccurrenceIterator(this, this.normalizeOccurrencesArgs(args));
}
collections(args = {}) {
return new CollectionIterator(this, this.normalizeCollectionsArgs(args));
}
*_run(rawArgs = {}) {
const args = this.normalizeRunArgs(rawArgs);
const iterator = new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RecurrenceRulesIterator"](Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["recurrenceRulesReducer"])(this.recurrenceRules), this.normOptions, args);
let date = iterator.next().value;
let index = 0;
while (date && (args.take === undefined || index < args.take)) {
index++;
date = date.add(this, 'generator');
const yieldArgs = yield this.normalizeRunOutput(date);
if (yieldArgs === null || yieldArgs === void 0 ? void 0 : yieldArgs.skipToDate) {
// The RecurrenceRuleIterator might have a different timezone from the rule.
// Because of this, the yieldArgs will not properly be normalized by the
// OccurrenceIterator, so we need to do it here
date = iterator.next(Object.assign(Object.assign({}, yieldArgs), {
skipToDate: normalizeDateTimeTimezone(yieldArgs.skipToDate, iterator.start.timezone)
})).value;
} else {
// theoretically, the yieldArgs are undefined here
// maybe in the future there will be other yieldArg options though
date = iterator.next(yieldArgs).value;
}
}
return undefined;
}
}
class Rule extends RuleBase {
/**
* Create a new Rule object with the specified rule config and options.
*
* ### Options
*
* - **timezone**: the timezone that yielded occurrences should be in. Note,
* this does not change the rule config. Occurrences are first found using
* the unmodified rule config, and then converted to the timezone specified
* here before being yielded.
* - **data**: arbitrary data you can associate with this rule. This
* is the only mutable property of `Rule` objects.
*
* ### Rule Config
*
* - #### frequency
*
* The frequency rule part identifies the type of recurrence rule. Valid values
* include `"SECONDLY"`, `"MINUTELY"`, `"HOURLY"`, `"DAILY"`, `"WEEKLY"`,
* `"MONTHLY"`, or `"YEARLY"`.
*
* - #### start
*
* The start of the rule (not necessarily the first occurrence).
* Either a `DateAdapter` instance, date object, or `DateTime` object.
* The type of date object depends on the `DateAdapter` class used for this
* `Rule`.
*
* - #### end?
*
* The end of the rule (not necessarily the last occurrence).
* Either a `DateAdapter` instance, date object, or `DateTime` object.
* The type of date object depends on the `DateAdapter` class used for this
* `Rule`.
*
* - #### duration?
*
* A length of time expressed in milliseconds.
*
* - #### interval?
*
* The interval rule part contains a positive integer representing at
* which intervals the recurrence rule repeats. The default value is
* `1`, meaning every second for a SECONDLY rule, every minute for a
* MINUTELY rule, every hour for an HOURLY rule, every day for a
* DAILY rule, every week for a WEEKLY rule, every month for a
* MONTHLY rule, and every year for a YEARLY rule. For example,
* within a DAILY rule, a value of `8` means every eight days.
*
* - #### count?
*
* The count rule part defines the number of occurrences at which to
* range-bound the recurrence. `count` and `end` are both two different
* ways of specifying how a recurrence completes.
*
* - #### weekStart?
*
* The weekStart rule part specifies the day on which the workweek starts.
* Valid values are `"MO"`, `"TU"`, `"WE"`, `"TH"`, `"FR"`, `"SA"`, and `"SU"`.
* This is significant when a WEEKLY rule has an interval greater than 1,
* and a `byDayOfWeek` rule part is specified. The
* default value is `"MO"`.
*
* - #### bySecondOfMinute?
*
* The bySecondOfMinute rule part expects an array of seconds
* within a minute. Valid values are 0 to 60.
*
* - #### byMinuteOfHour?
*
* The byMinuteOfHour rule part expects an array of minutes within an hour.
* Valid values are 0 to 59.
*
* - #### byHourOfDay?
*
* The byHourOfDay rule part expects an array of hours of the day.
* Valid values are 0 to 23.
*
* - #### byDayOfWeek?
*
* *note: the byDayOfWeek rule part is kinda complex. Blame the ICAL spec.*
*
* The byDayOfWeek rule part expects an array. Each array entry can
* be a day of the week (`"SU"`, `"MO"` , `"TU"`, `"WE"`, `"TH"`,
* `"FR"`, `"SA"`). If the rule's `frequency` is either MONTHLY or YEARLY,
* Any entry can also be a tuple where the first value of the tuple is a
* day of the week and the second value is an positive/negative integer
* (e.g. `["SU", 1]`). In this case, the number indicates the nth occurrence of
* the specified day within the MONTHLY or YEARLY rule.
*
* The behavior of byDayOfWeek changes depending on the `frequency`
* of the rule.
*
* Within a MONTHLY rule, `["MO", 1]` represents the first Monday
* within the month, whereas `["MO", -1]` represents the last Monday
* of the month.
*
* Within a YEARLY rule, the numeric value in a byDayOfWeek tuple entry
* corresponds to an offset within the month when the byMonthOfYear rule part is
* present, and corresponds to an offset within the year otherwise.
*
* Regardless of rule `frequency`, if a byDayOfWeek entry is a string
* (rather than a tuple), it means "all of these days" within the specified
* frequency (e.g. within a MONTHLY rule, `"MO"` represents all Mondays within
* the month).
*
* - #### byDayOfMonth?
*
* The byDayOfMonth rule part expects an array of days
* of the month. Valid values are 1 to 31 or -31 to -1.
*
* For example, -10 represents the tenth to the last day of the month.
* The byDayOfMonth rule part *must not* be specified when the rule's
* `frequency` is set to WEEKLY.
*
* - #### byMonthOfYear?
*
* The byMonthOfYear rule part expects an array of months
* of the year. Valid values are 1 to 12.
*
*/
constructor(config, options = {}) {
super(Rule.recurrenceRules, config, options);
}
set(prop, value, tzoptions = {}) {
let options = Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["cloneRuleOptions"])(this.options);
let timezone = this.timezone;
if (prop === 'timezone') {
if (value === this.timezone && !tzoptions.keepLocalTime) return this;else if (tzoptions.keepLocalTime) {
const json = this.normalizeDateInput(options.start).toJSON();
json.timezone = value;
const adapter = this.dateAdapter.fromJSON(json); // prettier-ignore
options.start = options.start instanceof this.dateAdapter ? adapter : options.start instanceof _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateTime"] ? adapter.toDateTime() : adapter.date;
}
timezone = value;
} else if (prop === 'options') {
options = value;
} else {
options[prop] = value;
}
return new Rule(options, {
data: this.data,
maxDuration: this.maxDuration,
timezone
});
}
}
Rule.recurrenceRules = [];
class ScheduleBase extends OccurrenceGenerator {
/**
* Create a new Schedule object with the specified options.
*
* The order of precidence for rrules, rdates, exrules, and exdates is:
*
* 1. rrules are included
* 2. exrules are excluded
* 3. rdates are included
* 4. exdates are excluded
*
*/
constructor(options) {
super(options);
this.data = options.data;
}
occurrences(args = {}) {
return new OccurrenceIterator(this, this.normalizeOccurrencesArgs(args));
}
collections(args = {}) {
return new CollectionIterator(this, this.normalizeCollectionsArgs(args));
}
*_run(args = {}) {
const count = args.take;
delete args.take;
const iterator = this.occurrenceStream._run(args);
let date = iterator.next().value;
let index = 0;
while (date && (count === undefined || count > index)) {
date = date.add(this, 'generator');
const yieldArgs = yield this.normalizeRunOutput(date);
date = iterator.next(yieldArgs).value;
index++;
}
return undefined;
}
}
/**
* An operator function which accepts a spread of occurrence generators
* and removes their occurrences from the output.
*
* @param streams a spread of occurrence generators
*/
function subtract(...streams) {
return options => new SubtractOperator(streams, options);
}
class SubtractOperator extends Operator {
/** Not actually used but necessary for IRunnable interface */
set(_, value) {
return new SubtractOperator(this.streams.map(stream => stream.set('timezone', value)), Object.assign(Object.assign({}, this.config), {
base: this.config.base && this.config.base.set('timezone', value),
timezone: value
}));
}
*_run(args = {}) {
if (!this.config.base) return;
const inclusion = new IterableWrapper(this.config.base, args);
const exclusion = new IterableWrapper(new AddOperator(this.streams, {
timezone: this.config.timezone
}), args);
cycleStreams(inclusion, exclusion, args);
while (!inclusion.done) {
const yieldArgs = yield this.normalizeRunOutput(inclusion.value);
if (!(yieldArgs && yieldArgs.skipToDate)) {
inclusion.next();
}
cycleStreams(inclusion, exclusion, args, yieldArgs);
}
}
calculateIsInfinite() {
return !!(this.config.base && this.config.base.isInfinite);
}
calculateHasDuration() {
return !!(this.config.base && this.config.base.hasDuration);
}
}
function cycleStreams(inclusion, exclusion, options = {}, yieldArgs = {}) {
processYieldArgs([inclusion, exclusion], options, yieldArgs);
iterateExclusion(inclusion, exclusion, options);
while (!inclusion.done && !exclusion.done && inclusion.value.isEqual(exclusion.value)) {
inclusion.next();
iterateExclusion(inclusion, exclusion, options);
}
}
function iterateExclusion(inclusion, exclusion, options = {}) {
if (options.reverse) {
while (!exclusion.done && !inclusion.done && exclusion.value.isAfter(inclusion.value)) {
exclusion.next();
}
return;
}
while (!exclusion.done && !inclusion.done && exclusion.value.isBefore(inclusion.value)) {
exclusion.next();
}
}
/**
* An operator function which deduplicates an occurrence stream. Occurrence
* `duration` is currently ignored.
*/
function unique() {
return options => new UniqueOperator([], options);
}
class UniqueOperator extends Operator {
/** Not actually used but necessary for IRunnable interface */
set(_, value) {
return new UniqueOperator([], Object.assign(Object.assign({}, this.config), {
base: this.config.base && this.config.base.set('timezone', value),
timezone: value
}));
}
*_run(args = {}) {
if (!this.config.base) return;
const stream = new IterableWrapper(this.config.base, args);
while (!stream.done) {
const yieldArgs = yield this.normalizeRunOutput(stream.value);
const lastValue = stream.value; // iterate the current stream
stream.next(yieldArgs);
while (!(yieldArgs && yieldArgs.skipToDate) && !stream.done && stream.value.isEqual(lastValue)) {
stream.next();
}
}
}
calculateIsInfinite() {
return !!(this.config.base && this.config.base.isInfinite);
}
calculateHasDuration() {
return !!(this.config.base && this.config.base.hasDuration);
}
}
class Schedule extends ScheduleBase {
/**
* Create a new Schedule object with the specified options.
*
* The order of precidence for rrules, rdates, exrules, and exdates is:
*
* 1. rrules are included
* 2. exrules are excluded
* 3. rdates are included
* 4. exdates are excluded
*
* ### Options
*
* - **timezone**: The timezone that yielded occurrences should be *displayed* in.
* Note, this one affects the *displayed* timezone of yielded occurrences.
* For rules, occurrences are first found using the unmodified rule
* config (including whatever timezone the `start` datetime is defined
* in), and then converted to the timezone specified here before being
* yielded. By default, the timezone is *local* time (`null`). So if you don't
* want your rules to be displayed in local time, you must supply a
* timezone argument.
* - **data**: arbitrary data you can associate with this Schedule. This
* is the only mutable property of `Schedule` objects.
* - **maxDuration**: currently unused.
* - **rrules**: rules specifying when occurrences happen. See the "Rule Config"
* section below.
* - **rdates**: individual dates that should be _included_ in the schedule.
* - **exdates**: individual dates that should be _excluded_ from the schedule.
* - **exrules**: rules specifying when occurrences shouldn't happen. See the
* "Rule Config" section below.
*
* ### Rule Config
*
* - #### frequency
*
* The frequency rule part identifies the type of recurrence rule. Valid values
* include `"SECONDLY"`, `"MINUTELY"`, `"HOURLY"`, `"DAILY"`, `"WEEKLY"`,
* `"MONTHLY"`, or `"YEARLY"`.
*
* - #### start
*
* The start of the rule (not necessarily the first occurrence).
* Either a `DateAdapter` instance, date object, or `DateTime` object.
* The type of date object depends on the `DateAdapter` class used for this
* `Rule`.
*
* - #### end?
*
* The end of the rule (not necessarily the last occurrence).
* Either a `DateAdapter` instance, date object, or `DateTime` object.
* The type of date object depends on the `DateAdapter` class used for this
* `Rule`.
*
* - #### duration?
*
* A length of time expressed in milliseconds.
*
* - #### interval?
*
* The interval rule part contains a positive integer representing at
* which intervals the recurrence rule repeats. The default value is
* `1`, meaning every second for a SECONDLY rule, every minute for a
* MINUTELY rule, every hour for an HOURLY rule, every day for a
* DAILY rule, every week for a WEEKLY rule, every month for a
* MONTHLY rule, and every year for a YEARLY rule. For example,
* within a DAILY rule, a value of `8` means every eight days.
*
* - #### count?
*
* The count rule part defines the number of occurrences at which to
* range-bound the recurrence. `count` and `end` are both two different
* ways of specifying how a recurrence completes.
*
* - #### weekStart?
*
* The weekStart rule part specifies the day on which the workweek starts.
* Valid values are `"MO"`, `"TU"`, `"WE"`, `"TH"`, `"FR"`, `"SA"`, and `"SU"`.
* This is significant when a WEEKLY rule has an interval greater than 1,
* and a `byDayOfWeek` rule part is specified. The
* default value is `"MO"`.
*
* - #### bySecondOfMinute?
*
* The bySecondOfMinute rule part expects an array of seconds
* within a minute. Valid values are 0 to 60.
*
* - #### byMinuteOfHour?
*
* The byMinuteOfHour rule part expects an array of minutes within an hour.
* Valid values are 0 to 59.
*
* - #### byHourOfDay?
*
* The byHourOfDay rule part expects an array of hours of the day.
* Valid values are 0 to 23.
*
* - #### byDayOfWeek?
*
* *note: the byDayOfWeek rule part is kinda complex. Blame the ICAL spec.*
*
* The byDayOfWeek rule part expects an array. Each array entry can
* be a day of the week (`"SU"`, `"MO"` , `"TU"`, `"WE"`, `"TH"`,
* `"FR"`, `"SA"`). If the rule's `frequency` is either MONTHLY or YEARLY,
* Any entry can also be a tuple where the first value of the tuple is a
* day of the week and the second value is an positive/negative integer
* (e.g. `["SU", 1]`). In this case, the number indicates the nth occurrence of
* the specified day within the MONTHLY or YEARLY rule.
*
* The behavior of byDayOfWeek changes depending on the `frequency`
* of the rule.
*
* Within a MONTHLY rule, `["MO", 1]` represents the first Monday
* within the month, whereas `["MO", -1]` represents the last Monday
* of the month.
*
* Within a YEARLY rule, the numeric value in a byDayOfWeek tuple entry
* corresponds to an offset within the month when the byMonthOfYear rule part is
* present, and corresponds to an offset within the year otherwise.
*
* Regardless of rule `frequency`, if a byDayOfWeek entry is a string
* (rather than a tuple), it means "all of these days" within the specified
* frequency (e.g. within a MONTHLY rule, `"MO"` represents all Mondays within
* the month).
*
* - #### byDayOfMonth?
*
* The byDayOfMonth rule part expects an array of days
* of the month. Valid values are 1 to 31 or -31 to -1.
*
* For example, -10 represents the tenth to the last day of the month.
* The byDayOfMonth rule part *must not* be specified when the rule's
* `frequency` is set to WEEKLY.
*
* - #### byMonthOfYear?
*
* The byMonthOfYear rule part expects an array of months
* of the year. Valid values are 1 to 12.
*
*/
constructor(options = {}) {
super(options);
this.rrules = [];
this.exrules = [];
for (const prop of ['rrules', 'exrules']) {
const arg = options[prop];
if (arg) {
this[prop] = arg.map(ruleArgs => {
if (ruleArgs instanceof Rule) {
return ruleArgs.set('timezone', this.timezone);
} else {
return new Rule(ruleArgs, {
timezone: this.timezone
});
}
});
}
}
for (const prop of ['rdates', 'exdates']) {
const arg = options[prop];
if (arg) {
this[prop] = arg instanceof Dates ? arg.set('timezone', this.timezone) : new Dates({
dates: arg,
timezone: this.timezone
});
} else {
this[prop] = new Dates({
timezone: this.timezone
});
}
}
this.hasDuration = this.rrules.every(rule => rule.hasDuration) && this.exrules.every(rule => rule.hasDuration) && this.rdates.hasDuration && this.exdates.hasDuration;
this.isInfinite = this.rrules.some(rule => rule.isInfinite);
this.occurrenceStream = [add(...this.rrules), subtract(...this.exrules), add(this.rdates), subtract(this.exdates), unique()].reduce((prev, curr) => curr({
base: prev,
timezone: this.timezone
}), undefined);
}
add(prop, value) {
const rrules = this.rrules.slice();
const exrules = this.exrules.slice();
let rdates = this.rdates;
let exdates = this.exdates;
switch (prop) {
case 'rrule':
rrules.push(value);
break;
case 'exrule':
exrules.push(value);
break;
case 'rdate':
rdates = this.rdates.add(value);
break;
case 'exdate':
exdates = this.exdates.add(value);
break;
}
return new Schedule({
timezone: this.timezone,
data: this.data,
rrules,
exrules,
rdates,
exdates
});
}
remove(prop, value) {
let rrules = this.rrules;
let exrules = this.exrules;
let rdates = this.rdates;
let exdates = this.exdates;
switch (prop) {
case 'rrule':
rrules = rrules.filter(rule => rule !== value);
break;
case 'exrule':
exrules = exrules.filter(rule => rule !== value);
break;
case 'rdate':
rdates = this.rdates.remove(value);
break;
case 'exdate':
exdates = this.exdates.remove(value);
break;
}
return new Schedule({
timezone: this.timezone,
data: this.data,
rrules,
exrules,
rdates,
exdates
});
}
set(prop, value, options = {}) {
let timezone = this.timezone;
let rrules = this.rrules;
let exrules = this.exrules;
let rdates = this.rdates;
let exdates = this.exdates;
switch (prop) {
case 'timezone':
if (value === this.timezone && !options.keepLocalTime) return this;else if (options.keepLocalTime) {
rrules = rrules.map(rule => rule.set('timezone', value, options));
exrules = exrules.map(rule => rule.set('timezone', value, options));
rdates = rdates.set('timezone', value, options);
exdates = exdates.set('timezone', value, options);
}
timezone = value;
break;
case 'rrules':
rrules = value;
break;
case 'exrules':
exrules = value;
break;
case 'rdates':
rdates = value;
break;
case 'exdates':
exdates = value;
break;
}
return new Schedule({
timezone,
data: this.data,
rrules,
exrules,
rdates,
exdates
});
}
}
/**
* An operator function, which takes a spread of occurrence generators and only
* returns the dates which intersect every occurrence generator.
*
* Because it's possible for all the generators to never intersect,
* and because the intersection operator can't detect this lack of intersection,
* you must call `intersection()` with a `{maxFailedIterations: number}` argument.
* For convenience, you can globally set `RScheduleConfig.defaultMaxFailedIterations`.
* Without further information, I'd probably set `defaultMaxFailedIterations = 50`.
*
* The `maxFailedIterations` argument caps the number of iterations the operator will
* run through without finding a single valid occurrence. If this number is reached, the operator will
* stop iterating (preventing a possible infinite loop).
*
* - Note: `maxFailedIterations` caps the number of iterations which
* *fail to turn up a single valid occurrence*. Every time a valid occurrence is returned,
* the current iteration count is reset to 0.
*
*/
function intersection(args) {
return options => new IntersectionOperator(args, options);
}
class IntersectionOperator extends Operator {
constructor(args, config) {
super(args.streams, config);
if (this.isInfinite) {
this.maxFailedIterations = args.maxFailedIterations || IntersectionOperator.defaultMaxFailedIterations;
if (!this.maxFailedIterations) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ArgumentError"]('The IntersectionOperator must be provided ' + 'a `maxFailedIterations` argument when it is built from schedules of infinite length. ' + 'This argument is used to ensure that the IntersectionOperator does not enter ' + 'an infinite loop because the underlying schedules never intersect. ' + 'If the `maxFailedIterations` count is reached it will be assumed that ' + 'all valid occurrences have been found and iteration will end without error.' + 'Without additional information, "50" is probably a good ' + '`maxFailedIterations` value. ' + 'If the schedules are not of infinite length, `maxFailedIterations` is ignored. ' + 'Note also that you can provide a `defaultMaxFailedIterations` number via ' + 'IntersectionOperator.defaultMaxFailedIterations.');
}
}
}
set(_, value) {
return new IntersectionOperator({
maxFailedIterations: this.maxFailedIterations,
streams: this.streams.map(stream => stream.set('timezone', value))
}, Object.assign(Object.assign({}, this.config), {
base: this.config.base && this.config.base.set('timezone', value),
timezone: value
}));
}
*_run(args = {}) {
const streams = this.streams.map(stream => new IterableWrapper(stream, args));
if (this.config.base) {
streams.push(new IterableWrapper(this.config.base, args));
}
if (streams.length === 0) return;
const hasEndDate = !!(!this.isInfinite || args.reverse || args.end);
if (!cycleStreams$1(streams, undefined, Object.assign(Object.assign({}, args), {
hasEndDate,
iteration: 0,
maxIterations: this.maxFailedIterations
}))) {
return;
}
let stream = selectNextIterable(streams, args);
while (stream) {
const yieldArgs = yield this.normalizeRunOutput(stream.value);
const lastValidDate = stream.value;
if (!(yieldArgs === null || yieldArgs === void 0 ? void 0 : yieldArgs.skipToDate)) {
// iterate the current stream
stream.next();
}
if (!cycleStreams$1(streams, lastValidDate, Object.assign(Object.assign({}, args), {
hasEndDate,
iteration: 0,
maxIterations: this.maxFailedIterations
}), yieldArgs)) {
return;
} // The call to `cycleStreams()`, above, has already called
// selectNextIterable with the `yieldArgs`
stream = selectNextIterable(streams, args);
}
}
calculateIsInfinite() {
// Note: Array#every() === true when length === 0
if (!this.config.base) {
if (this.streams.length === 0) return false;
return this.streams.every(stream => stream.isInfinite);
} else if (this.streams.length === 0) return this.config.base.isInfinite;
return this.config.base.isInfinite && this.streams.every(stream => stream.isInfinite);
}
calculateHasDuration() {
const streamsDuration = this.streams.every(stream => stream.hasDuration);
if (!this.config.base) return streamsDuration;
return this.config.base.hasDuration && streamsDuration;
}
}
function cycleStreams$1(streams, lastValidDate, options, yieldArgs) {
const next = selectNextIterable(streams, options, yieldArgs);
if (!next) return false;
if (lastValidDate && next.value.isEqual(lastValidDate)) return true;
if (streams.some(stream => stream.done)) return false;
if (streams.every(stream => stream.value.isEqual(next.value))) return true;
options.iteration++;
if (options.maxIterations && !options.hasEndDate && options.iteration > options.maxIterations) {
return false;
} // Since not all of the streams are equal, we grab the last stream...
const last = selectLastIterable(streams, options); // ...and skip all the other streams so they are equal or past the last one
streams.forEach(stream => {
// Because streams can have multiple, identical dates in a row,
// we don't want to `skipToDate` if the provided date is equal to the current date.
if (last.value.isEqual(stream.value)) return;
stream.next({
skipToDate: last.value
});
}); // then we repeat
return cycleStreams$1(streams, lastValidDate, options);
}
class DurationIterableWrapper extends IterableWrapper {
constructor(generator, runArgs) {
super(generator, runArgs);
this.workingValue = this.value;
this.next();
}
}
class MergeDurationOperatorError extends Error {}
/**
* An operator function which takes an occurrence stream with
* `hasDuration === true` and merges occurrences which have overlapping
* start and end times.
*
* Because it's possible for all the occurrences in the stream to have
* overlapping start and end times, you must provide a `maxDuration`
* argument that represents the maximum possible duration for a single
* occurrence. If this duration is exceeded, a `MergeDurationOperatorError`
* will be thrown.
*
* - For your convenience, you can globally set a default
* `MergeDurationOperator#maxDuration` via
* `RScheduleConfig.MergeDurationOperator.defaultMaxDuration`.
*
* Usage example:
*
* ```typescript
* const MILLISECONDS_IN_HOUR = 1000 * 60 * 60;
*
* const dates = new Dates({
* dates: [
* new StandardDateAdapter(new Date(2010, 10, 10, 13), { duration: MILLISECONDS_IN_HOUR * 1 }),
* new StandardDateAdapter(new Date(2010, 10, 11, 13), { duration: MILLISECONDS_IN_HOUR * 2 }),
* new StandardDateAdapter(new Date(2010, 10, 11, 14), { duration: MILLISECONDS_IN_HOUR * 2 }),
* new StandardDateAdapter(new Date(2010, 10, 12, 13), { duration: MILLISECONDS_IN_HOUR * 1 }),
* ],
* dateAdpter: StandardDateAdapter,
* }).pipe(
* mergeDuration({
* maxDuration: MILLISECONDS_IN_HOUR * 24
* })
* )
*
* dates.occurrences().toArray() === [
* new StandardDateAdapter(new Date(2010, 10, 10, 13), { duration: MILLISECONDS_IN_HOUR * 1 }),
* new StandardDateAdapter(new Date(2010, 10, 11, 13), { duration: MILLISECONDS_IN_HOUR * 3 }),
* new StandardDateAdapter(new Date(2010, 10, 12, 13), { duration: MILLISECONDS_IN_HOUR * 1 }),
* ]
* ```
*/
function mergeDuration(args) {
return options => new MergeDurationOperator(args, options);
}
class MergeDurationOperator extends Operator {
constructor(args, config) {
super([], config);
this.maxDuration = args.maxDuration;
if (config.base && !config.base.hasDuration) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ArgumentError"]('Base stream provided to MergeDurationOperator does not have an associated duration. ' + 'The MergeDurationOperator can only be used with streams which have a duration. ');
}
}
/** Not actually used but necessary for IRunnable interface */
set(_, value) {
return new MergeDurationOperator({
maxDuration: this.maxDuration
}, Object.assign(Object.assign({}, this.config), {
base: this.config.base && this.config.base.set('timezone', value),
timezone: value
}));
}
_run(args = {}) {
return args.reverse ? this.reverseRun(args) : this.forwardRun(args);
}
calculateIsInfinite() {
return !!(this.config.base && this.config.base.isInfinite);
}
calculateHasDuration() {
return true;
}
*forwardRun(args = {}) {
if (!this.config.base) return; // We want to find occurrences that end after the provided
// `start` time even if they begin before the provided `start`
// time. Because of this, we must begin iterating `maxDuration`
// before the provided start time.
let checkFromStart = args.start;
if (args.start) {
checkFromStart = args.start.subtract(this.maxDuration, 'millisecond');
}
let checkFromEnd = args.end;
if (args.end) {
checkFromEnd = args.end.add(this.maxDuration, 'millisecond');
}
const stream = new DurationIterableWrapper(this.config.base, Object.assign(Object.assign({}, args), {
start: checkFromStart,
end: checkFromEnd
}));
let yieldArgs; // checking `stream.workingValue` because when `stream.done === true`
// `stream.workingValue` will not have been yielded yet
while (stream.workingValue) {
// TODO(@john.carroll.p): figure out how to handle `DateTime#generators` for merged `DateTimes`
while (!stream.done && stream.workingValue.end.isAfterOrEqual(stream.value)) {
if (stream.workingValue.duration > this.maxDuration) {
throw new MergeDurationOperatorError(`MergeDurationOperatorError: Occurrence duration exceeded maxDuration of ` + this.maxDuration);
}
if (stream.value.end.isAfter(stream.workingValue.end)) {
const diff = stream.value.end.valueOf() - stream.workingValue.end.valueOf();
stream.workingValue = stream.workingValue.set('duration', stream.workingValue.duration + diff);
}
stream.next();
} // check to make sure the occurrence we are about to yield ends after the
// provided start time.
if (args.start && stream.workingValue.end.isBefore(args.start)) {
stream.workingValue = stream.value;
stream.next();
continue;
} // make sure the occurrence we are about to yield ends after the
// provided skipToDate
if ((yieldArgs === null || yieldArgs === void 0 ? void 0 : yieldArgs.skipToDate) && stream.workingValue.end.isBefore(yieldArgs.skipToDate)) {
stream.workingValue = stream.value;
stream.next();
continue;
} // make sure we are not after the user requested `end` time.
if (args.end && stream.workingValue && stream.workingValue.isAfter(args.end)) {
break;
}
if (stream.workingValue.duration > this.maxDuration) {
throw new MergeDurationOperatorError(`MergeDurationOperatorError: Occurrence duration exceeded maxDuration of ` + this.maxDuration);
}
yieldArgs = yield this.normalizeRunOutput(stream.workingValue);
if ((yieldArgs === null || yieldArgs === void 0 ? void 0 : yieldArgs.skipToDate) && stream.workingValue.isAfterOrEqual(yieldArgs.skipToDate)) {
throw new Error('A provided `skipToDate` option must be greater than the last yielded date ' + '(or smaller, in the case of reverse iteration)');
}
stream.workingValue = stream.value;
stream.next();
}
}
*reverseRun(args = {}) {
if (!this.config.base) return; // We want to find occurrences that end after the provided
// `start` time even if they begin before the provided `start`
// time. Because of this, we must begin iterating `maxDuration`
// before the provided start time.
let checkFromStart = args.start;
if (args.start) {
checkFromStart = args.start.subtract(this.maxDuration, 'millisecond');
}
let checkFromEnd = args.end;
if (args.end) {
checkFromEnd = args.end.add(this.maxDuration, 'millisecond');
}
const stream = new DurationIterableWrapper(this.config.base, Object.assign(Object.assign({}, args), {
start: checkFromStart,
end: checkFromEnd
}));
let yieldArgs; // checking `stream.workingValue` because when `stream.done === true`
// `stream.workingValue` will not have been yielded yet
while (stream.workingValue) {
// TODO(@john.carroll.p): figure out how to handle `DateTime#generators` for merged `DateTimes`
while (!stream.done && stream.workingValue.isBeforeOrEqual(stream.value.end)) {
if (stream.workingValue.duration > this.maxDuration) {
throw new MergeDurationOperatorError(`MergeDurationOperatorError: Occurrence duration exceeded maxDuration of ` + this.maxDuration);
}
if (stream.value.isBefore(stream.workingValue) || stream.value.end.isAfter(stream.workingValue.end)) {
if (stream.value.end.isAfter(stream.workingValue.end)) {
// `stream.workingValue` is a subset of `stream.value`
// so simply replace `stream.workingValue` with `stream.value`
stream.workingValue = stream.value;
} else {
const diff = stream.workingValue.valueOf() - stream.value.valueOf();
stream.workingValue = stream.value.set('duration', stream.workingValue.duration + diff);
}
}
stream.next();
} // check to make sure the occurrence we are about to yield starts before the
// provided start time.
if (args.start && stream.workingValue.end.isBefore(args.start)) {
break;
}
if (yieldArgs && yieldArgs.skipToDate && stream.workingValue.end.isBefore(yieldArgs.skipToDate)) {
stream.workingValue = stream.value;
stream.next();
continue;
} // make sure we are not after the user requested `end` time.
if (args.end && stream.workingValue && stream.workingValue.isAfter(args.end)) {
stream.workingValue = stream.value;
stream.next();
continue;
}
if (stream.workingValue.duration > this.maxDuration) {
throw new MergeDurationOperatorError(`MergeDurationOperatorError: Occurrence duration exceeded maxDuration of ` + this.maxDuration);
}
yieldArgs = yield this.normalizeRunOutput(stream.workingValue);
if (yieldArgs && yieldArgs.skipToDate && stream.workingValue.end.isBeforeOrEqual(yieldArgs.skipToDate)) {
throw new Error('A provided `skipToDate` option must be greater than the last yielded date ' + '(or smaller, in the case of reverse iteration)');
}
stream.workingValue = stream.value;
stream.next();
}
}
}
class SplitDurationOperatorError extends Error {}
/**
* An operator function which takes an occurrence stream with
* `hasDuration === true` and passes occurrences through a splitting
* function. One usecase for this operator is to dynamically break up
* occurrences with a large duration into several smaller occurrences.
*
* You must provide a `maxDuration` argument that represents the
* maximum possible duration for a single occurrence. If this
* duration is exceeded, a `SplitDurationOperatorError` will be
* thrown.
*
* - For your convenience, you can globally set a default
* `SplitDurationOperator#maxDuration` via
* `RScheduleConfig.SplitDurationOperator.defaultMaxDuration`.
*
* Usage example:
*
* ```typescript
* const MILLISECONDS_IN_HOUR = 1000 * 60 * 60;
*
* const splitFn = (date: DateTime) => {
* if (date.duration > MILLISECONDS_IN_HOUR) {
* const diff = date.duration! / 2;
*
* return [
* date.set('duration', diff),
* date.add(diff, 'millisecond').set('duration', diff),
* ];
* }
*
* return [date];
* };
*
* const dates = new Dates({
* dates: [
* new StandardDateAdapter(new Date(2010, 10, 10, 13), { duration: MILLISECONDS_IN_HOUR * 1 }),
* new StandardDateAdapter(new Date(2010, 10, 11, 13), { duration: MILLISECONDS_IN_HOUR * 2 }),
* ],
* dateAdpter: StandardDateAdapter,
* }).pipe(
* splitDuration({
* splitFn,
* maxDuration: MILLISECONDS_IN_HOUR * 1
* })
* )
*
* expect(dates.occurrences().toArray()).toEqual([
* new StandardDateAdapter(new Date(2010, 10, 10, 13), { duration: MILLISECONDS_IN_HOUR * 1 }),
* new StandardDateAdapter(new Date(2010, 10, 11, 13), { duration: MILLISECONDS_IN_HOUR * 1 }),
* new StandardDateAdapter(new Date(2010, 10, 11, 14), { duration: MILLISECONDS_IN_HOUR * 1 }),
* ])
* ```
*/
function splitDuration(args) {
return options => new SplitDurationOperator(args, options);
}
class SplitDurationOperator extends Operator {
constructor(args, config) {
super([], config);
this.splitFn = args.splitFn;
this.maxDuration = args.maxDuration;
if (config.base && !config.base.hasDuration) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ArgumentError"]('Base stream provided to SplitDurationOperator does not have an associated duration. ' + 'The SplitDurationOperator can only be used with streams which have a duration.');
}
}
/** Not actually used but necessary for IRunnable interface */
set(_, value) {
return new SplitDurationOperator({
maxDuration: this.maxDuration,
splitFn: this.splitFn
}, Object.assign(Object.assign({}, this.config), {
base: this.config.base && this.config.base.set('timezone', value),
timezone: value
}));
}
*_run(args = {}) {
if (!this.config.base) return;
const reverse = args.reverse || false; // We want to find occurrences that end after the provided
// `start` time even if they begin before the provided `start`
// time. Because of this, we add `maxDuration` to
// the provided start time.
let checkFromStart = args.start;
if (args.start) {
checkFromStart = args.start.subtract(this.maxDuration, 'millisecond');
} // same goes for `end` time as with `start` time.
let checkFromEnd = args.end;
if (args.end) {
checkFromEnd = args.end.add(this.maxDuration, 'millisecond');
}
const stream = new IterableWrapper(this.config.base, Object.assign(Object.assign({}, args), {
start: checkFromStart,
end: checkFromEnd
}));
let yieldArgs;
const datesBucket = [];
while (!stream.done || datesBucket[0] && datesBucket[0][0]) {
/**
* Example:
* 10am - 2pm -> 10am - 12pm, 12pm - 2pm
* 11am - 3pm -> 11am - 1pm, 1pm - 3pm
* 2pm - 4pm -> 2pm - 3pm, 3pm - 4pm
*/
if (!(datesBucket[0] && datesBucket[0][0])) {
// we're out of dates
datesBucket.push(this.splitDate(stream.value, reverse));
stream.next();
}
while (!stream.done && (reverse ? datesBucket[0].some(date => date.isBeforeOrEqual(stream.value.end)) : datesBucket[0].some(date => date.isAfterOrEqual(stream.value)))) {
datesBucket.push(this.splitDate(stream.value, reverse));
stream.next();
}
let selectedDate = datesBucket[0] && datesBucket[0][0];
let bucketIndex = -1;
let selectedBucketIndex = 0;
let dateIndex = -1;
let selectedDateIndex = 0; // find the next date as well as its location in the datesBucket
for (const bucket of datesBucket) {
bucketIndex++;
dateIndex = -1;
for (const date of bucket) {
dateIndex++;
let dateShouldComeNext;
if (reverse) {
dateShouldComeNext = date.isAfter(selectedDate) || date.isEqual(selectedDate) && date.duration > selectedDate.duration;
} else {
dateShouldComeNext = date.isBefore(selectedDate) || date.isEqual(selectedDate) && date.duration < selectedDate.duration;
}
if (dateShouldComeNext) {
selectedDate = date;
selectedBucketIndex = bucketIndex;
selectedDateIndex = dateIndex;
break;
}
}
}
datesBucket[selectedBucketIndex].splice(selectedDateIndex, 1);
if (datesBucket[selectedBucketIndex].length === 0) {
datesBucket.splice(selectedBucketIndex, 1);
} // If we've been yieldedArgs from the last cycle, check to see
// that the selectedDate honors the `skipToDate` requirement
// if not, discard this selectedDate
if (yieldArgs && yieldArgs.skipToDate && selectedDate && !datePastEnd(selectedDate, args) && !datePastSkipToDate(selectedDate, yieldArgs.skipToDate, args)) {
continue;
} // because we subtracted `maxDuration` to the base iterator's start time,
// check to make sure the selectedDate we are about to yield should
// actually be yielded (it may be before the provided `start` time).
// If not, discard the selectedDate.
if (args.start && selectedDate.end.isBefore(args.start)) {
if (reverse) break;
continue;
} // because we added `maxDuration` to the base iterator's end time,
// check to make sure the selectedDate we are about to yield should
// actually be yielded (it may be after the provided `end` time).
// If not, end iteration.
if (args.end && selectedDate.isAfter(args.end)) {
if (reverse) continue;
break;
}
if (selectedDate.duration > this.maxDuration) {
throw new SplitDurationOperatorError(`SplitDurationOperatorError: Occurrence duration exceeded maxDuration of ` + this.maxDuration);
}
yieldArgs = yield this.normalizeRunOutput(selectedDate);
if (yieldArgs && yieldArgs.skipToDate && (args.reverse ? selectedDate.isBeforeOrEqual(yieldArgs.skipToDate) : selectedDate.isAfterOrEqual(yieldArgs.skipToDate))) {
throw new Error('A provided `skipToDate` option must be greater than the last yielded date ' + '(or smaller, in the case of reverse iteration)');
}
}
}
calculateIsInfinite() {
return !!(this.config.base && this.config.base.isInfinite);
}
calculateHasDuration() {
return true;
}
splitDate(date, reverse) {
const dates = this.splitFn(date);
let valid;
if (dates.length === 0) {
valid = false;
} else if (dates.length === 1) {
valid = date.duration === dates[0].duration;
} else {
valid = date.duration === dates.reduce((prev, curr) => prev + curr.duration, 0);
}
if (!valid) {
throw new Error('The provided SplitDurationOperator split function ' + 'must return an array of DateTimes with length > 0 ' + 'where the total duration of the new dates equals the duration of ' + 'the original date.');
}
dates.sort(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["dateTimeSortComparer"]);
if (reverse) {
dates.reverse();
}
return dates;
}
}
function datePastEnd(date, options) {
return !!(options.reverse ? options.start && date.isBefore(options.start) : options.end && date.isAfter(options.end));
}
function datePastSkipToDate(date, skipToDate, options) {
return !!(options.reverse ? skipToDate.isAfterOrEqual(date) : skipToDate.isBeforeOrEqual(date));
}
/***/ }),
/***/ "./node_modules/@rschedule/core/es2015/main.js":
/*!*****************************************************!*\
!*** ./node_modules/@rschedule/core/es2015/main.js ***!
\*****************************************************/
/*! exports provided: ArgumentError, DateAdapter, DateAdapterBase, DateTime, InfiniteLoopError, InvalidDateAdapterError, InvalidDateTime, InvalidDateTimeError, RecurrenceRuleError, RecurrenceRulesIterator, RuleOptionError, ValidDateTime, cloneJSON, cloneRuleOptions, dateInputToDateAdapter, dateInputToDateTime, dateTimeSortComparer, freqToGranularity, getDaysInYear, getDifferenceBetweenWeekdays, isLeapYear, normalizeDateTimeTimezone, normalizeRuleOptions, numberSortComparer, orderedWeekdays, recurrenceRulesReducer, uniqDateTimes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArgumentError", function() { return ArgumentError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DateAdapter", function() { return DateAdapter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DateAdapterBase", function() { return DateAdapterBase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DateTime", function() { return DateTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InfiniteLoopError", function() { return InfiniteLoopError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InvalidDateAdapterError", function() { return InvalidDateAdapterError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InvalidDateTime", function() { return InvalidDateTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InvalidDateTimeError", function() { return InvalidDateTimeError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RecurrenceRuleError", function() { return RecurrenceRuleError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RecurrenceRulesIterator", function() { return RecurrenceRulesIterator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RuleOptionError", function() { return RuleOptionError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ValidDateTime", function() { return ValidDateTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cloneJSON", function() { return cloneJSON; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cloneRuleOptions", function() { return cloneRuleOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateInputToDateAdapter", function() { return dateInputToDateAdapter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateInputToDateTime", function() { return dateInputToDateTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateTimeSortComparer", function() { return dateTimeSortComparer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "freqToGranularity", function() { return freqToGranularity; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDaysInYear", function() { return getDaysInYear; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDifferenceBetweenWeekdays", function() { return getDifferenceBetweenWeekdays; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isLeapYear", function() { return isLeapYear; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizeDateTimeTimezone", function() { return normalizeDateTimeTimezone; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizeRuleOptions", function() { return normalizeRuleOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "numberSortComparer", function() { return numberSortComparer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "orderedWeekdays", function() { return orderedWeekdays; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "recurrenceRulesReducer", function() { return recurrenceRulesReducer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "uniqDateTimes", function() { return uniqDateTimes; });
class InvalidDateAdapterError extends Error {}
let dateAdapterConfig;
class DateAdapterBase {
constructor(_date, options) {
this.duration = options && options.duration || 0;
this.generators = options && options.generators && options.generators.slice() || [];
if (!Number.isInteger(this.duration) || this.duration < 0) {
throw new InvalidDateAdapterError('duration must be a non-negative integer');
}
}
static set adapter(value) {
if (dateAdapterConfig) {
throw new Error(`"${dateAdapterConfig.name}" has already been configured.`);
}
dateAdapterConfig = value;
}
static get adapter() {
if (!dateAdapterConfig) {
throw new Error('No date adapter has been configured. See rSchedule docs.');
}
return dateAdapterConfig;
}
static isDate(_object) {
throw unimplementedError('isDate()');
}
static fromDate(_date, _options) {
throw unimplementedError('fromDate()');
}
static fromJSON(_json) {
throw unimplementedError('fromJSON()');
}
static fromDateTime(_datetime) {
throw unimplementedError('fromDateTime()');
}
toDateTime() {
const date = DateTime.fromJSON(Object.assign(Object.assign({}, this.toJSON()), {
generators: this.generators
}));
return date;
}
}
DateAdapterBase.hasTimezoneSupport = false;
function unimplementedError(name) {
return new Error(`You must implement the "${name}" method for this DateAdapter class`);
}
var DateAdapter;
(function (DateAdapter) {
DateAdapter.WEEKDAYS = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];
DateAdapter.MILLISECONDS_IN_SECOND = 1000;
DateAdapter.MILLISECONDS_IN_MINUTE = DateAdapter.MILLISECONDS_IN_SECOND * 60;
DateAdapter.MILLISECONDS_IN_HOUR = DateAdapter.MILLISECONDS_IN_MINUTE * 60;
DateAdapter.MILLISECONDS_IN_DAY = DateAdapter.MILLISECONDS_IN_HOUR * 24;
DateAdapter.MILLISECONDS_IN_WEEK = DateAdapter.MILLISECONDS_IN_DAY * 7;
})(DateAdapter || (DateAdapter = {}));
class InvalidDateTimeError extends Error {}
class DateTime {
constructor(date, timezone, duration, generators) {
this.date = new Date(date);
this.timezone = timezone || null;
this.duration = duration || 0;
this.generators = generators && generators.slice() || [];
if (!Number.isInteger(this.duration) || this.duration < 0) {
throw new InvalidDateTimeError('duration must be a non-negative integer');
}
this.assertIsValid();
} // /**
// * Similar to `Array.isArray()`, `isInstance()` provides a surefire method
// * of determining if an object is a `DateTime` by checking against the
// * global symbol registry.
// */
// static isInstance(object: any): object is DateTime {
// return !!(object && object[DATETIME_ID]);
// }
static fromJSON(json) {
const date = new Date(Date.UTC(json.year, json.month - 1, json.day, json.hour, json.minute, json.second, json.millisecond));
return new DateTime(date, json.timezone, json.duration, json.generators);
}
static fromDateAdapter(adapter) {
return DateTime.fromJSON(Object.assign(Object.assign({}, adapter.toJSON()), {
generators: adapter.generators
}));
}
/**
* Returns `undefined` if `duration` is `0`. Else returns
* the `end` date.
*/
get end() {
if (!this.duration) return;
if (this._end) return this._end;
this._end = this.add(this.duration, 'millisecond');
return this._end;
} // While we constrain the argument to be another DateAdapter in typescript
// we handle the case of someone passing in another type of object in javascript
isEqual(object) {
if (!object) {
return false;
}
assertSameTimeZone(this, object);
return this.valueOf() === object.valueOf();
}
isBefore(object) {
assertSameTimeZone(this, object);
return this.valueOf() < object.valueOf();
}
isBeforeOrEqual(object) {
assertSameTimeZone(this, object);
return this.valueOf() <= object.valueOf();
}
isAfter(object) {
assertSameTimeZone(this, object);
return this.valueOf() > object.valueOf();
}
isAfterOrEqual(object) {
assertSameTimeZone(this, object);
return this.valueOf() >= object.valueOf();
}
isOccurring(object) {
if (!this.duration) {
throw new Error('DateTime#isOccurring() is only applicable to DateTimes with durations');
}
assertSameTimeZone(this, object);
return object.isAfterOrEqual(this) && object.isBeforeOrEqual(this.add(this.duration, 'millisecond'));
}
add(amount, unit) {
switch (unit) {
case 'generator':
{
const generators = this.generators.slice();
generators.unshift(amount);
return new DateTime(this.date, this.timezone, this.duration, generators);
}
case 'year':
return this.forkDateTime(addUTCYears(this.date, amount));
case 'month':
return this.forkDateTime(addUTCMonths(this.date, amount));
case 'week':
return this.forkDateTime(addUTCWeeks(this.date, amount));
case 'day':
return this.forkDateTime(addUTCDays(this.date, amount));
case 'hour':
return this.forkDateTime(addUTCHours(this.date, amount));
case 'minute':
return this.forkDateTime(addUTCMinutes(this.date, amount));
case 'second':
return this.forkDateTime(addUTCSeconds(this.date, amount));
case 'millisecond':
return this.forkDateTime(addUTCMilliseconds(this.date, amount));
default:
throw new Error('Invalid unit provided to `DateTime#add`');
}
}
subtract(amount, unit) {
switch (unit) {
case 'year':
return this.forkDateTime(subUTCYears(this.date, amount));
case 'month':
return this.forkDateTime(subUTCMonths(this.date, amount));
case 'week':
return this.forkDateTime(subUTCWeeks(this.date, amount));
case 'day':
return this.forkDateTime(subUTCDays(this.date, amount));
case 'hour':
return this.forkDateTime(subUTCHours(this.date, amount));
case 'minute':
return this.forkDateTime(subUTCMinutes(this.date, amount));
case 'second':
return this.forkDateTime(subUTCSeconds(this.date, amount));
case 'millisecond':
return this.forkDateTime(subUTCMilliseconds(this.date, amount));
default:
throw new Error('Invalid unit provided to `DateTime#subtract`');
}
}
get(unit) {
switch (unit) {
case 'year':
return this.date.getUTCFullYear();
case 'month':
return this.date.getUTCMonth() + 1;
case 'yearday':
return getUTCYearDay(this.date);
case 'weekday':
return DateAdapter.WEEKDAYS[this.date.getUTCDay()];
case 'day':
return this.date.getUTCDate();
case 'hour':
return this.date.getUTCHours();
case 'minute':
return this.date.getUTCMinutes();
case 'second':
return this.date.getUTCSeconds();
case 'millisecond':
return this.date.getUTCMilliseconds();
default:
throw new Error('Invalid unit provided to `DateTime#set`');
}
}
set(unit, value) {
if (unit === 'duration') {
return new DateTime(this.date, this.timezone, value, this.generators);
}
if (unit === 'generators') {
return new DateTime(this.date, this.timezone, this.duration, value);
}
let date = new Date(this.date);
switch (unit) {
case 'year':
date.setUTCFullYear(value);
break;
case 'month':
{
// If the current day of the month
// is greater than days in the month we are moving to, we need to also
// set the day to the end of that month.
const length = monthLength(value, date.getUTCFullYear());
const day = date.getUTCDate();
if (day > length) {
date.setUTCDate(1);
date.setUTCMonth(value);
date = subUTCDays(date, 1);
} else {
date.setUTCMonth(value - 1);
}
break;
}
case 'day':
date.setUTCDate(value);
break;
case 'hour':
date.setUTCHours(value);
break;
case 'minute':
date.setUTCMinutes(value);
break;
case 'second':
date.setUTCSeconds(value);
break;
case 'millisecond':
date.setUTCMilliseconds(value);
break;
default:
throw new Error('Invalid unit provided to `DateTime#set`');
}
return this.forkDateTime(date);
}
granularity(granularity, opt = {}) {
let date = this.forkDateTime(this.date);
switch (granularity) {
case 'year':
date = date.set('month', 1);
case 'month':
date = date.set('day', 1);
break;
case 'week':
date = setDateToStartOfWeek(date, opt.weekStart);
}
switch (granularity) {
case 'year':
case 'month':
case 'week':
case 'day':
date = date.set('hour', 0);
case 'hour':
date = date.set('minute', 0);
case 'minute':
date = date.set('second', 0);
case 'second':
date = date.set('millisecond', 0);
case 'millisecond':
return date;
default:
throw new Error('Invalid granularity provided to `DateTime#granularity`: ' + granularity);
}
}
endGranularity(granularity, opt = {}) {
let date = this.forkDateTime(this.date);
switch (granularity) {
case 'year':
date = date.set('month', 12);
case 'month':
date = date.set('day', monthLength(date.get('month'), date.get('year')));
break;
case 'week':
date = setDateToEndOfWeek(date, opt.weekStart);
}
switch (granularity) {
case 'year':
case 'month':
case 'week':
case 'day':
date = date.set('hour', 23);
case 'hour':
date = date.set('minute', 59);
case 'minute':
date = date.set('second', 59);
case 'second':
date = date.set('millisecond', 999);
case 'millisecond':
return date;
default:
throw new Error('Invalid granularity provided to `DateTime#granularity`: ' + granularity);
}
}
toISOString() {
return this.date.toISOString();
}
toDateTime() {
return this;
}
toJSON() {
const json = {
timezone: this.timezone,
year: this.get('year'),
month: this.get('month'),
day: this.get('day'),
hour: this.get('hour'),
minute: this.get('minute'),
second: this.get('second'),
millisecond: this.get('millisecond')
};
if (this.duration) {
json.duration = this.duration;
}
return json;
}
valueOf() {
return this.date.valueOf();
}
assertIsValid() {
if (isNaN(this.valueOf())) {
throw new InvalidDateTimeError('DateTime has invalid date.');
}
return true;
}
forkDateTime(date) {
return new DateTime(date, this.timezone, this.duration, this.generators);
}
}
function assertSameTimeZone(x, y) {
if (x.timezone !== y.timezone) {
throw new InvalidDateTimeError('Attempted to compare a datetime to another date in a different timezone: ' + JSON.stringify(x) + ' and ' + JSON.stringify(y));
}
return true;
}
function setDateToStartOfWeek(date, wkst) {
const index = orderedWeekdays(wkst).indexOf(date.get('weekday'));
return date.subtract(index, 'day');
}
function setDateToEndOfWeek(date, wkst) {
const index = orderedWeekdays(wkst).indexOf(date.get('weekday'));
return date.add(6 - index, 'day');
}
function dateTimeSortComparer(a, b) {
if (a.isAfter(b)) return 1;
if (a.isBefore(b)) return -1;
if (a.duration && b.duration) {
if (a.duration > b.duration) return 1;
if (a.duration < b.duration) return -1;
}
return 0;
}
function uniqDateTimes(dates) {
return Array.from(new Map(dates.map(date => [date.toISOString(), date])).values());
}
function orderedWeekdays(wkst = 'SU') {
const wkdays = DateAdapter.WEEKDAYS.slice();
let index = wkdays.indexOf(wkst);
while (index !== 0) {
shiftArray(wkdays);
index--;
}
return wkdays;
}
function shiftArray(array, from = 'first') {
if (array.length === 0) {
return array;
} else if (from === 'first') {
array.push(array.shift());
} else {
array.unshift(array.pop());
}
return array;
}
function getDifferenceBetweenWeekdays(x, y) {
if (x === y) return 0;
const result = DateAdapter.WEEKDAYS.indexOf(x) - DateAdapter.WEEKDAYS.indexOf(y);
return result > 0 ? 7 - result : Math.abs(result);
}
/**
* Returns the days in the given month.
*
* @param month base-1
* @param year
*/
function monthLength(month, year) {
const block = {
1: 31,
2: getDaysInFebruary(year),
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
};
return block[month];
}
function getDaysInFebruary(year) {
return isLeapYear(year) ? 29 : 28;
} // taken from date-fn
function isLeapYear(year) {
return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
}
function getDaysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
function getUTCYearDay(now) {
const start = new Date(Date.UTC(now.getUTCFullYear(), 0, 1));
const diff = now.valueOf() - start.valueOf();
return 1 + Math.floor(diff / DateAdapter.MILLISECONDS_IN_DAY);
}
/**
* These functions are basically lifted from `date-fns`, but changed
* to use the UTC date methods, which `date-fns` doesn't support.
*/
function toInteger(input) {
if (input === null || input === true || input === false) {
return NaN;
}
const int = Number(input);
if (isNaN(int)) {
return int;
}
return int < 0 ? Math.ceil(int) : Math.floor(int);
}
function addMilliseconds(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
const timestamp = dirtyDate.valueOf();
const amount = toInteger(dirtyAmount);
return new Date(timestamp + amount);
}
function addUTCYears(date, input) {
const amount = toInteger(input);
return addUTCMonths(date, amount * 12);
}
function addUTCMonths(date, input) {
const amount = toInteger(input);
date = new Date(date);
const desiredMonth = date.getUTCMonth() + amount;
const dateWithDesiredMonth = new Date(0);
dateWithDesiredMonth.setUTCFullYear(date.getUTCFullYear(), desiredMonth, 1);
dateWithDesiredMonth.setUTCHours(0, 0, 0, 0);
const daysInMonth = monthLength(dateWithDesiredMonth.getUTCMonth() + 1, dateWithDesiredMonth.getUTCFullYear()); // Set the last day of the new month
// if the original date was the last day of the longer month
date.setUTCMonth(desiredMonth, Math.min(daysInMonth, date.getUTCDate()));
return date;
}
function addUTCWeeks(date, input) {
const amount = toInteger(input);
const days = amount * 7;
return addUTCDays(date, days);
}
function addUTCDays(date, input) {
// by adding milliseconds rather than days, we supress the native Date object's automatic
// daylight savings time conversions which we don't want in UTC mode
return addUTCMilliseconds(date, toInteger(input) * DateAdapter.MILLISECONDS_IN_DAY);
}
function addUTCHours(date, input) {
const amount = toInteger(input);
return addMilliseconds(date, amount * DateAdapter.MILLISECONDS_IN_HOUR);
}
function addUTCMinutes(date, input) {
const amount = toInteger(input);
return addMilliseconds(date, amount * DateAdapter.MILLISECONDS_IN_MINUTE);
}
function addUTCSeconds(date, input) {
const amount = toInteger(input);
return addMilliseconds(date, amount * DateAdapter.MILLISECONDS_IN_SECOND);
}
function addUTCMilliseconds(date, input) {
const amount = toInteger(input);
const timestamp = date.getTime();
return new Date(timestamp + amount);
}
function subUTCYears(date, amount) {
return addUTCYears(date, -amount);
}
function subUTCMonths(date, amount) {
return addUTCMonths(date, -amount);
}
function subUTCWeeks(date, amount) {
return addUTCWeeks(date, -amount);
}
function subUTCDays(date, amount) {
return addUTCDays(date, -amount);
}
function subUTCHours(date, amount) {
return addUTCHours(date, -amount);
}
function subUTCMinutes(date, amount) {
return addUTCMinutes(date, -amount);
}
function subUTCSeconds(date, amount) {
return addUTCSeconds(date, -amount);
}
function subUTCMilliseconds(date, amount) {
return addUTCMilliseconds(date, -amount);
}
class ArgumentError extends Error {}
class InfiniteLoopError extends Error {}
function numberSortComparer(a, b) {
if (a > b) {
return 1;
} else if (b > a) {
return -1;
} else {
return 0;
}
}
function freqToGranularity(freq) {
switch (freq) {
case 'YEARLY':
return 'year';
case 'MONTHLY':
return 'month';
case 'WEEKLY':
return 'week';
case 'DAILY':
return 'day';
case 'HOURLY':
return 'hour';
case 'MINUTELY':
return 'minute';
case 'SECONDLY':
return 'second';
case 'MILLISECONDLY':
return 'millisecond';
default:
throw new Error('unknown freq passed to freqToGranularity()');
}
}
function cloneJSON(json) {
return JSON.parse(JSON.stringify(json));
}
function dateInputToDateAdapter(date) {
// prettier-ignore
return date instanceof DateTime ? DateAdapterBase.adapter.fromDateTime(date) : date instanceof DateAdapterBase ? date : DateAdapterBase.adapter.fromDate(date);
}
function dateInputToDateTime(date, timezone) {
if (date instanceof DateTime) {
if (date.timezone !== timezone) {
return DateAdapterBase.adapter.fromDateTime(date).set('timezone', timezone).toDateTime();
}
return date;
}
return date instanceof DateAdapterBase ? date.set('timezone', timezone).toDateTime() : DateAdapterBase.adapter.fromDate(date).set('timezone', timezone).toDateTime();
} // export function normalizeDateInput<T extends DateAdapter>(
// dateAdapter: DateAdapterConstructor<T>,
// input: DateInput<T>,
// timezone: string | null,
// ): DateTime {
// if (input instanceof DateTime) {
// if (input.timezone !== timezone) {
// return dateAdapter
// .fromDateTime(input)
// .set('timezone', timezone)
// .toDateTime();
// }
// return input;
// }
// return input instanceof DateAdapter
// ? input.set('timezone', timezone).toDateTime()
// : new dateAdapter(input).toDateTime();
// }
function normalizeDateTimeTimezone(date, timezone) {
if (date.timezone !== timezone) {
return DateAdapterBase.adapter.fromDateTime(date).set('timezone', timezone).toDateTime();
}
return date;
}
class RuleOptionError extends Error {}
function normalizeDefaultOptions(options) {
let start;
if (options.start instanceof DateTime) {
start = options.start;
} else if (options.start instanceof DateAdapterBase) {
start = options.start.toDateTime();
} else if (DateAdapterBase.adapter.isDate(options.start)) {
start = DateAdapterBase.adapter.fromDate(options.start).toDateTime();
} else {
throw new RuleOptionError('"start" must be either a `DateAdapter` instance or an instance of the ' + 'date a DateAdapter is wrapping (e.g. `StandardDateAdapter` wraps a `Date`)');
}
let end;
if (options.end) {
if (options.end instanceof DateTime) {
end = options.end;
} else if (options.end instanceof DateAdapterBase) {
end = options.end.toDateTime();
} else if (DateAdapterBase.adapter.isDate(options.end)) {
end = DateAdapterBase.adapter.fromDate(options.end).toDateTime();
} else {
throw new RuleOptionError('"end" must be either be `undefined`, a `DateAdapter` instance, or an instance of the ' + 'date a DateAdapter is wrapping (e.g. `StandardDateAdapter` wraps a `Date`)');
}
}
if (options.duration !== undefined) {
if (!Number.isInteger(options.duration)) {
throw new RuleOptionError('"duration" expects a whole number');
}
if (options.duration <= 0) {
throw new RuleOptionError('"duration" must be greater than 0');
}
}
if (options.count !== undefined) {
if (!Number.isInteger(options.count)) {
throw new RuleOptionError('"count" must be a whole number');
}
if (options.count < 0) {
throw new RuleOptionError('"count" must be greater than 0');
}
}
if (options.end !== undefined && options.count !== undefined) {
throw new RuleOptionError('"end" and "count" cannot both be present');
}
return {
start,
end,
count: options.count,
duration: options.duration
};
}
function normalizeRuleOptions(recurrenceModules, options) {
const normOptions = normalizeDefaultOptions(options);
const startOptions = cloneJSON(options);
recurrenceModules.forEach(mod => {
mod.normalizeOptions(startOptions, normOptions);
});
Object.keys(normOptions).forEach(key => {
if (normOptions[key] === undefined) {
delete normOptions[key];
}
});
return normOptions;
}
function cloneRuleOptions(options) {
const obj = cloneJSON(options);
obj.start = options.start;
if (options.end) obj.end = options.end;
return obj;
}
class RecurrenceRuleError extends Error {}
class ValidDateTime {
constructor(date) {
this.date = date;
}
}
class InvalidDateTime {
constructor(date) {
this.date = date;
}
}
function recurrenceRulesReducer(rules) {
return iterator => rules.reduce((prev, curr) => {
const rule = curr.get(iterator);
if (rule) prev.push(rule);
return prev;
}, []);
}
class RecurrenceRulesIterator {
constructor(recurrenceRules, options, args) {
this.options = options;
this.args = args;
this.rules = [];
this.iterator = // prettier-ignore
this.options.count === undefined ? this.iterate() : this.args.reverse ? this.iterateWithReverseCount() : this.iterateWithCount();
this.options = Object.assign(Object.assign({}, cloneJSON(options)), {
start: options.start,
end: options.end
});
this.reverse = this.options.count === undefined && args.reverse || false;
const _this$normalizeDateTi = this.normalizeDateTimeArgs(args),
start = _this$normalizeDateTi.start,
end = _this$normalizeDateTi.end;
if (options.count !== undefined) {
this.start = options.start;
} else if (start && options.start) {
this.start = start.isAfterOrEqual(options.start) ? start : options.start;
} else {
this.start = start || options.start;
}
if (end && options.end) {
this.end = end.isBeforeOrEqual(options.end) ? end : options.end;
} else {
this.end = end || options.end;
}
if (this.args.reverse && !(options.count !== undefined || this.end)) {
throw new Error('When iterating in reverse, the rule must have an `end` or `count` ' + 'property or you must provide an `end` argument.');
}
this.isInfinite = !this.end && this.options.count === undefined;
this.hasDuration = !!this.options.duration;
this.rules = Array.isArray(recurrenceRules) ? recurrenceRules : recurrenceRules(this);
}
[Symbol.iterator]() {
return this.iterator;
}
next(args) {
return this.iterator.next(args);
}
/**
* In the pipe controller, we have an extra level of indirection with
* the `run()` and `iterate()` methods. The `iterate()` method is the
* method which actually runs the logic in the pipes. If we didn't
* need to account for the `count` property of a rule, we would *only*
* need the iterate method... so much simpler. But we do need to account
* for rules with a `count` property.
*
* Rules with a `count` property need to begin iteration at the beginning
* because the `count` is always from the rule's start time. So if someone
* passes in a new start time as an argument to a rule with `count`, we
* need to secretly iterate from the beginning, tracking the number of
* iterations, and then only start yielding dates when we reach the section
* the user cares about (or, if we hit our `count` quota, cancel iterating).
*
* Additionally, we need to handle iterating in reverse. In this case, we build
* up a cache of dates between the rule's start time and the reverse iteration
* start date. Once we hit the reverse iteration start date, we start
* yielding dates in the cache, in reverse order.
*
* In general, I imagine the count number, if used, will be small. But a large
* count will definitely have a negative performance affect. I don't think
* there's anything to be done about this.
*/
*iterateWithReverseCount() {
const dates = Array.from(this.iterateWithCount()).reverse();
let yieldArgs;
const dateCache = dates.slice();
let date = dateCache.shift();
while (date) {
if (yieldArgs && yieldArgs.skipToDate && date.isAfter(yieldArgs.skipToDate)) {
date = dateCache.shift();
continue;
}
yieldArgs = yield date;
if (yieldArgs && yieldArgs.skipToDate && yieldArgs.skipToDate.isAfterOrEqual(date)) {
throw new Error('A provided `skipToDate` option must be greater than the last yielded date ' + '(or smaller, in the case of reverse iteration)');
}
date = dateCache.shift();
}
return undefined;
}
*iterateWithCount() {
if (this.options.count === 0) return;
const iterable = this.iterate();
const start = this.args.start || this.start;
let date = iterable.next().value;
let index = 1;
let yieldArgs;
while (date && index <= this.options.count) {
index++;
if (date.isBefore(start)) {
date = iterable.next().value;
continue;
}
if (yieldArgs && yieldArgs.skipToDate && date.isBefore(yieldArgs.skipToDate)) {
date = iterable.next().value;
continue;
}
yieldArgs = yield date;
if (yieldArgs && yieldArgs.skipToDate && yieldArgs.skipToDate.isBeforeOrEqual(date)) {
throw new Error('A provided `skipToDate` option must be greater than the last yielded date ' + '(or smaller, in the case of reverse iteration)');
}
date = iterable.next().value;
}
return undefined;
}
*iterate() {
let startingDate = this.start;
if (this.reverse) startingDate = this.end;
let date = this.nextDate(startingDate);
while (date) {
const args = yield this.normalizeRunOutput(date);
if (args && args.skipToDate) {
if (this.reverse ? args.skipToDate.isAfterOrEqual(date) : args.skipToDate.isBeforeOrEqual(date)) {
// We cannot consistently skip backwards because after an iterator is "done"
// it always returns undefined and you cannot reset it. Theoretically, it would be
// fine to skip backwards if the iterator wasn't already "done", but this
// would be prone to user error so we simply disallow skipping backwards altogether.
throw new Error('A provided `skipToDate` option must be greater than the last yielded date ' + '(or smaller, in the case of reverse iteration)');
}
date = this.nextDate(args.skipToDate);
} else {
date = this.nextDate(this.reverse ? date.subtract(1, 'millisecond') : date.add(1, 'millisecond'));
}
}
return undefined;
}
/**
* Loops through the recurrence rules until a valid date is found.
*/
nextDate(start) {
let result = this.runRules(start.set('generators', []));
if (this.isDatePastEnd(result.date)) return null;
let index = 0;
while (result instanceof InvalidDateTime && index < 50) {
result = this.runRules(result.date);
if (this.isDatePastEnd(result.date)) return null;
index++;
}
if (result instanceof InvalidDateTime) {
throw new RecurrenceRuleError(`Failed to find a matching occurrence in ${index} iterations. ` + `Last iterated date: "${result.date.toISOString()}"`);
}
if (this.reverse ? start.isBefore(result.date) : start.isAfter(result.date)) {
throw new RecurrenceRuleError('An error occurred in a recurrence rule. If this happened using ' + 'the rSchedule provided recurrence rules, you should ' + 'open an issue in the rSchedule repo. The maintainer is going to ' + 'want to know how to recreate the error.');
}
return result.date;
}
/**
* Performs one run of the recurrence rules and returns the result.
* It's a slightly optimized reducer function.
*/
runRules(start) {
let result = new ValidDateTime(start);
for (const rule of this.rules) {
if (result instanceof InvalidDateTime) {
return result;
}
result = rule.run(result.date);
}
return result;
}
isDatePastEnd(date) {
return this.reverse ? date.isBefore(this.start) : this.end && date.isAfter(this.end);
}
normalizeRunOutput(date) {
return this.hasDuration ? date.set('duration', this.options.duration) : date;
}
normalizeDateTimeArgs(args) {
return {
start: args.start && normalizeDateTimeTimezone(args.start, this.options.start.timezone),
end: args.end && normalizeDateTimeTimezone(args.end, this.options.start.timezone)
};
}
}
/***/ }),
/***/ "./node_modules/@rschedule/core/es2015/rules.js":
/*!******************************************************!*\
!*** ./node_modules/@rschedule/core/es2015/rules.js ***!
\******************************************************/
/*! exports provided: ByDayOfMonthRule, ByDayOfMonthRuleModule, ByDayOfWeekRule, ByDayOfWeekRuleModule, ByHourOfDayRule, ByHourOfDayRuleModule, ByMillisecondOfSecondRule, ByMillisecondOfSecondRuleModule, ByMinuteOfHourRule, ByMinuteOfHourRuleModule, ByMonthOfYearRule, ByMonthOfYearRuleModule, BySecondOfMinuteRule, BySecondOfMinuteRuleModule, FrequencyRule, FrequencyRuleModule, ICAL_RULES, RevByDayOfMonthRule, RevByDayOfWeekRule, RevByHourOfDayRule, RevByMillisecondOfSecondRule, RevByMinuteOfHourRule, RevByMonthOfYearRule, RevBySecondOfMinuteRule, RevFrequencyRule, getPrevWeekdaysOfMonth, getPrevWeekdaysOfYear */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByDayOfMonthRule", function() { return ByDayOfMonthRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByDayOfMonthRuleModule", function() { return ByDayOfMonthRuleModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByDayOfWeekRule", function() { return ByDayOfWeekRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByDayOfWeekRuleModule", function() { return ByDayOfWeekRuleModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByHourOfDayRule", function() { return ByHourOfDayRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByHourOfDayRuleModule", function() { return ByHourOfDayRuleModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByMillisecondOfSecondRule", function() { return ByMillisecondOfSecondRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByMillisecondOfSecondRuleModule", function() { return ByMillisecondOfSecondRuleModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByMinuteOfHourRule", function() { return ByMinuteOfHourRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByMinuteOfHourRuleModule", function() { return ByMinuteOfHourRuleModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByMonthOfYearRule", function() { return ByMonthOfYearRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByMonthOfYearRuleModule", function() { return ByMonthOfYearRuleModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BySecondOfMinuteRule", function() { return BySecondOfMinuteRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BySecondOfMinuteRuleModule", function() { return BySecondOfMinuteRuleModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FrequencyRule", function() { return FrequencyRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FrequencyRuleModule", function() { return FrequencyRuleModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ICAL_RULES", function() { return ICAL_RULES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RevByDayOfMonthRule", function() { return RevByDayOfMonthRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RevByDayOfWeekRule", function() { return RevByDayOfWeekRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RevByHourOfDayRule", function() { return RevByHourOfDayRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RevByMillisecondOfSecondRule", function() { return RevByMillisecondOfSecondRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RevByMinuteOfHourRule", function() { return RevByMinuteOfHourRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RevByMonthOfYearRule", function() { return RevByMonthOfYearRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RevBySecondOfMinuteRule", function() { return RevBySecondOfMinuteRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RevFrequencyRule", function() { return RevFrequencyRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPrevWeekdaysOfMonth", function() { return getPrevWeekdaysOfMonth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPrevWeekdaysOfYear", function() { return getPrevWeekdaysOfYear; });
/* harmony import */ var _rschedule_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @rschedule/core */ "./node_modules/@rschedule/core/es2015/main.js");
class RecurrenceRule {
constructor(processor) {
this.processor = processor;
this.start = processor.start;
this.end = processor.end;
this.options = processor.options;
}
}
class FrequencyRule extends RecurrenceRule {
constructor(processor, initDate) {
super(processor);
this.initDate = initDate;
this.intervalUnit = Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["freqToGranularity"])(this.options.frequency);
this.firstIntervalStartDate = this.normalizedStartDate(this.options.start);
this.intervalStartDate = this.firstIntervalStartDate;
this.intervalEndDate = this.normalizedEndDate(this.firstIntervalStartDate);
this.skipToInterval(this.initDate);
}
run(date) {
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ValidDateTime"](date));
}
validateDate(arg) {
const date = arg.date;
if (arg instanceof _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ValidDateTime"] && this.dateIsWithinInterval(date)) {
return arg;
}
this.skipToInterval(date);
return new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"]( // if the interval is 1, date will always be within the interval
this.dateIsWithinInterval(date) ? date : this.setToCurrentInterval());
}
setToCurrentInterval() {
return this.intervalStartDate;
}
normalizedStartDate(date) {
if (this.options.frequency === 'WEEKLY') {
return date.granularity('week', {
weekStart: this.options.weekStart
});
}
return date.granularity(this.intervalUnit);
}
normalizedEndDate(start) {
switch (this.options.frequency) {
case 'YEARLY':
return start.add(1, 'year');
case 'MONTHLY':
return start.add(1, 'month');
case 'WEEKLY':
return start.add(1, 'week');
case 'DAILY':
return start.add(1, 'day');
case 'HOURLY':
return start.add(1, 'hour');
case 'MINUTELY':
return start.add(1, 'minute');
case 'SECONDLY':
return start.add(1, 'second');
case 'MILLISECONDLY':
return start.add(1, 'millisecond');
default:
throw new Error(`Unknown frequency ${this.options.frequency}`);
}
}
skipToInterval(date) {
const amount = this.intervalDifference(date);
this.intervalStartDate = this.firstIntervalStartDate.add(amount, this.intervalUnit);
this.intervalEndDate = this.normalizedEndDate(this.intervalStartDate);
}
dateIsWithinInterval(date) {
return this.intervalStartDate.isBeforeOrEqual(date) && this.intervalEndDate.isAfter(date);
}
intervalDifference(date) {
return intervalDifferenceBetweenDates({
first: this.firstIntervalStartDate,
second: date,
unit: this.intervalUnit,
interval: this.options.interval,
weekStart: this.options.weekStart,
direction: 'after'
});
}
}
/**
* Given the frequency (unit) and interval, this function finds
* how many jumps forward the first date needs in order to equal
* or exceed the second date.
*
* For example:
*
* 1. Unit is daily and interval is 1. The second date is 3 days
* after the first. This will return 3.
* 2. Unit is yearly and interval is 1. The second date is 3 days
* after the first. This will return 0.
* 3. Unit is yearly and interval is 3. The second date is 4 years
* after the first. This will return 6.
*/
function intervalDifferenceBetweenDates({
first,
second,
unit,
interval,
weekStart,
direction
}) {
let difference = (() => {
let intervalDuration;
let months;
switch (unit) {
case 'year':
months = (second.get('year') - first.get('year')) * 12;
months = months + second.get('month') - first.get('month');
return Math.floor(months / 12);
case 'month':
months = (second.get('year') - first.get('year')) * 12;
months = months + second.get('month') - first.get('month');
return months;
case 'week':
first = first.granularity('week', {
weekStart
});
intervalDuration = _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapter"].MILLISECONDS_IN_WEEK;
break;
case 'day':
intervalDuration = _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapter"].MILLISECONDS_IN_DAY;
break;
case 'hour':
intervalDuration = _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapter"].MILLISECONDS_IN_HOUR;
break;
case 'minute':
intervalDuration = _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapter"].MILLISECONDS_IN_MINUTE;
break;
case 'second':
intervalDuration = _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapter"].MILLISECONDS_IN_SECOND;
break;
case 'millisecond':
intervalDuration = 1;
break;
default:
throw new Error('Unexpected `unit` value');
}
const diff = second.valueOf() - first.valueOf();
return Math.floor(diff / intervalDuration);
})();
const fn = direction === 'after' ? Math.ceil : Math.floor;
difference = fn(difference / interval) * interval;
return difference;
}
class RevFrequencyRule extends FrequencyRule {
setToCurrentInterval() {
return this.intervalEndDate.subtract(1, 'millisecond');
}
intervalDifference(date) {
return intervalDifferenceBetweenDates({
first: this.firstIntervalStartDate,
second: date,
unit: this.intervalUnit,
interval: this.options.interval,
weekStart: this.options.weekStart,
direction: 'before'
});
}
}
const FREQUENCIES = ['MILLISECONDLY', 'SECONDLY', 'MINUTELY', 'HOURLY', 'DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'];
const FrequencyRuleModule = {
name: 'FrequencyRule',
get: processor => {
if (processor.options.byMillisecondOfSecond !== undefined || processor.options.frequency !== 'MILLISECONDLY') {
return null;
}
if (processor.reverse) return new RevFrequencyRule(processor, processor.end);
return new FrequencyRule(processor, processor.start);
},
normalizeOptions: (options, norm) => {
if (!FREQUENCIES.includes(options.frequency)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"](`"frequency" must be one of ${JSON.stringify(FREQUENCIES)}`);
}
if (options.interval !== undefined) {
if (!Number.isInteger(options.interval)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"interval" expects a whole number');
}
if (options.interval < 1) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"interval" cannot be less than 1');
}
}
if (options.weekStart !== undefined) {
if (!_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapter"].WEEKDAYS.includes(options.weekStart)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"](`"weekStart" must be one of ${JSON.stringify(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapter"].WEEKDAYS)}`);
}
}
norm.frequency = options.frequency;
norm.interval = options.interval || 1;
norm.weekStart = options.weekStart || 'MO';
},
deps: () => [FrequencyRuleModule]
};
function ruleOptionFilled(option) {
return Array.isArray(option) && option.length > 0;
}
const freqCache = new WeakMap();
class RecurrenceRuleBase extends RecurrenceRule {
constructor(processor) {
super(processor);
if (!freqCache.has(this.processor)) {
freqCache.set(this.processor, new FrequencyRule(processor, processor.start));
}
this.frequency = freqCache.get(this.processor);
}
validateDate(arg) {
return this.frequency.validateDate(arg);
}
}
class RevRecurrenceRuleBase extends RecurrenceRule {
constructor(processor) {
super(processor);
if (!freqCache.has(this.processor)) {
freqCache.set(this.processor, new RevFrequencyRule(processor, processor.end));
}
this.frequency = freqCache.get(this.processor);
}
validateDate(arg) {
return this.frequency.validateDate(arg);
}
}
/**
* Contains shared logic for ByHourOfDay, ByMinuteOfHour,
* BySecondOfMinute, and ByMillisecondOfSecond reverse rule pipes
*/
class RevByTimeOfUnitRule extends RevRecurrenceRuleBase {
run(date) {
// e.g. const currentTime = date.get('hour');
const currentTime = date.get(this.granularity); // e.g. for (const time of this.options.byHourOfDay) {
for (const time of this.option) {
if (currentTime < time) continue;
if (currentTime === time) {
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ValidDateTime"](date));
} // e.g. return this.nextValidDate(args, date.endGranularity('day').set('hour', time));
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](date.endGranularity(this.baseGranularity).set(this.granularity, time)));
}
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](date // e.g. .endGranularity('day')
.endGranularity(this.baseGranularity) // e.g. .subtract(1, 'day')
.subtract(1, this.baseGranularity) // e.g. .set('hour', this.options.byHourOfDay[0]);
.set(this.granularity, this.option[0])));
}
}
class RevByMillisecondOfSecondRule extends RevByTimeOfUnitRule {
constructor() {
super(...arguments);
this.baseGranularity = 'second';
this.granularity = 'millisecond';
this.option = this.options.byMillisecondOfSecond.slice().reverse();
}
}
/**
* Contains shared logic for ByHourOfDay, ByMinuteOfHour,
* BySecondOfMinute, and ByMillisecondOfSecond rule pipes
*/
class ByTimeOfUnitRule extends RecurrenceRuleBase {
run(date) {
// e.g. const currentTime = date.get('hour');
const currentTime = date.get(this.granularity); // e.g. for (const time of this.options.byHourOfDay) {
for (const time of this.option) {
if (currentTime > time) continue;
if (currentTime === time) {
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ValidDateTime"](date));
} // e.g. return this.nextValidDate(args, date.granularity('day').set('hour', time));
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](date.granularity(this.baseGranularity).set(this.granularity, time)));
}
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](date // e.g. .granularity('day')
.granularity(this.baseGranularity) // e.g. .add(1, 'day')
.add(1, this.baseGranularity) // e.g. .set('hour', this.options.byHourOfDay[0]);
.set(this.granularity, this.option[0])));
}
}
class ByMillisecondOfSecondRule extends ByTimeOfUnitRule {
constructor() {
super(...arguments);
this.baseGranularity = 'second';
this.granularity = 'millisecond';
this.option = this.options.byMillisecondOfSecond;
}
}
const ByMillisecondOfSecondRuleModule = {
name: 'ByMillisecondOfSecond',
get: processor => {
if (processor.options.byMillisecondOfSecond === undefined) return null;
if (processor.reverse) return new RevByMillisecondOfSecondRule(processor);
return new ByMillisecondOfSecondRule(processor);
},
normalizeOptions: (options, norm) => {
if (options.byMillisecondOfSecond !== undefined) {
if (!ruleOptionFilled(options.byMillisecondOfSecond)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"byMillisecondOfSecond" expects a non-empty array');
}
if (options.byMillisecondOfSecond.some(num => num < 0 || num > 999)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"byMillisecondOfSecond" values must be >= 0 && <= 999');
}
norm.byMillisecondOfSecond = options.byMillisecondOfSecond;
norm.byMillisecondOfSecond.sort(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["numberSortComparer"]);
} else if (options.frequency !== 'MILLISECONDLY') {
norm.byMillisecondOfSecond = [norm.start.get('millisecond')];
}
},
deps: () => [FrequencyRuleModule, ByMillisecondOfSecondRuleModule]
};
class RevBySecondOfMinuteRule extends RevByTimeOfUnitRule {
constructor() {
super(...arguments);
this.baseGranularity = 'minute';
this.granularity = 'second';
this.option = this.options.bySecondOfMinute.slice().reverse();
}
}
class BySecondOfMinuteRule extends ByTimeOfUnitRule {
constructor() {
super(...arguments);
this.baseGranularity = 'minute';
this.granularity = 'second';
this.option = this.options.bySecondOfMinute;
}
}
const BySecondOfMinuteRuleModule = {
name: 'BySecondOfMinute',
get: processor => {
if (processor.options.bySecondOfMinute === undefined) return null;
if (processor.reverse) return new RevBySecondOfMinuteRule(processor);
return new BySecondOfMinuteRule(processor);
},
normalizeOptions: (options, norm) => {
if (options.bySecondOfMinute !== undefined) {
if (!ruleOptionFilled(options.bySecondOfMinute)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"bySecondOfMinute" expects a non-empty array');
}
if (options.bySecondOfMinute.some(num => num < 0 || num > 60)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"bySecondOfMinute" values must be >= 0 && <= 60');
}
norm.bySecondOfMinute = options.bySecondOfMinute;
norm.bySecondOfMinute.sort(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["numberSortComparer"]);
} else if (!['SECONDLY', 'MILLISECONDLY'].includes(options.frequency)) {
norm.bySecondOfMinute = [norm.start.get('second')];
}
},
deps: () => [FrequencyRuleModule, BySecondOfMinuteRuleModule, ByMillisecondOfSecondRuleModule]
};
class RevByMinuteOfHourRule extends RevByTimeOfUnitRule {
constructor() {
super(...arguments);
this.baseGranularity = 'hour';
this.granularity = 'minute';
this.option = this.options.byMinuteOfHour.slice().reverse();
}
}
class ByMinuteOfHourRule extends ByTimeOfUnitRule {
constructor() {
super(...arguments);
this.baseGranularity = 'hour';
this.granularity = 'minute';
this.option = this.options.byMinuteOfHour;
}
}
const ByMinuteOfHourRuleModule = {
name: 'ByMinuteOfHour',
get: processor => {
if (processor.options.byMinuteOfHour === undefined) return null;
if (processor.reverse) return new RevByMinuteOfHourRule(processor);
return new ByMinuteOfHourRule(processor);
},
normalizeOptions: (options, norm) => {
if (options.byMinuteOfHour !== undefined) {
if (!ruleOptionFilled(options.byMinuteOfHour)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"byMinuteOfHour" expects a non-empty array');
}
if (options.byMinuteOfHour.some(num => num < 0 || num > 59)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"byMinuteOfHour" values must be >= 0 && <= 59');
}
norm.byMinuteOfHour = options.byMinuteOfHour;
norm.byMinuteOfHour.sort(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["numberSortComparer"]);
} else if (!['MINUTELY', 'SECONDLY', 'MILLISECONDLY'].includes(options.frequency)) {
norm.byMinuteOfHour = [norm.start.get('minute')];
}
},
deps: () => [FrequencyRuleModule, ByMinuteOfHourRuleModule, BySecondOfMinuteRuleModule, ByMillisecondOfSecondRuleModule]
};
class RevByHourOfDayRule extends RevByTimeOfUnitRule {
constructor() {
super(...arguments);
this.baseGranularity = 'day';
this.granularity = 'hour';
this.option = this.options.byHourOfDay.slice().reverse();
}
}
class ByHourOfDayRule extends ByTimeOfUnitRule {
constructor() {
super(...arguments);
this.baseGranularity = 'day';
this.granularity = 'hour';
this.option = this.options.byHourOfDay;
}
}
const ByHourOfDayRuleModule = {
name: 'ByHourOfDay',
get: processor => {
if (processor.options.byHourOfDay === undefined) return null;
if (processor.reverse) return new RevByHourOfDayRule(processor);
return new ByHourOfDayRule(processor);
},
normalizeOptions: (options, norm) => {
if (options.byHourOfDay !== undefined) {
if (!ruleOptionFilled(options.byHourOfDay)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"byHourOfDay" expects a non-empty array');
}
if (options.byHourOfDay.some(num => num < 0 || num > 23)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"byHourOfDay" values must be >= 0 && <= 23');
}
norm.byHourOfDay = options.byHourOfDay;
norm.byHourOfDay.sort(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["numberSortComparer"]);
} else if (['YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY'].includes(options.frequency)) {
norm.byHourOfDay = [norm.start.get('hour')];
}
},
deps: () => [FrequencyRuleModule, ByHourOfDayRuleModule, ByMinuteOfHourRuleModule, BySecondOfMinuteRuleModule, ByMillisecondOfSecondRuleModule]
};
function getNextWeekday(date, weekday) {
return date.add(Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["getDifferenceBetweenWeekdays"])(date.get('weekday'), weekday), 'day');
}
function getNthWeekdayOfMonth(date, weekday, nth) {
let base = date.set('day', 1);
if (nth < 0) {
base = base.add(1, 'month');
}
base = getNextWeekday(base, weekday); // when nth is negative, adding it will act as subtraction
return nth < 0 ? base.add(nth, 'week') : base.add(nth - 1, 'week');
}
class ByDayOfMonthRule extends RecurrenceRuleBase {
run(date) {
const normalizedByDayOfMonth = normalizeByDayOfMonth(date, this.options.byDayOfMonth, this.options.byDayOfWeek);
const currentDay = date.get('day');
for (const day of normalizedByDayOfMonth) {
if (currentDay > day) continue;
if (currentDay === day) {
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ValidDateTime"](date));
}
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](date.granularity('month').set('day', day)));
}
let next;
let nextMonth = date;
let index = 0;
while (!next && index < 30) {
nextMonth = nextMonth.granularity('month').add(1, 'month');
next = normalizeByDayOfMonth(nextMonth, this.options.byDayOfMonth, this.options.byDayOfWeek)[0];
index++;
}
if (index >= 13) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RecurrenceRuleError"]('byDayOfMonth Infinite while loop');
}
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](nextMonth.set('day', next)));
}
}
/**
* Does a few things:
*
* 1. filters out byDayOfMonth entries which are not applicable
* to current month
* 2. negative entries to positive ones
* 3. if a byDayOfWeek option is given, removes days which are
* not on the correct day of the week
*/
function normalizeByDayOfMonth(date, byDayOfMonth, byDayOfWeek) {
const lengthOfMonth = date.endGranularity('month').get('day');
let normalizedByDayOfMonth = byDayOfMonth.filter(day => lengthOfMonth >= Math.abs(day)).map(day => day > 0 ? day : lengthOfMonth + day + 1);
if (byDayOfWeek) {
const base = date.granularity('month');
const filteredByDayOfMonth = [];
byDayOfWeek.forEach(entry => {
if (typeof entry === 'string') {
filteredByDayOfMonth.push(...normalizedByDayOfMonth.filter(day => base.set('day', day).get('weekday') === entry));
return;
}
const nthWeekdayOfMonth = getNthWeekdayOfMonth(date, ...entry).get('day');
if (normalizedByDayOfMonth.includes(nthWeekdayOfMonth)) {
filteredByDayOfMonth.push(nthWeekdayOfMonth);
}
});
normalizedByDayOfMonth = Array.from(new Set(filteredByDayOfMonth));
}
return normalizedByDayOfMonth.sort((a, b) => {
if (a > b) return 1;
if (a < b) return -1;else return 0;
});
}
class RevByDayOfMonthRule extends RevRecurrenceRuleBase {
run(date) {
const normalizedByDayOfMonth = normalizeByDayOfMonth(date, this.options.byDayOfMonth, this.options.byDayOfWeek).reverse();
const currentDay = date.get('day');
for (const day of normalizedByDayOfMonth) {
if (currentDay < day) continue;
if (currentDay === day) {
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ValidDateTime"](date));
}
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](date.endGranularity('month').set('day', day)));
}
let next;
let nextMonth = date;
let index = 0;
while (!next && index < 30) {
nextMonth = nextMonth.endGranularity('month').subtract(1, 'month');
next = normalizeByDayOfMonth(nextMonth, this.options.byDayOfMonth, this.options.byDayOfWeek).pop();
index++;
}
if (index >= 13) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RecurrenceRuleError"]('byDayOfMonth Infinite while loop');
}
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](nextMonth.set('day', next)));
}
}
const ByDayOfMonthRuleModule = {
name: 'ByDayOfMonth',
get: processor => {
if (processor.options.byDayOfMonth === undefined) return null;
if (processor.reverse) return new RevByDayOfMonthRule(processor);
return new ByDayOfMonthRule(processor);
},
normalizeOptions: (options, norm) => {
if (options.byDayOfMonth !== undefined) {
if (options.frequency === 'WEEKLY') {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('when "frequency" is "WEEKLY", "byDayOfMonth" cannot be present');
}
if (!ruleOptionFilled(options.byDayOfMonth)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"byDayOfMonth" expects a non-empty array');
}
if (options.byDayOfMonth.some(num => num === 0 || num < -31 || num > 31)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"byDayOfMonth" values must be `num !== 0 && num <= 31 && num >= -31`');
}
norm.byDayOfMonth = options.byDayOfMonth.slice();
} else if (!(ruleOptionFilled(options.byDayOfWeek) || ruleOptionFilled(options.byDayOfYear)) && ['YEARLY', 'MONTHLY'].includes(options.frequency)) {
norm.byDayOfMonth = [norm.start.get('day')];
}
},
deps: () => [FrequencyRuleModule, ByDayOfMonthRuleModule, ByHourOfDayRuleModule, ByMinuteOfHourRuleModule, BySecondOfMinuteRuleModule, ByMillisecondOfSecondRuleModule]
};
function getNthWeekdayOfYear(date, weekday, nth) {
let base = date.set('month', 1).set('day', 1);
if (nth < 0) {
base = base.add(1, 'year');
}
base = getNextWeekday(base, weekday); // when nth is negative, adding it will act as subtraction
return nth < 0 ? base.add(nth, 'week') : base.add(nth - 1, 'week');
}
function getPreviousWeekday(date, weekday) {
const diff = Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["getDifferenceBetweenWeekdays"])(date.get('weekday'), weekday);
return date.subtract(diff === 0 ? 0 : 7 - diff, 'day');
}
class RevByDayOfWeekRule extends RevRecurrenceRuleBase {
run(date) {
if (this.options.frequency === 'YEARLY') {
return this.options.byMonthOfYear === undefined ? this.expandYearly(date) : this.expandMonthly(date);
} else if (this.options.frequency === 'MONTHLY') {
return this.expandMonthly(date);
}
return this.expand(date);
}
expandYearly(date) {
let next = getPrevWeekdaysOfYear(date, this.options.byDayOfWeek)[0];
let index = 0;
let base = date; // If we can't find a valid date this year,
// search the previous year. Only search the past 28 years.
// (the calendar repeats on a 28 year cycle, according
// to the internet).
while (!next && index < 28) {
index++;
base = base.granularity('year').subtract(1, 'millisecond');
next = getPrevWeekdaysOfYear(base, this.options.byDayOfWeek)[0];
}
if (!next) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RecurrenceRuleError"]('The byDayOfWeek rule appears to contain an impossible combination');
}
return this.result(date, next);
}
expandMonthly(date) {
let next = getPrevWeekdaysOfMonth(date, this.options.byDayOfWeek)[0];
let index = 0;
let base = date; // TODO: performance improvment
// If, in the first year, a match isn't found, we should be able to
// jumpt to the previous leap year and check that. Or, if already on
// a leap year, we can just error immediately.
// If we can't find a valid date this month,
// search the previous month. Only search the past 4 years
// (to account for leap year).
while (!next && index < 50) {
index++;
base = base.granularity('month').subtract(1, 'millisecond');
next = getPrevWeekdaysOfMonth(base, this.options.byDayOfWeek)[0];
}
if (!next) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RecurrenceRuleError"]('The byDayOfWeek rule appears to contain an impossible combination');
}
return this.result(date, next);
}
expand(date) {
const next = this.options.byDayOfWeek.map(weekday => getPreviousWeekday(date, weekday)).sort(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["dateTimeSortComparer"]).pop();
return this.result(date, next);
}
result(date, next) {
if (next.isEqual(date)) {
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ValidDateTime"](date));
}
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](next.endGranularity('day')));
}
}
/** For each byDayOfWeek entry, find the previous DateTime */
function getPrevWeekdaysOfYear(date, byDayOfWeek) {
const normalizedNthWeekdaysOfYear = byDayOfWeek.filter(entry => Array.isArray(entry)).map(entry => getNthWeekdayOfYear(date, ...entry));
const normalizedNextWeekdays = byDayOfWeek.filter(entry => typeof entry === 'string').map(weekday => getPreviousWeekday(date, weekday)).filter(entry => entry.get('year') === date.get('year'));
return Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["uniqDateTimes"])([...normalizedNthWeekdaysOfYear, ...normalizedNextWeekdays]).filter(entry => entry.isBeforeOrEqual(date)).sort(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["dateTimeSortComparer"]).reverse();
}
/** For each byDayOfWeek entry, find the previous DateTime */
function getPrevWeekdaysOfMonth(date, byDayOfWeek) {
const normalizedNthWeekdaysOfMonth = byDayOfWeek.filter(entry => Array.isArray(entry)).map(entry => getNthWeekdayOfMonth(date, ...entry));
const normalizedNextWeekdays = byDayOfWeek.filter(entry => typeof entry === 'string').map(weekday => getPreviousWeekday(date, weekday)).filter(entry => entry.get('year') === date.get('year') && entry.get('month') === date.get('month'));
return Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["uniqDateTimes"])([...normalizedNthWeekdaysOfMonth, ...normalizedNextWeekdays]).filter(entry => entry.isBeforeOrEqual(date)).sort(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["dateTimeSortComparer"]).reverse();
}
class ByDayOfWeekRule extends RecurrenceRuleBase {
run(date) {
if (this.options.frequency === 'YEARLY') {
return this.options.byMonthOfYear === undefined ? this.expandYearly(date) : this.expandMonthly(date);
} else if (this.options.frequency === 'MONTHLY') {
return this.expandMonthly(date);
}
return this.expand(date);
}
expandYearly(date) {
let next = getNextWeekdaysOfYear(date, this.options.byDayOfWeek)[0];
let index = 0;
let base = date; // If we can't find a valid date this year,
// search next year. Only search the next 28 years.
// (the calendar repeats on a 28 year cycle, according
// to the internet).
while (!next && index < 28) {
index++;
base = base.granularity('year').add(1, 'year');
next = getNextWeekdaysOfYear(base, this.options.byDayOfWeek)[0];
}
if (!next) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RecurrenceRuleError"]('The byDayOfWeek rule appears to contain an impossible combination');
}
return this.result(date, next);
}
expandMonthly(date) {
let next = getNextWeekdaysOfMonth(date, this.options.byDayOfWeek)[0];
let index = 0;
let base = date; // TODO: performance improvment
// If, in the first year, a match isn't found, we should be able to
// jumpt to the next leap year and check that. Or, if already on
// a leap year, we can just error immediately.
// If we can't find a valid date this month,
// search the next month. Only search the next 4 years
// (to account for leap year).
while (!next && index < 50) {
index++;
base = base.granularity('month').add(1, 'month');
next = getNextWeekdaysOfMonth(base, this.options.byDayOfWeek)[0];
}
if (!next) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RecurrenceRuleError"]('The byDayOfWeek rule appears to contain an impossible combination');
}
return this.result(date, next);
}
expand(date) {
const next = this.options.byDayOfWeek.map(weekday => getNextWeekday(date, weekday)).sort(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["dateTimeSortComparer"])[0];
return this.result(date, next);
}
result(date, next) {
if (next.isEqual(date)) {
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ValidDateTime"](date));
}
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](next.granularity('day')));
}
}
/** For each byDayOfWeek entry, find the next DateTime */
function getNextWeekdaysOfYear(date, byDayOfWeek) {
const normalizedNthWeekdaysOfYear = byDayOfWeek.filter(entry => Array.isArray(entry)).map(entry => getNthWeekdayOfYear(date, ...entry));
const normalizedNextWeekdays = byDayOfWeek.filter(entry => typeof entry === 'string').map(weekday => getNextWeekday(date, weekday)).filter(entry => entry.get('year') === date.get('year'));
return Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["uniqDateTimes"])([...normalizedNthWeekdaysOfYear, ...normalizedNextWeekdays]).filter(entry => entry.isAfterOrEqual(date)).sort(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["dateTimeSortComparer"]);
}
/** For each byDayOfWeek entry, find the next DateTime */
function getNextWeekdaysOfMonth(date, byDayOfWeek) {
const normalizedNthWeekdaysOfMonth = byDayOfWeek.filter(entry => Array.isArray(entry)).map(entry => getNthWeekdayOfMonth(date, ...entry));
const normalizedNextWeekdays = byDayOfWeek.filter(entry => typeof entry === 'string').map(weekday => getNextWeekday(date, weekday)).filter(entry => entry.get('year') === date.get('year') && entry.get('month') === date.get('month'));
return Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["uniqDateTimes"])([...normalizedNthWeekdaysOfMonth, ...normalizedNextWeekdays]).filter(entry => entry.isAfterOrEqual(date)).sort(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["dateTimeSortComparer"]);
}
const ByDayOfWeekRuleModule = {
name: 'ByDayOfWeek',
get: processor => {
if (processor.options.byDayOfWeek === undefined) return null;
if (processor.reverse) return new RevByDayOfWeekRule(processor);
return new ByDayOfWeekRule(processor);
},
normalizeOptions: (options, norm) => {
if (options.byDayOfWeek !== undefined) {
if (!ruleOptionFilled(options.byDayOfWeek)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"byDayOfWeek" expects a non-empty array');
}
const invalidWeeday = options.byDayOfWeek.find(day => Array.isArray(day) ? !_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapter"].WEEKDAYS.includes(day[0]) : !_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapter"].WEEKDAYS.includes(day));
if (invalidWeeday) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"](`"byDayOfWeek" expects weedays in the form ` + `${JSON.stringify(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapter"].WEEKDAYS)} but "${invalidWeeday}" was provided`);
}
if (!['YEARLY', 'MONTHLY'].includes(options.frequency) && options.byDayOfWeek.some(weekday => Array.isArray(weekday))) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"byDayOfWeek" can only include a numeric value (i.e. `[string, number]`) when the "frequency" is ' + 'either "MONTHLY" or "YEARLY"');
}
if (options.frequency === 'MONTHLY' && options.byDayOfWeek.some(weekday => Array.isArray(weekday) && (weekday[1] < -31 || weekday[1] === 0 || weekday[1] > 31))) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('when "frequency" is "MONTHLY", each "byDayOfWeek" can optionally only' + ' have a numeric value >= -31 and <= 31 and !== 0');
}
if (options.frequency === 'YEARLY' && options.byDayOfWeek.some(weekday => Array.isArray(weekday) && (weekday[1] < -366 || weekday[1] === 0 || weekday[1] > 366))) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('when "frequency" is "YEARLY", each "byDayOfWeek" can optionally only' + ' have a numeric value >= -366 and <= 366 and !== 0');
}
norm.byDayOfWeek = options.byDayOfWeek;
} else if (!ruleOptionFilled(options.byDayOfMonth) && options.frequency === 'WEEKLY') {
norm.byDayOfWeek = [norm.start.get('weekday')];
}
},
deps: () => [FrequencyRuleModule, ByDayOfWeekRuleModule, ByHourOfDayRuleModule, ByMinuteOfHourRuleModule, BySecondOfMinuteRuleModule, ByMillisecondOfSecondRuleModule]
};
class RevByMonthOfYearRule extends RevRecurrenceRuleBase {
constructor() {
super(...arguments);
this.option = this.processor.options.byMonthOfYear.slice().reverse();
}
run(date) {
const currentMonth = date.get('month');
for (const month of this.option) {
if (currentMonth < month) continue;
if (currentMonth === month) {
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ValidDateTime"](date));
}
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](date.endGranularity('year').set('month', month)));
}
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](date.endGranularity('year').subtract(1, 'year').set('month', this.option[0])));
}
}
class ByMonthOfYearRule extends RecurrenceRuleBase {
run(date) {
const currentMonth = date.get('month');
for (const month of this.options.byMonthOfYear) {
if (currentMonth > month) continue;
if (currentMonth === month) {
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ValidDateTime"](date));
}
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](date.granularity('year').set('month', month)));
}
return this.validateDate(new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateTime"](date.granularity('year').add(1, 'year').set('month', this.options.byMonthOfYear[0])));
}
}
const ByMonthOfYearRuleModule = {
name: 'ByMonthOfYear',
get: processor => {
if (processor.options.byMonthOfYear === undefined) return null;
if (processor.reverse) {
return new RevByMonthOfYearRule(processor);
}
return new ByMonthOfYearRule(processor);
},
normalizeOptions: (options, norm) => {
if (options.byMonthOfYear !== undefined) {
if (!ruleOptionFilled(options.byMonthOfYear)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"byMonthOfYear" expects a non-empty array');
}
if (options.byMonthOfYear.some(num => num < 1 || num > 12)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["RuleOptionError"]('"byMonthOfYear" values must be `num >= 1 && num >= 12`');
}
norm.byMonthOfYear = options.byMonthOfYear.slice();
norm.byMonthOfYear.sort(_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["numberSortComparer"]);
} else if (!(ruleOptionFilled(options.byDayOfMonth) || ruleOptionFilled(options.byDayOfWeek) || ruleOptionFilled(options.byDayOfYear)) && options.frequency === 'YEARLY') {
norm.byMonthOfYear = [norm.start.get('month')];
}
},
deps: () => [FrequencyRuleModule, ByMonthOfYearRuleModule, ByDayOfMonthRuleModule, ByHourOfDayRuleModule, ByMinuteOfHourRuleModule, BySecondOfMinuteRuleModule, ByMillisecondOfSecondRuleModule]
};
const ICAL_RULES = [FrequencyRuleModule, ByMonthOfYearRuleModule, ByDayOfMonthRuleModule, ByDayOfWeekRuleModule, ByHourOfDayRuleModule, ByMinuteOfHourRuleModule, BySecondOfMinuteRuleModule, ByMillisecondOfSecondRuleModule];
/***/ }),
/***/ "./node_modules/@rschedule/json-tools/es2015/Schedule.js":
/*!***************************************************************!*\
!*** ./node_modules/@rschedule/json-tools/es2015/Schedule.js ***!
\***************************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @rschedule/core/generators */ "./node_modules/@rschedule/core/es2015/generators.js");
/* harmony import */ var _rschedule_json_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @rschedule/json-tools */ "./node_modules/@rschedule/json-tools/es2015/main.js");
/* harmony import */ var _rschedule_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @rschedule/core */ "./node_modules/@rschedule/core/es2015/main.js");
_rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Dates"].prototype.toJSON = function serialize(opts = {}) {
const json = {
type: 'Dates',
dates: this.adapters.map(adapter => adapter.toJSON())
};
if (!opts.nested) json.timezone = this.timezone;
Object(_rschedule_json_tools__WEBPACK_IMPORTED_MODULE_1__["serializeDataToJSON"])(this, json, opts);
return json;
};
_rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Dates"].fromJSON = function parse(json, options = {}) {
if (json.type !== 'Dates') {
throw new _rschedule_json_tools__WEBPACK_IMPORTED_MODULE_1__["ParseJSONError"]('Invalid Dates JSON');
}
return new _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Dates"]({
dates: json.dates.map(date => _rschedule_core__WEBPACK_IMPORTED_MODULE_2__["DateAdapterBase"].adapter.fromJSON(date)),
data: typeof options.data === 'function' ? options.data(json) : json.data,
timezone: options.timezone || json.timezone
});
};
Object(_rschedule_json_tools__WEBPACK_IMPORTED_MODULE_1__["registerJSONSerializerFn"])('Dates', _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Dates"].fromJSON);
_rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Rule"].prototype.toJSON = function serialize(opts = {}) {
const json = {
type: 'Rule',
config: Object.assign(Object.assign({}, Object(_rschedule_core__WEBPACK_IMPORTED_MODULE_2__["cloneJSON"])(this.options)), {
start: this.normalizeDateInput(this.options.start).toJSON()
})
};
if (this.options.end) {
json.config.end = this.normalizeDateInput(this.options.end).toJSON();
}
if (!opts.nested) json.timezone = this.timezone;
Object(_rschedule_json_tools__WEBPACK_IMPORTED_MODULE_1__["serializeDataToJSON"])(this, json, opts);
return json;
};
_rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Rule"].fromJSON = function fromJSON(json, options = {}) {
const config = Object.assign(Object.assign({}, json.config), {
start: _rschedule_core__WEBPACK_IMPORTED_MODULE_2__["DateAdapterBase"].adapter.fromJSON(json.config.start),
end: json.config.end && _rschedule_core__WEBPACK_IMPORTED_MODULE_2__["DateAdapterBase"].adapter.fromJSON(json.config.end)
});
return new _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Rule"](config, {
data: typeof options.data === 'function' ? options.data(json) : json.data,
timezone: options.timezone || json.timezone
});
};
Object(_rschedule_json_tools__WEBPACK_IMPORTED_MODULE_1__["registerJSONSerializerFn"])('Rule', _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Rule"].fromJSON);
_rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Schedule"].prototype.toJSON = function serialize(opts = {}) {
const json = {
type: 'Schedule',
rrules: this.rrules.map(rule => rule.toJSON(Object.assign(Object.assign({}, opts), {
nested: true
}))),
exrules: this.exrules.map(rule => rule.toJSON(Object.assign(Object.assign({}, opts), {
nested: true
}))),
rdates: this.rdates.toJSON(Object.assign(Object.assign({}, opts), {
nested: true
})),
exdates: this.exdates.toJSON(Object.assign(Object.assign({}, opts), {
nested: true
}))
};
if (!opts.nested) json.timezone = this.timezone;
Object(_rschedule_json_tools__WEBPACK_IMPORTED_MODULE_1__["serializeDataToJSON"])(this, json, opts);
return json;
};
_rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Schedule"].fromJSON = function parse(json, options = {}) {
if (json.type !== 'Schedule') {
throw new _rschedule_json_tools__WEBPACK_IMPORTED_MODULE_1__["ParseJSONError"]('Invalid Schedule JSON');
}
return new _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Schedule"]({
rrules: json.rrules.map(rule => _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Rule"].fromJSON(rule, Object.assign({
timezone: json.timezone
}, options))),
exrules: json.exrules.map(rule => _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Rule"].fromJSON(rule, Object.assign({
timezone: json.timezone
}, options))),
rdates: _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Dates"].fromJSON(json.rdates, Object.assign({
timezone: json.timezone
}, options)),
exdates: _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Dates"].fromJSON(json.exdates, Object.assign({
timezone: json.timezone
}, options)),
data: typeof options.data === 'function' ? options.data(json) : json.data,
timezone: options.timezone || json.timezone
});
};
Object(_rschedule_json_tools__WEBPACK_IMPORTED_MODULE_1__["registerJSONSerializerFn"])('Schedule', _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["Schedule"].fromJSON);
/***/ }),
/***/ "./node_modules/@rschedule/json-tools/es2015/main.js":
/*!***********************************************************!*\
!*** ./node_modules/@rschedule/json-tools/es2015/main.js ***!
\***********************************************************/
/*! exports provided: ParseJSONError, SerializeJSONError, registerJSONSerializerFn, serializeDataToJSON */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParseJSONError", function() { return ParseJSONError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SerializeJSONError", function() { return SerializeJSONError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerJSONSerializerFn", function() { return registerJSONSerializerFn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "serializeDataToJSON", function() { return serializeDataToJSON; });
/* harmony import */ var _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @rschedule/core/generators */ "./node_modules/@rschedule/core/es2015/generators.js");
class ParseJSONError extends Error {}
class SerializeJSONError extends Error {}
_rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["OccurrenceGenerator"].JSON_FN_MAP = new Map();
_rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["OccurrenceGenerator"].prototype.toJSON = function serialize(opts) {
throw new SerializeJSONError(`To support smaller bundles, ${this.constructor.name}#toJSON() ` + `must be manually added. See "@rschedule/json-tools" in the rSchedule docs.`);
};
_rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["OccurrenceGenerator"].fromJSON = function parse(json, options) {
if (typeof json !== 'object' || json === null) {
throw new ParseJSONError(`Invalid json "${json}"`);
}
const fn = _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["OccurrenceGenerator"].JSON_FN_MAP.get(json.type);
if (!fn) {
throw new ParseJSONError(`Unknown rSchedule object type "${json.type}". Have you added a json serializer ` + `for "${json.type}"? ` + `See "@rschedule/json-tools" in the rSchedule docs.`);
}
return fn(json, options);
};
function serializeDataToJSON(gen, json, opt) {
if (!opt.data) return;
if (opt.data === true) {
json.data = gen.data;
} else {
json.data = opt.data(gen);
}
if (json.data === undefined) delete json.data;
}
function registerJSONSerializerFn(name, fn) {
if (_rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["OccurrenceGenerator"].JSON_FN_MAP.has(name)) {
throw new Error(`Attempting to set a global json parser function for "${name}" ` + 'but one already exists.');
}
_rschedule_core_generators__WEBPACK_IMPORTED_MODULE_0__["OccurrenceGenerator"].JSON_FN_MAP.set(name, fn);
}
/***/ }),
/***/ "./node_modules/@rschedule/standard-date-adapter/es2015/main.js":
/*!**********************************************************************!*\
!*** ./node_modules/@rschedule/standard-date-adapter/es2015/main.js ***!
\**********************************************************************/
/*! exports provided: StandardDateAdapter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StandardDateAdapter", function() { return StandardDateAdapter; });
/* harmony import */ var _rschedule_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @rschedule/core */ "./node_modules/@rschedule/core/es2015/main.js");
class StandardDateAdapter extends _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapterBase"] {
constructor(date, options = {}) {
super(undefined, options);
if (!['UTC', null, undefined].includes(options.timezone)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateAdapterError"](`StandardDateAdapter only supports "UTC" and ` + `local time zones but "${options.timezone}" was provided.`);
}
this._date = new Date(date);
this.timezone = options.timezone !== undefined ? options.timezone : null;
this.assertIsValid();
}
static isDate(object) {
return Object.prototype.toString.call(object) === '[object Date]';
}
static fromDate(date, options) {
return new StandardDateAdapter(date, options);
}
static fromJSON(json) {
const args = [json.year, json.month - 1, json.day, json.hour, json.minute, json.second, json.millisecond];
switch (json.timezone) {
case 'UTC':
{
return new StandardDateAdapter(new Date(Date.UTC(...args)), {
timezone: 'UTC',
duration: json.duration
});
}
case null:
{
return new StandardDateAdapter(new Date(...args), {
timezone: null,
duration: json.duration
});
}
default:
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateAdapterError"]('The `StandardDateAdapter` only supports datetimes in ' + `UTC or LOCAL (null) time. You provided a JSON object ` + `with timezone "${json.timezone}".`);
}
}
static fromDateTime(datetime) {
const date = StandardDateAdapter.fromJSON(datetime.toJSON());
date.generators.push(...datetime.generators);
return date;
}
get date() {
return new Date(this._date);
}
get end() {
if (!this.duration) return;
if (this._end) return this._end;
this._end = StandardDateAdapter.fromDateTime(this.toDateTime().add(this.duration, 'millisecond')).date;
return this._end;
}
set(prop, value) {
if (prop === 'timezone') {
if (this.timezone === value) return this;else {
return new StandardDateAdapter(this._date, {
timezone: value,
duration: this.duration,
generators: this.generators
});
}
} else if (prop === 'duration') {
if (this.duration === value) return this;else {
return new StandardDateAdapter(this._date, {
timezone: this.timezone,
duration: value,
generators: this.generators
});
}
}
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["ArgumentError"](`Unknown prop "${prop}" for StandardDateAdapter#set()`);
}
valueOf() {
return this._date.valueOf();
}
toISOString() {
return this._date.toISOString();
}
toJSON() {
let json;
if (this.timezone === 'UTC') {
json = {
timezone: this.timezone,
year: this._date.getUTCFullYear(),
month: this._date.getUTCMonth() + 1,
day: this._date.getUTCDate(),
hour: this._date.getUTCHours(),
minute: this._date.getUTCMinutes(),
second: this._date.getUTCSeconds(),
millisecond: this._date.getUTCMilliseconds()
};
} else {
json = {
timezone: this.timezone,
year: this._date.getFullYear(),
month: this._date.getMonth() + 1,
day: this._date.getDate(),
hour: this._date.getHours(),
minute: this._date.getMinutes(),
second: this._date.getSeconds(),
millisecond: this._date.getMilliseconds()
};
}
if (this.duration) {
json.duration = this.duration;
}
return json;
}
assertIsValid() {
if (!StandardDateAdapter.isDate(this._date) || isNaN(this._date.valueOf())) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateAdapterError"]('StandardDateAdapter has invalid date.');
} else if (![null, 'UTC'].includes(this.timezone)) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateAdapterError"]('StandardDateAdapter only supports local (null) and UTC timezones but ' + `"${this.timezone}" was specified.`);
} else if (this.duration && this.duration <= 0) {
throw new _rschedule_core__WEBPACK_IMPORTED_MODULE_0__["InvalidDateAdapterError"]('If provided, duration must be greater than 0.');
}
return true;
}
}
StandardDateAdapter.hasTimezoneSupport = false;
/***/ }),
/***/ "./node_modules/@rschedule/standard-date-adapter/es2015/setup.js":
/*!***********************************************************************!*\
!*** ./node_modules/@rschedule/standard-date-adapter/es2015/setup.js ***!
\***********************************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _rschedule_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @rschedule/core */ "./node_modules/@rschedule/core/es2015/main.js");
/* harmony import */ var _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @rschedule/core/generators */ "./node_modules/@rschedule/core/es2015/generators.js");
/* harmony import */ var _rschedule_core_rules_ICAL_RULES__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @rschedule/core/rules/ICAL_RULES */ "./node_modules/@rschedule/core/es2015/rules.js");
/* harmony import */ var _rschedule_standard_date_adapter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @rschedule/standard-date-adapter */ "./node_modules/@rschedule/standard-date-adapter/es2015/main.js");
_rschedule_core__WEBPACK_IMPORTED_MODULE_0__["DateAdapterBase"].adapter = _rschedule_standard_date_adapter__WEBPACK_IMPORTED_MODULE_3__["StandardDateAdapter"];
_rschedule_core_generators__WEBPACK_IMPORTED_MODULE_1__["Rule"].recurrenceRules = _rschedule_core_rules_ICAL_RULES__WEBPACK_IMPORTED_MODULE_2__["ICAL_RULES"];
/***/ }),
/***/ "./node_modules/accounting/accounting.js":
/*!***********************************************!*\
!*** ./node_modules/accounting/accounting.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/*!
* accounting.js v0.4.2
* Copyright 2014 Open Exchange Rates
*
* Freely distributable under the MIT license.
* Portions of accounting.js are inspired or borrowed from underscore.js
*
* Full details and documentation:
* http://openexchangerates.github.io/accounting.js/
*/
(function (root, undefined) {
/* --- Setup --- */
// Create the local library object, to be exported or referenced globally later
var lib = {}; // Current version
lib.version = '0.4.2';
/* --- Exposed settings --- */
// The library's settings configuration object. Contains default parameters for
// currency and number formatting
lib.settings = {
currency: {
symbol: "$",
// default currency symbol is '$'
format: "%s%v",
// controls output: %s = symbol, %v = value (can be object, see docs)
decimal: ".",
// decimal point separator
thousand: ",",
// thousands separator
precision: 2,
// decimal places
grouping: 3 // digit grouping (not implemented yet)
},
number: {
precision: 0,
// default precision on numbers is 0
grouping: 3,
// digit grouping (not implemented yet)
thousand: ",",
decimal: "."
}
};
/* --- Internal Helper Methods --- */
// Store reference to possibly-available ECMAScript 5 methods for later
var nativeMap = Array.prototype.map,
nativeIsArray = Array.isArray,
toString = Object.prototype.toString;
/**
* Tests whether supplied parameter is a string
* from underscore.js
*/
function isString(obj) {
return !!(obj === '' || obj && obj.charCodeAt && obj.substr);
}
/**
* Tests whether supplied parameter is an array
* from underscore.js, delegates to ECMA5's native Array.isArray
*/
function isArray(obj) {
return nativeIsArray ? nativeIsArray(obj) : toString.call(obj) === '[object Array]';
}
/**
* Tests whether supplied parameter is a true object
*/
function isObject(obj) {
return obj && toString.call(obj) === '[object Object]';
}
/**
* Extends an object with a defaults object, similar to underscore's _.defaults
*
* Used for abstracting parameter handling from API methods
*/
function defaults(object, defs) {
var key;
object = object || {};
defs = defs || {}; // Iterate over object non-prototype properties:
for (key in defs) {
if (defs.hasOwnProperty(key)) {
// Replace values with defaults only if undefined (allow empty/zero values):
if (object[key] == null) object[key] = defs[key];
}
}
return object;
}
/**
* Implementation of `Array.map()` for iteration loops
*
* Returns a new Array as a result of calling `iterator` on each array value.
* Defers to native Array.map if available
*/
function map(obj, iterator, context) {
var results = [],
i,
j;
if (!obj) return results; // Use native .map method if it exists:
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); // Fallback for native .map:
for (i = 0, j = obj.length; i < j; i++) {
results[i] = iterator.call(context, obj[i], i, obj);
}
return results;
}
/**
* Check and normalise the value of precision (must be positive integer)
*/
function checkPrecision(val, base) {
val = Math.round(Math.abs(val));
return isNaN(val) ? base : val;
}
/**
* Parses a format string or object and returns format obj for use in rendering
*
* `format` is either a string with the default (positive) format, or object
* containing `pos` (required), `neg` and `zero` values (or a function returning
* either a string or object)
*
* Either string or format.pos must contain "%v" (value) to be valid
*/
function checkCurrencyFormat(format) {
var defaults = lib.settings.currency.format; // Allow function as format parameter (should return string or object):
if (typeof format === "function") format = format(); // Format can be a string, in which case `value` ("%v") must be present:
if (isString(format) && format.match("%v")) {
// Create and return positive, negative and zero formats:
return {
pos: format,
neg: format.replace("-", "").replace("%v", "-%v"),
zero: format
}; // If no format, or object is missing valid positive value, use defaults:
} else if (!format || !format.pos || !format.pos.match("%v")) {
// If defaults is a string, casts it to an object for faster checking next time:
return !isString(defaults) ? defaults : lib.settings.currency.format = {
pos: defaults,
neg: defaults.replace("%v", "-%v"),
zero: defaults
};
} // Otherwise, assume format was fine:
return format;
}
/* --- API Methods --- */
/**
* Takes a string/array of strings, removes all formatting/cruft and returns the raw float value
* Alias: `accounting.parse(string)`
*
* Decimal must be included in the regular expression to match floats (defaults to
* accounting.settings.number.decimal), so if the number uses a non-standard decimal
* separator, provide it as the second argument.
*
* Also matches bracketed negatives (eg. "$ (1.99)" => -1.99)
*
* Doesn't throw any errors (`NaN`s become 0) but this may change in future
*/
var unformat = lib.unformat = lib.parse = function (value, decimal) {
// Recursively unformat arrays:
if (isArray(value)) {
return map(value, function (val) {
return unformat(val, decimal);
});
} // Fails silently (need decent errors):
value = value || 0; // Return the value as-is if it's already a number:
if (typeof value === "number") return value; // Default decimal point comes from settings, but could be set to eg. "," in opts:
decimal = decimal || lib.settings.number.decimal; // Build regex to strip out everything except digits, decimal point and minus sign:
var regex = new RegExp("[^0-9-" + decimal + "]", ["g"]),
unformatted = parseFloat(("" + value).replace(/\((?=\d+)(.*)\)/, "-$1") // replace bracketed values with negatives
.replace(regex, '') // strip out any cruft
.replace(decimal, '.') // make sure decimal point is standard
); // This will fail silently which may cause trouble, let's wait and see:
return !isNaN(unformatted) ? unformatted : 0;
};
/**
* Implementation of toFixed() that treats floats more like decimals
*
* Fixes binary rounding issues (eg. (0.615).toFixed(2) === "0.61") that present
* problems for accounting- and finance-related software.
*/
var toFixed = lib.toFixed = function (value, precision) {
precision = checkPrecision(precision, lib.settings.number.precision);
var exponentialForm = Number(lib.unformat(value) + 'e' + precision);
var rounded = Math.round(exponentialForm);
var finalResult = Number(rounded + 'e-' + precision).toFixed(precision);
return finalResult;
};
/**
* Format a number, with comma-separated thousands and custom precision/decimal places
* Alias: `accounting.format()`
*
* Localise by overriding the precision and thousand / decimal separators
* 2nd parameter `precision` can be an object matching `settings.number`
*/
var formatNumber = lib.formatNumber = lib.format = function (number, precision, thousand, decimal) {
// Resursively format arrays:
if (isArray(number)) {
return map(number, function (val) {
return formatNumber(val, precision, thousand, decimal);
});
} // Clean up number:
number = unformat(number); // Build options object from second param (if object) or all params, extending defaults:
var opts = defaults(isObject(precision) ? precision : {
precision: precision,
thousand: thousand,
decimal: decimal
}, lib.settings.number),
// Clean up precision
usePrecision = checkPrecision(opts.precision),
// Do some calc:
negative = number < 0 ? "-" : "",
base = parseInt(toFixed(Math.abs(number || 0), usePrecision), 10) + "",
mod = base.length > 3 ? base.length % 3 : 0; // Format the number:
return negative + (mod ? base.substr(0, mod) + opts.thousand : "") + base.substr(mod).replace(/(\d{3})(?=\d)/g, "$1" + opts.thousand) + (usePrecision ? opts.decimal + toFixed(Math.abs(number), usePrecision).split('.')[1] : "");
};
/**
* Format a number into currency
*
* Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format)
* defaults: (0, "$", 2, ",", ".", "%s%v")
*
* Localise by overriding the symbol, precision, thousand / decimal separators and format
* Second param can be an object matching `settings.currency` which is the easiest way.
*
* To do: tidy up the parameters
*/
var formatMoney = lib.formatMoney = function (number, symbol, precision, thousand, decimal, format) {
// Resursively format arrays:
if (isArray(number)) {
return map(number, function (val) {
return formatMoney(val, symbol, precision, thousand, decimal, format);
});
} // Clean up number:
number = unformat(number); // Build options object from second param (if object) or all params, extending defaults:
var opts = defaults(isObject(symbol) ? symbol : {
symbol: symbol,
precision: precision,
thousand: thousand,
decimal: decimal,
format: format
}, lib.settings.currency),
// Check format (returns object with pos, neg and zero):
formats = checkCurrencyFormat(opts.format),
// Choose which format to use for this value:
useFormat = number > 0 ? formats.pos : number < 0 ? formats.neg : formats.zero; // Return with currency symbol added:
return useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(number), checkPrecision(opts.precision), opts.thousand, opts.decimal));
};
/**
* Format a list of numbers into an accounting column, padding with whitespace
* to line up currency symbols, thousand separators and decimals places
*
* List should be an array of numbers
* Second parameter can be an object containing keys that match the params
*
* Returns array of accouting-formatted number strings of same length
*
* NB: `white-space:pre` CSS rule is required on the list container to prevent
* browsers from collapsing the whitespace in the output strings.
*/
lib.formatColumn = function (list, symbol, precision, thousand, decimal, format) {
if (!list || !isArray(list)) return []; // Build options object from second param (if object) or all params, extending defaults:
var opts = defaults(isObject(symbol) ? symbol : {
symbol: symbol,
precision: precision,
thousand: thousand,
decimal: decimal,
format: format
}, lib.settings.currency),
// Check format (returns object with pos, neg and zero), only need pos for now:
formats = checkCurrencyFormat(opts.format),
// Whether to pad at start of string or after currency symbol:
padAfterSymbol = formats.pos.indexOf("%s") < formats.pos.indexOf("%v") ? true : false,
// Store value for the length of the longest string in the column:
maxLength = 0,
// Format the list according to options, store the length of the longest string:
formatted = map(list, function (val, i) {
if (isArray(val)) {
// Recursively format columns if list is a multi-dimensional array:
return lib.formatColumn(val, opts);
} else {
// Clean up the value
val = unformat(val); // Choose which format to use for this value (pos, neg or zero):
var useFormat = val > 0 ? formats.pos : val < 0 ? formats.neg : formats.zero,
// Format this value, push into formatted list and save the length:
fVal = useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(val), checkPrecision(opts.precision), opts.thousand, opts.decimal));
if (fVal.length > maxLength) maxLength = fVal.length;
return fVal;
}
}); // Pad each number in the list and send back the column of numbers:
return map(formatted, function (val, i) {
// Only if this is a string (not a nested array, which would have already been padded):
if (isString(val) && val.length < maxLength) {
// Depending on symbol position, pad after symbol or at index 0:
return padAfterSymbol ? val.replace(opts.symbol, opts.symbol + new Array(maxLength - val.length + 1).join(" ")) : new Array(maxLength - val.length + 1).join(" ") + val;
}
return val;
});
};
/* --- Module Definition --- */
// Export accounting for CommonJS. If being loaded as an AMD module, define it as such.
// Otherwise, just add `accounting` to the global object
if (true) {
if ( true && module.exports) {
exports = module.exports = lib;
}
exports.accounting = lib;
} else {} // Root will be `window` in browser or `global` on the server:
})(this);
/***/ }),
/***/ "./node_modules/adm-zip/adm-zip.js":
/*!*****************************************!*\
!*** ./node_modules/adm-zip/adm-zip.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const Utils = __webpack_require__(/*! ./util */ "./node_modules/adm-zip/util/index.js");
const pth = __webpack_require__(/*! path */ "path");
const ZipEntry = __webpack_require__(/*! ./zipEntry */ "./node_modules/adm-zip/zipEntry.js");
const ZipFile = __webpack_require__(/*! ./zipFile */ "./node_modules/adm-zip/zipFile.js");
const get_Bool = (val, def) => typeof val === "boolean" ? val : def;
const get_Str = (val, def) => typeof val === "string" ? val : def;
const defaultOptions = {
// option "noSort" : if true it disables files sorting
noSort: false,
// read entries during load (initial loading may be slower)
readEntries: false,
// default method is none
method: Utils.Constants.NONE,
// file system
fs: null
};
module.exports = function (
/**String*/
input,
/** object */
options) {
let inBuffer = null; // create object based default options, allowing them to be overwritten
const opts = Object.assign(Object.create(null), defaultOptions); // test input variable
if (input && "object" === typeof input) {
// if value is not buffer we accept it to be object with options
if (!(input instanceof Uint8Array)) {
Object.assign(opts, input);
input = opts.input ? opts.input : undefined;
if (opts.input) delete opts.input;
} // if input is buffer
if (Buffer.isBuffer(input)) {
inBuffer = input;
opts.method = Utils.Constants.BUFFER;
input = undefined;
}
} // assign options
Object.assign(opts, options); // instanciate utils filesystem
const filetools = new Utils(opts); // if input is file name we retrieve its content
if (input && "string" === typeof input) {
// load zip file
if (filetools.fs.existsSync(input)) {
opts.method = Utils.Constants.FILE;
opts.filename = input;
inBuffer = filetools.fs.readFileSync(input);
} else {
throw new Error(Utils.Errors.INVALID_FILENAME);
}
} // create variable
const _zip = new ZipFile(inBuffer, opts);
const canonical = Utils.canonical,
sanitize = Utils.sanitize;
function getEntry(
/**Object*/
entry) {
if (entry && _zip) {
var item; // If entry was given as a file name
if (typeof entry === "string") item = _zip.getEntry(entry); // if entry was given as a ZipEntry object
if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined") item = _zip.getEntry(entry.entryName);
if (item) {
return item;
}
}
return null;
}
function fixPath(zipPath) {
const _pth$posix = pth.posix,
join = _pth$posix.join,
normalize = _pth$posix.normalize,
sep = _pth$posix.sep; // convert windows file separators and normalize
return join(".", normalize(sep + zipPath.split("\\").join(sep) + sep));
}
return {
/**
* Extracts the given entry from the archive and returns the content as a Buffer object
* @param entry ZipEntry object or String with the full path of the entry
*
* @return Buffer or Null in case of error
*/
readFile: function (
/**Object*/
entry,
/*String, Buffer*/
pass) {
var item = getEntry(entry);
return item && item.getData(pass) || null;
},
/**
* Asynchronous readFile
* @param entry ZipEntry object or String with the full path of the entry
* @param callback
*
* @return Buffer or Null in case of error
*/
readFileAsync: function (
/**Object*/
entry,
/**Function*/
callback) {
var item = getEntry(entry);
if (item) {
item.getDataAsync(callback);
} else {
callback(null, "getEntry failed for:" + entry);
}
},
/**
* Extracts the given entry from the archive and returns the content as plain text in the given encoding
* @param entry ZipEntry object or String with the full path of the entry
* @param encoding Optional. If no encoding is specified utf8 is used
*
* @return String
*/
readAsText: function (
/**Object*/
entry,
/**String=*/
encoding) {
var item = getEntry(entry);
if (item) {
var data = item.getData();
if (data && data.length) {
return data.toString(encoding || "utf8");
}
}
return "";
},
/**
* Asynchronous readAsText
* @param entry ZipEntry object or String with the full path of the entry
* @param callback
* @param encoding Optional. If no encoding is specified utf8 is used
*
* @return String
*/
readAsTextAsync: function (
/**Object*/
entry,
/**Function*/
callback,
/**String=*/
encoding) {
var item = getEntry(entry);
if (item) {
item.getDataAsync(function (data, err) {
if (err) {
callback(data, err);
return;
}
if (data && data.length) {
callback(data.toString(encoding || "utf8"));
} else {
callback("");
}
});
} else {
callback("");
}
},
/**
* Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory
*
* @param entry
*/
deleteFile: function (
/**Object*/
entry) {
// @TODO: test deleteFile
var item = getEntry(entry);
if (item) {
_zip.deleteEntry(item.entryName);
}
},
/**
* Adds a comment to the zip. The zip must be rewritten after adding the comment.
*
* @param comment
*/
addZipComment: function (
/**String*/
comment) {
// @TODO: test addZipComment
_zip.comment = comment;
},
/**
* Returns the zip comment
*
* @return String
*/
getZipComment: function () {
return _zip.comment || "";
},
/**
* Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment
* The comment cannot exceed 65535 characters in length
*
* @param entry
* @param comment
*/
addZipEntryComment: function (
/**Object*/
entry,
/**String*/
comment) {
var item = getEntry(entry);
if (item) {
item.comment = comment;
}
},
/**
* Returns the comment of the specified entry
*
* @param entry
* @return String
*/
getZipEntryComment: function (
/**Object*/
entry) {
var item = getEntry(entry);
if (item) {
return item.comment || "";
}
return "";
},
/**
* Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content
*
* @param entry
* @param content
*/
updateFile: function (
/**Object*/
entry,
/**Buffer*/
content) {
var item = getEntry(entry);
if (item) {
item.setData(content);
}
},
/**
* Adds a file from the disk to the archive
*
* @param localPath File to add to zip
* @param zipPath Optional path inside the zip
* @param zipName Optional name for the file
*/
addLocalFile: function (
/**String*/
localPath,
/**String=*/
zipPath,
/**String=*/
zipName,
/**String*/
comment) {
if (filetools.fs.existsSync(localPath)) {
// fix ZipPath
zipPath = zipPath ? fixPath(zipPath) : ""; // p - local file name
var p = localPath.split("\\").join("/").split("/").pop(); // add file name into zippath
zipPath += zipName ? zipName : p; // read file attributes
const _attr = filetools.fs.statSync(localPath); // add file into zip file
this.addFile(zipPath, filetools.fs.readFileSync(localPath), comment, _attr);
} else {
throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
}
},
/**
* Adds a local directory and all its nested files and directories to the archive
*
* @param localPath
* @param zipPath optional path inside zip
* @param filter optional RegExp or Function if files match will
* be included.
*/
addLocalFolder: function (
/**String*/
localPath,
/**String=*/
zipPath,
/**=RegExp|Function*/
filter) {
// Prepare filter
if (filter instanceof RegExp) {
// if filter is RegExp wrap it
filter = function (rx) {
return function (filename) {
return rx.test(filename);
};
}(filter);
} else if ("function" !== typeof filter) {
// if filter is not function we will replace it
filter = function () {
return true;
};
} // fix ZipPath
zipPath = zipPath ? fixPath(zipPath) : ""; // normalize the path first
localPath = pth.normalize(localPath);
if (filetools.fs.existsSync(localPath)) {
const items = filetools.findFiles(localPath);
const self = this;
if (items.length) {
items.forEach(function (filepath) {
var p = pth.relative(localPath, filepath).split("\\").join("/"); //windows fix
if (filter(p)) {
var stats = filetools.fs.statSync(filepath);
if (stats.isFile()) {
self.addFile(zipPath + p, filetools.fs.readFileSync(filepath), "", stats);
} else {
self.addFile(zipPath + p + "/", Buffer.alloc(0), "", stats);
}
}
});
}
} else {
throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
}
},
/**
* Asynchronous addLocalFile
* @param localPath
* @param callback
* @param zipPath optional path inside zip
* @param filter optional RegExp or Function if files match will
* be included.
*/
addLocalFolderAsync: function (
/*String*/
localPath,
/*Function*/
callback,
/*String*/
zipPath,
/*RegExp|Function*/
filter) {
if (filter instanceof RegExp) {
filter = function (rx) {
return function (filename) {
return rx.test(filename);
};
}(filter);
} else if ("function" !== typeof filter) {
filter = function () {
return true;
};
} // fix ZipPath
zipPath = zipPath ? fixPath(zipPath) : ""; // normalize the path first
localPath = pth.normalize(localPath);
var self = this;
filetools.fs.open(localPath, "r", function (err) {
if (err && err.code === "ENOENT") {
callback(undefined, Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
} else if (err) {
callback(undefined, err);
} else {
var items = filetools.findFiles(localPath);
var i = -1;
var next = function () {
i += 1;
if (i < items.length) {
var filepath = items[i];
var p = pth.relative(localPath, filepath).split("\\").join("/"); //windows fix
p = p.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^\x20-\x7E]/g, ""); // accent fix
if (filter(p)) {
filetools.fs.stat(filepath, function (er0, stats) {
if (er0) callback(undefined, er0);
if (stats.isFile()) {
filetools.fs.readFile(filepath, function (er1, data) {
if (er1) {
callback(undefined, er1);
} else {
self.addFile(zipPath + p, data, "", stats);
next();
}
});
} else {
self.addFile(zipPath + p + "/", Buffer.alloc(0), "", stats);
next();
}
});
} else {
next();
}
} else {
callback(true, undefined);
}
};
next();
}
});
},
/**
*
* @param {string} localPath - path where files will be extracted
* @param {object} props - optional properties
* @param {string} props.zipPath - optional path inside zip
* @param {regexp, function} props.filter - RegExp or Function if files match will be included.
*/
addLocalFolderPromise: function (
/*String*/
localPath,
/* object */
props) {
return new Promise((resolve, reject) => {
const _Object$assign = Object.assign({}, props),
filter = _Object$assign.filter,
zipPath = _Object$assign.zipPath;
this.addLocalFolderAsync(localPath, (done, err) => {
if (err) reject(err);
if (done) resolve(this);
}, zipPath, filter);
});
},
/**
* Allows you to create a entry (file or directory) in the zip file.
* If you want to create a directory the entryName must end in / and a null buffer should be provided.
* Comment and attributes are optional
*
* @param {string} entryName
* @param {Buffer | string} content - file content as buffer or utf8 coded string
* @param {string} comment - file comment
* @param {number | object} attr - number as unix file permissions, object as filesystem Stats object
*/
addFile: function (
/**String*/
entryName,
/**Buffer*/
content,
/**String*/
comment,
/**Number*/
attr) {
let entry = getEntry(entryName);
const update = entry != null; // prepare new entry
if (!update) {
entry = new ZipEntry();
entry.entryName = entryName;
}
entry.comment = comment || "";
const isStat = "object" === typeof attr && attr instanceof filetools.fs.Stats; // last modification time from file stats
if (isStat) {
entry.header.time = attr.mtime;
} // Set file attribute
var fileattr = entry.isDirectory ? 0x10 : 0; // (MS-DOS directory flag)
// extended attributes field for Unix
if (!Utils.isWin) {
// set file type either S_IFDIR / S_IFREG
let unix = entry.isDirectory ? 0x4000 : 0x8000;
if (isStat) {
// File attributes from file stats
unix |= 0xfff & attr.mode;
} else if ("number" === typeof attr) {
// attr from given attr values
unix |= 0xfff & attr;
} else {
// Default values:
unix |= entry.isDirectory ? 0o755 : 0o644; // permissions (drwxr-xr-x) or (-r-wr--r--)
}
fileattr = (fileattr | unix << 16) >>> 0; // add attributes
}
entry.attr = fileattr;
entry.setData(content);
if (!update) _zip.setEntry(entry);
},
/**
* Returns an array of ZipEntry objects representing the files and folders inside the archive
*
* @return Array
*/
getEntries: function () {
return _zip ? _zip.entries : [];
},
/**
* Returns a ZipEntry object representing the file or folder specified by ``name``.
*
* @param name
* @return ZipEntry
*/
getEntry: function (
/**String*/
name) {
return getEntry(name);
},
getEntryCount: function () {
return _zip.getEntryCount();
},
forEach: function (callback) {
return _zip.forEach(callback);
},
/**
* Extracts the given entry to the given targetPath
* If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted
*
* @param entry ZipEntry object or String with the full path of the entry
* @param targetPath Target folder where to write the file
* @param maintainEntryPath If maintainEntryPath is true and the entry is inside a folder, the entry folder
* will be created in targetPath as well. Default is TRUE
* @param overwrite If the file already exists at the target path, the file will be overwriten if this is true.
* Default is FALSE
* @param keepOriginalPermission The file will be set as the permission from the entry if this is true.
* Default is FALSE
* @param outFileName String If set will override the filename of the extracted file (Only works if the entry is a file)
*
* @return Boolean
*/
extractEntryTo: function (
/**Object*/
entry,
/**String*/
targetPath,
/**Boolean*/
maintainEntryPath,
/**Boolean*/
overwrite,
/**Boolean*/
keepOriginalPermission,
/**String**/
outFileName) {
overwrite = get_Bool(overwrite, false);
keepOriginalPermission = get_Bool(keepOriginalPermission, false);
maintainEntryPath = get_Bool(maintainEntryPath, true);
outFileName = get_Str(outFileName, get_Str(keepOriginalPermission, undefined));
var item = getEntry(entry);
if (!item) {
throw new Error(Utils.Errors.NO_ENTRY);
}
var entryName = canonical(item.entryName);
var target = sanitize(targetPath, outFileName && !item.isDirectory ? outFileName : maintainEntryPath ? entryName : pth.basename(entryName));
if (item.isDirectory) {
var children = _zip.getEntryChildren(item);
children.forEach(function (child) {
if (child.isDirectory) return;
var content = child.getData();
if (!content) {
throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
}
var name = canonical(child.entryName);
var childName = sanitize(targetPath, maintainEntryPath ? name : pth.basename(name)); // The reverse operation for attr depend on method addFile()
const fileAttr = keepOriginalPermission ? child.header.fileAttr : undefined;
filetools.writeFileTo(childName, content, overwrite, fileAttr);
});
return true;
}
var content = item.getData();
if (!content) throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
if (filetools.fs.existsSync(target) && !overwrite) {
throw new Error(Utils.Errors.CANT_OVERRIDE);
} // The reverse operation for attr depend on method addFile()
const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
filetools.writeFileTo(target, content, overwrite, fileAttr);
return true;
},
/**
* Test the archive
*
*/
test: function (pass) {
if (!_zip) {
return false;
}
for (var entry in _zip.entries) {
try {
if (entry.isDirectory) {
continue;
}
var content = _zip.entries[entry].getData(pass);
if (!content) {
return false;
}
} catch (err) {
return false;
}
}
return true;
},
/**
* Extracts the entire archive to the given location
*
* @param targetPath Target location
* @param overwrite If the file already exists at the target path, the file will be overwriten if this is true.
* Default is FALSE
* @param keepOriginalPermission The file will be set as the permission from the entry if this is true.
* Default is FALSE
*/
extractAllTo: function (
/**String*/
targetPath,
/**Boolean*/
overwrite,
/**Boolean*/
keepOriginalPermission,
/*String, Buffer*/
pass) {
overwrite = get_Bool(overwrite, false);
pass = get_Str(keepOriginalPermission, pass);
keepOriginalPermission = get_Bool(keepOriginalPermission, false);
if (!_zip) {
throw new Error(Utils.Errors.NO_ZIP);
}
_zip.entries.forEach(function (entry) {
var entryName = sanitize(targetPath, canonical(entry.entryName.toString()));
if (entry.isDirectory) {
filetools.makeDir(entryName);
return;
}
var content = entry.getData(pass);
if (!content) {
throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
} // The reverse operation for attr depend on method addFile()
const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
filetools.writeFileTo(entryName, content, overwrite, fileAttr);
try {
filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time);
} catch (err) {
throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
}
});
},
/**
* Asynchronous extractAllTo
*
* @param targetPath Target location
* @param overwrite If the file already exists at the target path, the file will be overwriten if this is true.
* Default is FALSE
* @param keepOriginalPermission The file will be set as the permission from the entry if this is true.
* Default is FALSE
* @param callback The callback will be executed when all entries are extracted successfully or any error is thrown.
*/
extractAllToAsync: function (
/**String*/
targetPath,
/**Boolean*/
overwrite,
/**Boolean*/
keepOriginalPermission,
/**Function*/
callback) {
if (!callback) {
callback = function () {};
}
overwrite = get_Bool(overwrite, false);
if (typeof keepOriginalPermission === "function" && !callback) callback = keepOriginalPermission;
keepOriginalPermission = get_Bool(keepOriginalPermission, false);
if (!_zip) {
callback(new Error(Utils.Errors.NO_ZIP));
return;
}
targetPath = pth.resolve(targetPath); // convert entryName to
const getPath = entry => sanitize(targetPath, pth.normalize(canonical(entry.entryName.toString())));
const getError = (msg, file) => new Error(msg + ': "' + file + '"'); // separate directories from files
const dirEntries = [];
const fileEntries = new Set();
_zip.entries.forEach(e => {
if (e.isDirectory) {
dirEntries.push(e);
} else {
fileEntries.add(e);
}
}); // Create directory entries first synchronously
// this prevents race condition and assures folders are there before writing files
for (const entry of dirEntries) {
const dirPath = getPath(entry); // The reverse operation for attr depend on method addFile()
const dirAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
try {
filetools.makeDir(dirPath);
if (dirAttr) filetools.fs.chmodSync(dirPath, dirAttr); // in unix timestamp will change if files are later added to folder, but still
filetools.fs.utimesSync(dirPath, entry.header.time, entry.header.time);
} catch (er) {
callback(getError("Unable to create folder", dirPath));
}
} // callback wrapper, for some house keeping
const done = () => {
if (fileEntries.size === 0) {
callback();
}
}; // Extract file entries asynchronously
for (const entry of fileEntries.values()) {
const entryName = pth.normalize(canonical(entry.entryName.toString()));
const filePath = sanitize(targetPath, entryName);
entry.getDataAsync(function (content, err_1) {
if (err_1) {
callback(new Error(err_1));
return;
}
if (!content) {
callback(new Error(Utils.Errors.CANT_EXTRACT_FILE));
} else {
// The reverse operation for attr depend on method addFile()
const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
filetools.writeFileToAsync(filePath, content, overwrite, fileAttr, function (succ) {
if (!succ) {
callback(getError("Unable to write file", filePath));
return;
}
filetools.fs.utimes(filePath, entry.header.time, entry.header.time, function (err_2) {
if (err_2) {
callback(getError("Unable to set times", filePath));
return;
}
fileEntries.delete(entry); // call the callback if it was last entry
done();
});
});
}
});
} // call the callback if fileEntries was empty
done();
},
/**
* Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip
*
* @param targetFileName
* @param callback
*/
writeZip: function (
/**String*/
targetFileName,
/**Function*/
callback) {
if (arguments.length === 1) {
if (typeof targetFileName === "function") {
callback = targetFileName;
targetFileName = "";
}
}
if (!targetFileName && opts.filename) {
targetFileName = opts.filename;
}
if (!targetFileName) return;
var zipData = _zip.compressToBuffer();
if (zipData) {
var ok = filetools.writeFileTo(targetFileName, zipData, true);
if (typeof callback === "function") callback(!ok ? new Error("failed") : null, "");
}
},
writeZipPromise: function (
/**String*/
targetFileName,
/* object */
props) {
const _Object$assign2 = Object.assign({
overwrite: true
}, props),
overwrite = _Object$assign2.overwrite,
perm = _Object$assign2.perm;
return new Promise((resolve, reject) => {
// find file name
if (!targetFileName && opts.filename) targetFileName = opts.filename;
if (!targetFileName) reject("ADM-ZIP: ZIP File Name Missing");
this.toBufferPromise().then(zipData => {
const ret = done => done ? resolve(done) : reject("ADM-ZIP: Wasn't able to write zip file");
filetools.writeFileToAsync(targetFileName, zipData, overwrite, perm, ret);
}, reject);
});
},
toBufferPromise: function () {
return new Promise((resolve, reject) => {
_zip.toAsyncBuffer(resolve, reject);
});
},
/**
* Returns the content of the entire zip file as a Buffer object
*
* @return Buffer
*/
toBuffer: function (
/**Function=*/
onSuccess,
/**Function=*/
onFail,
/**Function=*/
onItemStart,
/**Function=*/
onItemEnd) {
this.valueOf = 2;
if (typeof onSuccess === "function") {
_zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd);
return null;
}
return _zip.compressToBuffer();
}
};
};
/***/ }),
/***/ "./node_modules/adm-zip/headers/entryHeader.js":
/*!*****************************************************!*\
!*** ./node_modules/adm-zip/headers/entryHeader.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var Utils = __webpack_require__(/*! ../util */ "./node_modules/adm-zip/util/index.js"),
Constants = Utils.Constants;
/* The central directory file header */
module.exports = function () {
var _verMade = 20,
// v2.0
_version = 10,
// v1.0
_flags = 0,
_method = 0,
_time = 0,
_crc = 0,
_compressedSize = 0,
_size = 0,
_fnameLen = 0,
_extraLen = 0,
_comLen = 0,
_diskStart = 0,
_inattr = 0,
_attr = 0,
_offset = 0;
_verMade |= Utils.isWin ? 0x0a00 : 0x0300; // Set EFS flag since filename and comment fields are all by default encoded using UTF-8.
// Without it file names may be corrupted for other apps when file names use unicode chars
_flags |= Constants.FLG_EFS;
var _dataHeader = {};
function setTime(val) {
val = new Date(val);
_time = (val.getFullYear() - 1980 & 0x7f) << 25 | // b09-16 years from 1980
val.getMonth() + 1 << 21 | // b05-08 month
val.getDate() << 16 | // b00-04 hour
// 2 bytes time
val.getHours() << 11 | // b11-15 hour
val.getMinutes() << 5 | // b05-10 minute
val.getSeconds() >> 1; // b00-04 seconds divided by 2
}
setTime(+new Date());
return {
get made() {
return _verMade;
},
set made(val) {
_verMade = val;
},
get version() {
return _version;
},
set version(val) {
_version = val;
},
get flags() {
return _flags;
},
set flags(val) {
_flags = val;
},
get method() {
return _method;
},
set method(val) {
switch (val) {
case Constants.STORED:
this.version = 10;
case Constants.DEFLATED:
default:
this.version = 20;
}
_method = val;
},
get time() {
return new Date((_time >> 25 & 0x7f) + 1980, (_time >> 21 & 0x0f) - 1, _time >> 16 & 0x1f, _time >> 11 & 0x1f, _time >> 5 & 0x3f, (_time & 0x1f) << 1);
},
set time(val) {
setTime(val);
},
get crc() {
return _crc;
},
set crc(val) {
_crc = Math.max(0, val) >>> 0;
},
get compressedSize() {
return _compressedSize;
},
set compressedSize(val) {
_compressedSize = Math.max(0, val) >>> 0;
},
get size() {
return _size;
},
set size(val) {
_size = Math.max(0, val) >>> 0;
},
get fileNameLength() {
return _fnameLen;
},
set fileNameLength(val) {
_fnameLen = val;
},
get extraLength() {
return _extraLen;
},
set extraLength(val) {
_extraLen = val;
},
get commentLength() {
return _comLen;
},
set commentLength(val) {
_comLen = val;
},
get diskNumStart() {
return _diskStart;
},
set diskNumStart(val) {
_diskStart = Math.max(0, val) >>> 0;
},
get inAttr() {
return _inattr;
},
set inAttr(val) {
_inattr = Math.max(0, val) >>> 0;
},
get attr() {
return _attr;
},
set attr(val) {
_attr = Math.max(0, val) >>> 0;
},
// get Unix file permissions
get fileAttr() {
return _attr ? (_attr >>> 0 | 0) >> 16 & 0xfff : 0;
},
get offset() {
return _offset;
},
set offset(val) {
_offset = Math.max(0, val) >>> 0;
},
get encripted() {
return (_flags & 1) === 1;
},
get entryHeaderSize() {
return Constants.CENHDR + _fnameLen + _extraLen + _comLen;
},
get realDataOffset() {
return _offset + Constants.LOCHDR + _dataHeader.fnameLen + _dataHeader.extraLen;
},
get dataHeader() {
return _dataHeader;
},
loadDataHeaderFromBinary: function (
/*Buffer*/
input) {
var data = input.slice(_offset, _offset + Constants.LOCHDR); // 30 bytes and should start with "PK\003\004"
if (data.readUInt32LE(0) !== Constants.LOCSIG) {
throw new Error(Utils.Errors.INVALID_LOC);
}
_dataHeader = {
// version needed to extract
version: data.readUInt16LE(Constants.LOCVER),
// general purpose bit flag
flags: data.readUInt16LE(Constants.LOCFLG),
// compression method
method: data.readUInt16LE(Constants.LOCHOW),
// modification time (2 bytes time, 2 bytes date)
time: data.readUInt32LE(Constants.LOCTIM),
// uncompressed file crc-32 value
crc: data.readUInt32LE(Constants.LOCCRC),
// compressed size
compressedSize: data.readUInt32LE(Constants.LOCSIZ),
// uncompressed size
size: data.readUInt32LE(Constants.LOCLEN),
// filename length
fnameLen: data.readUInt16LE(Constants.LOCNAM),
// extra field length
extraLen: data.readUInt16LE(Constants.LOCEXT)
};
},
loadFromBinary: function (
/*Buffer*/
data) {
// data should be 46 bytes and start with "PK 01 02"
if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) {
throw new Error(Utils.Errors.INVALID_CEN);
} // version made by
_verMade = data.readUInt16LE(Constants.CENVEM); // version needed to extract
_version = data.readUInt16LE(Constants.CENVER); // encrypt, decrypt flags
_flags = data.readUInt16LE(Constants.CENFLG); // compression method
_method = data.readUInt16LE(Constants.CENHOW); // modification time (2 bytes time, 2 bytes date)
_time = data.readUInt32LE(Constants.CENTIM); // uncompressed file crc-32 value
_crc = data.readUInt32LE(Constants.CENCRC); // compressed size
_compressedSize = data.readUInt32LE(Constants.CENSIZ); // uncompressed size
_size = data.readUInt32LE(Constants.CENLEN); // filename length
_fnameLen = data.readUInt16LE(Constants.CENNAM); // extra field length
_extraLen = data.readUInt16LE(Constants.CENEXT); // file comment length
_comLen = data.readUInt16LE(Constants.CENCOM); // volume number start
_diskStart = data.readUInt16LE(Constants.CENDSK); // internal file attributes
_inattr = data.readUInt16LE(Constants.CENATT); // external file attributes
_attr = data.readUInt32LE(Constants.CENATX); // LOC header offset
_offset = data.readUInt32LE(Constants.CENOFF);
},
dataHeaderToBinary: function () {
// LOC header size (30 bytes)
var data = Buffer.alloc(Constants.LOCHDR); // "PK\003\004"
data.writeUInt32LE(Constants.LOCSIG, 0); // version needed to extract
data.writeUInt16LE(_version, Constants.LOCVER); // general purpose bit flag
data.writeUInt16LE(_flags, Constants.LOCFLG); // compression method
data.writeUInt16LE(_method, Constants.LOCHOW); // modification time (2 bytes time, 2 bytes date)
data.writeUInt32LE(_time, Constants.LOCTIM); // uncompressed file crc-32 value
data.writeUInt32LE(_crc, Constants.LOCCRC); // compressed size
data.writeUInt32LE(_compressedSize, Constants.LOCSIZ); // uncompressed size
data.writeUInt32LE(_size, Constants.LOCLEN); // filename length
data.writeUInt16LE(_fnameLen, Constants.LOCNAM); // extra field length
data.writeUInt16LE(_extraLen, Constants.LOCEXT);
return data;
},
entryHeaderToBinary: function () {
// CEN header size (46 bytes)
var data = Buffer.alloc(Constants.CENHDR + _fnameLen + _extraLen + _comLen); // "PK\001\002"
data.writeUInt32LE(Constants.CENSIG, 0); // version made by
data.writeUInt16LE(_verMade, Constants.CENVEM); // version needed to extract
data.writeUInt16LE(_version, Constants.CENVER); // encrypt, decrypt flags
data.writeUInt16LE(_flags, Constants.CENFLG); // compression method
data.writeUInt16LE(_method, Constants.CENHOW); // modification time (2 bytes time, 2 bytes date)
data.writeUInt32LE(_time, Constants.CENTIM); // uncompressed file crc-32 value
data.writeUInt32LE(_crc, Constants.CENCRC); // compressed size
data.writeUInt32LE(_compressedSize, Constants.CENSIZ); // uncompressed size
data.writeUInt32LE(_size, Constants.CENLEN); // filename length
data.writeUInt16LE(_fnameLen, Constants.CENNAM); // extra field length
data.writeUInt16LE(_extraLen, Constants.CENEXT); // file comment length
data.writeUInt16LE(_comLen, Constants.CENCOM); // volume number start
data.writeUInt16LE(_diskStart, Constants.CENDSK); // internal file attributes
data.writeUInt16LE(_inattr, Constants.CENATT); // external file attributes
data.writeUInt32LE(_attr, Constants.CENATX); // LOC header offset
data.writeUInt32LE(_offset, Constants.CENOFF); // fill all with
data.fill(0x00, Constants.CENHDR);
return data;
},
toJSON: function () {
const bytes = function (nr) {
return nr + " bytes";
};
return {
made: _verMade,
version: _version,
flags: _flags,
method: Utils.methodToString(_method),
time: this.time,
crc: "0x" + _crc.toString(16).toUpperCase(),
compressedSize: bytes(_compressedSize),
size: bytes(_size),
fileNameLength: bytes(_fnameLen),
extraLength: bytes(_extraLen),
commentLength: bytes(_comLen),
diskNumStart: _diskStart,
inAttr: _inattr,
attr: _attr,
offset: _offset,
entryHeaderSize: bytes(Constants.CENHDR + _fnameLen + _extraLen + _comLen)
};
},
toString: function () {
return JSON.stringify(this.toJSON(), null, "\t");
}
};
};
/***/ }),
/***/ "./node_modules/adm-zip/headers/index.js":
/*!***********************************************!*\
!*** ./node_modules/adm-zip/headers/index.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
exports.EntryHeader = __webpack_require__(/*! ./entryHeader */ "./node_modules/adm-zip/headers/entryHeader.js");
exports.MainHeader = __webpack_require__(/*! ./mainHeader */ "./node_modules/adm-zip/headers/mainHeader.js");
/***/ }),
/***/ "./node_modules/adm-zip/headers/mainHeader.js":
/*!****************************************************!*\
!*** ./node_modules/adm-zip/headers/mainHeader.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var Utils = __webpack_require__(/*! ../util */ "./node_modules/adm-zip/util/index.js"),
Constants = Utils.Constants;
/* The entries in the end of central directory */
module.exports = function () {
var _volumeEntries = 0,
_totalEntries = 0,
_size = 0,
_offset = 0,
_commentLength = 0;
return {
get diskEntries() {
return _volumeEntries;
},
set diskEntries(
/*Number*/
val) {
_volumeEntries = _totalEntries = val;
},
get totalEntries() {
return _totalEntries;
},
set totalEntries(
/*Number*/
val) {
_totalEntries = _volumeEntries = val;
},
get size() {
return _size;
},
set size(
/*Number*/
val) {
_size = val;
},
get offset() {
return _offset;
},
set offset(
/*Number*/
val) {
_offset = val;
},
get commentLength() {
return _commentLength;
},
set commentLength(
/*Number*/
val) {
_commentLength = val;
},
get mainHeaderSize() {
return Constants.ENDHDR + _commentLength;
},
loadFromBinary: function (
/*Buffer*/
data) {
// data should be 22 bytes and start with "PK 05 06"
// or be 56+ bytes and start with "PK 06 06" for Zip64
if ((data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) && (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG)) {
throw new Error(Utils.Errors.INVALID_END);
}
if (data.readUInt32LE(0) === Constants.ENDSIG) {
// number of entries on this volume
_volumeEntries = data.readUInt16LE(Constants.ENDSUB); // total number of entries
_totalEntries = data.readUInt16LE(Constants.ENDTOT); // central directory size in bytes
_size = data.readUInt32LE(Constants.ENDSIZ); // offset of first CEN header
_offset = data.readUInt32LE(Constants.ENDOFF); // zip file comment length
_commentLength = data.readUInt16LE(Constants.ENDCOM);
} else {
// number of entries on this volume
_volumeEntries = Utils.readBigUInt64LE(data, Constants.ZIP64SUB); // total number of entries
_totalEntries = Utils.readBigUInt64LE(data, Constants.ZIP64TOT); // central directory size in bytes
_size = Utils.readBigUInt64LE(data, Constants.ZIP64SIZ); // offset of first CEN header
_offset = Utils.readBigUInt64LE(data, Constants.ZIP64OFF);
_commentLength = 0;
}
},
toBinary: function () {
var b = Buffer.alloc(Constants.ENDHDR + _commentLength); // "PK 05 06" signature
b.writeUInt32LE(Constants.ENDSIG, 0);
b.writeUInt32LE(0, 4); // number of entries on this volume
b.writeUInt16LE(_volumeEntries, Constants.ENDSUB); // total number of entries
b.writeUInt16LE(_totalEntries, Constants.ENDTOT); // central directory size in bytes
b.writeUInt32LE(_size, Constants.ENDSIZ); // offset of first CEN header
b.writeUInt32LE(_offset, Constants.ENDOFF); // zip file comment length
b.writeUInt16LE(_commentLength, Constants.ENDCOM); // fill comment memory with spaces so no garbage is left there
b.fill(" ", Constants.ENDHDR);
return b;
},
toJSON: function () {
// creates 0x0000 style output
const offset = function (nr, len) {
let offs = nr.toString(16).toUpperCase();
while (offs.length < len) offs = "0" + offs;
return "0x" + offs;
};
return {
diskEntries: _volumeEntries,
totalEntries: _totalEntries,
size: _size + " bytes",
offset: offset(_offset, 4),
commentLength: _commentLength
};
},
toString: function () {
return JSON.stringify(this.toJSON(), null, "\t");
}
};
};
/***/ }),
/***/ "./node_modules/adm-zip/methods/deflater.js":
/*!**************************************************!*\
!*** ./node_modules/adm-zip/methods/deflater.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = function (
/*Buffer*/
inbuf) {
var zlib = __webpack_require__(/*! zlib */ "zlib");
var opts = {
chunkSize: (parseInt(inbuf.length / 1024) + 1) * 1024
};
return {
deflate: function () {
return zlib.deflateRawSync(inbuf, opts);
},
deflateAsync: function (
/*Function*/
callback) {
var tmp = zlib.createDeflateRaw(opts),
parts = [],
total = 0;
tmp.on("data", function (data) {
parts.push(data);
total += data.length;
});
tmp.on("end", function () {
var buf = Buffer.alloc(total),
written = 0;
buf.fill(0);
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
part.copy(buf, written);
written += part.length;
}
callback && callback(buf);
});
tmp.end(inbuf);
}
};
};
/***/ }),
/***/ "./node_modules/adm-zip/methods/index.js":
/*!***********************************************!*\
!*** ./node_modules/adm-zip/methods/index.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
exports.Deflater = __webpack_require__(/*! ./deflater */ "./node_modules/adm-zip/methods/deflater.js");
exports.Inflater = __webpack_require__(/*! ./inflater */ "./node_modules/adm-zip/methods/inflater.js");
exports.ZipCrypto = __webpack_require__(/*! ./zipcrypto */ "./node_modules/adm-zip/methods/zipcrypto.js");
/***/ }),
/***/ "./node_modules/adm-zip/methods/inflater.js":
/*!**************************************************!*\
!*** ./node_modules/adm-zip/methods/inflater.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = function (
/*Buffer*/
inbuf) {
var zlib = __webpack_require__(/*! zlib */ "zlib");
return {
inflate: function () {
return zlib.inflateRawSync(inbuf);
},
inflateAsync: function (
/*Function*/
callback) {
var tmp = zlib.createInflateRaw(),
parts = [],
total = 0;
tmp.on("data", function (data) {
parts.push(data);
total += data.length;
});
tmp.on("end", function () {
var buf = Buffer.alloc(total),
written = 0;
buf.fill(0);
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
part.copy(buf, written);
written += part.length;
}
callback && callback(buf);
});
tmp.end(inbuf);
}
};
};
/***/ }),
/***/ "./node_modules/adm-zip/methods/zipcrypto.js":
/*!***************************************************!*\
!*** ./node_modules/adm-zip/methods/zipcrypto.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// node crypt, we use it for generate salt
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const _require = __webpack_require__(/*! crypto */ "crypto"),
randomFillSync = _require.randomFillSync; // generate CRC32 lookup table
const crctable = new Uint32Array(256).map((t, crc) => {
for (let j = 0; j < 8; j++) {
if (0 !== (crc & 1)) {
crc = crc >>> 1 ^ 0xedb88320;
} else {
crc >>>= 1;
}
}
return crc >>> 0;
}); // C-style uInt32 Multiply (discards higher bits, when JS multiply discards lower bits)
const uMul = (a, b) => Math.imul(a, b) >>> 0; // crc32 byte single update (actually same function is part of utils.crc32 function :) )
const crc32update = (pCrc32, bval) => {
return crctable[(pCrc32 ^ bval) & 0xff] ^ pCrc32 >>> 8;
}; // function for generating salt for encrytion header
const genSalt = () => {
if ("function" === typeof randomFillSync) {
return randomFillSync(Buffer.alloc(12));
} else {
// fallback if function is not defined
return genSalt.node();
}
}; // salt generation with node random function (mainly as fallback)
genSalt.node = () => {
const salt = Buffer.alloc(12);
const len = salt.length;
for (let i = 0; i < len; i++) salt[i] = Math.random() * 256 & 0xff;
return salt;
}; // general config
const config = {
genSalt
}; // Class Initkeys handles same basic ops with keys
function Initkeys(pw) {
const pass = Buffer.isBuffer(pw) ? pw : Buffer.from(pw);
this.keys = new Uint32Array([0x12345678, 0x23456789, 0x34567890]);
for (let i = 0; i < pass.length; i++) {
this.updateKeys(pass[i]);
}
}
Initkeys.prototype.updateKeys = function (byteValue) {
const keys = this.keys;
keys[0] = crc32update(keys[0], byteValue);
keys[1] += keys[0] & 0xff;
keys[1] = uMul(keys[1], 134775813) + 1;
keys[2] = crc32update(keys[2], keys[1] >>> 24);
return byteValue;
};
Initkeys.prototype.next = function () {
const k = (this.keys[2] | 2) >>> 0; // key
return uMul(k, k ^ 1) >> 8 & 0xff; // decode
};
function make_decrypter(
/*Buffer*/
pwd) {
// 1. Stage initialize key
const keys = new Initkeys(pwd); // return decrypter function
return function (
/*Buffer*/
data) {
// result - we create new Buffer for results
const result = Buffer.alloc(data.length);
let pos = 0; // process input data
for (let c of data) {
//c ^= keys.next();
//result[pos++] = c; // decode & Save Value
result[pos++] = keys.updateKeys(c ^ keys.next()); // update keys with decoded byte
}
return result;
};
}
function make_encrypter(
/*Buffer*/
pwd) {
// 1. Stage initialize key
const keys = new Initkeys(pwd); // return encrypting function, result and pos is here so we dont have to merge buffers later
return function (
/*Buffer*/
data,
/*Buffer*/
result,
/* Number */
pos = 0) {
// result - we create new Buffer for results
if (!result) result = Buffer.alloc(data.length); // process input data
for (let c of data) {
const k = keys.next(); // save key byte
result[pos++] = c ^ k; // save val
keys.updateKeys(c); // update keys with decoded byte
}
return result;
};
}
function decrypt(
/*Buffer*/
data,
/*Object*/
header,
/*String, Buffer*/
pwd) {
if (!data || !Buffer.isBuffer(data) || data.length < 12) {
return Buffer.alloc(0);
} // 1. We Initialize and generate decrypting function
const decrypter = make_decrypter(pwd); // 2. decrypt salt what is always 12 bytes and is a part of file content
const salt = decrypter(data.slice(0, 12)); // 3. does password meet expectations
if (salt[11] !== header.crc >>> 24) {
throw "ADM-ZIP: Wrong Password";
} // 4. decode content
return decrypter(data.slice(12));
} // lets add way to populate salt, NOT RECOMMENDED for production but maybe useful for testing general functionality
function _salter(data) {
if (Buffer.isBuffer(data) && data.length >= 12) {
// be aware - currently salting buffer data is modified
config.genSalt = function () {
return data.slice(0, 12);
};
} else if (data === "node") {
// test salt generation with node random function
config.genSalt = genSalt.node;
} else {
// if value is not acceptable config gets reset.
config.genSalt = genSalt;
}
}
function encrypt(
/*Buffer*/
data,
/*Object*/
header,
/*String, Buffer*/
pwd,
/*Boolean*/
oldlike = false) {
// 1. test data if data is not Buffer we make buffer from it
if (data == null) data = Buffer.alloc(0); // if data is not buffer be make buffer from it
if (!Buffer.isBuffer(data)) data = Buffer.from(data.toString()); // 2. We Initialize and generate encrypting function
const encrypter = make_encrypter(pwd); // 3. generate salt (12-bytes of random data)
const salt = config.genSalt();
salt[11] = header.crc >>> 24 & 0xff; // old implementations (before PKZip 2.04g) used two byte check
if (oldlike) salt[10] = header.crc >>> 16 & 0xff; // 4. create output
const result = Buffer.alloc(data.length + 12);
encrypter(salt, result); // finally encode content
return encrypter(data, result, 12);
}
module.exports = {
decrypt,
encrypt,
_salter
};
/***/ }),
/***/ "./node_modules/adm-zip/util/constants.js":
/*!************************************************!*\
!*** ./node_modules/adm-zip/util/constants.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = {
/* The local file header */
LOCHDR: 30,
// LOC header size
LOCSIG: 0x04034b50,
// "PK\003\004"
LOCVER: 4,
// version needed to extract
LOCFLG: 6,
// general purpose bit flag
LOCHOW: 8,
// compression method
LOCTIM: 10,
// modification time (2 bytes time, 2 bytes date)
LOCCRC: 14,
// uncompressed file crc-32 value
LOCSIZ: 18,
// compressed size
LOCLEN: 22,
// uncompressed size
LOCNAM: 26,
// filename length
LOCEXT: 28,
// extra field length
/* The Data descriptor */
EXTSIG: 0x08074b50,
// "PK\007\008"
EXTHDR: 16,
// EXT header size
EXTCRC: 4,
// uncompressed file crc-32 value
EXTSIZ: 8,
// compressed size
EXTLEN: 12,
// uncompressed size
/* The central directory file header */
CENHDR: 46,
// CEN header size
CENSIG: 0x02014b50,
// "PK\001\002"
CENVEM: 4,
// version made by
CENVER: 6,
// version needed to extract
CENFLG: 8,
// encrypt, decrypt flags
CENHOW: 10,
// compression method
CENTIM: 12,
// modification time (2 bytes time, 2 bytes date)
CENCRC: 16,
// uncompressed file crc-32 value
CENSIZ: 20,
// compressed size
CENLEN: 24,
// uncompressed size
CENNAM: 28,
// filename length
CENEXT: 30,
// extra field length
CENCOM: 32,
// file comment length
CENDSK: 34,
// volume number start
CENATT: 36,
// internal file attributes
CENATX: 38,
// external file attributes (host system dependent)
CENOFF: 42,
// LOC header offset
/* The entries in the end of central directory */
ENDHDR: 22,
// END header size
ENDSIG: 0x06054b50,
// "PK\005\006"
ENDSUB: 8,
// number of entries on this disk
ENDTOT: 10,
// total number of entries
ENDSIZ: 12,
// central directory size in bytes
ENDOFF: 16,
// offset of first CEN header
ENDCOM: 20,
// zip file comment length
END64HDR: 20,
// zip64 END header size
END64SIG: 0x07064b50,
// zip64 Locator signature, "PK\006\007"
END64START: 4,
// number of the disk with the start of the zip64
END64OFF: 8,
// relative offset of the zip64 end of central directory
END64NUMDISKS: 16,
// total number of disks
ZIP64SIG: 0x06064b50,
// zip64 signature, "PK\006\006"
ZIP64HDR: 56,
// zip64 record minimum size
ZIP64LEAD: 12,
// leading bytes at the start of the record, not counted by the value stored in ZIP64SIZE
ZIP64SIZE: 4,
// zip64 size of the central directory record
ZIP64VEM: 12,
// zip64 version made by
ZIP64VER: 14,
// zip64 version needed to extract
ZIP64DSK: 16,
// zip64 number of this disk
ZIP64DSKDIR: 20,
// number of the disk with the start of the record directory
ZIP64SUB: 24,
// number of entries on this disk
ZIP64TOT: 32,
// total number of entries
ZIP64SIZB: 40,
// zip64 central directory size in bytes
ZIP64OFF: 48,
// offset of start of central directory with respect to the starting disk number
ZIP64EXTRA: 56,
// extensible data sector
/* Compression methods */
STORED: 0,
// no compression
SHRUNK: 1,
// shrunk
REDUCED1: 2,
// reduced with compression factor 1
REDUCED2: 3,
// reduced with compression factor 2
REDUCED3: 4,
// reduced with compression factor 3
REDUCED4: 5,
// reduced with compression factor 4
IMPLODED: 6,
// imploded
// 7 reserved for Tokenizing compression algorithm
DEFLATED: 8,
// deflated
ENHANCED_DEFLATED: 9,
// enhanced deflated
PKWARE: 10,
// PKWare DCL imploded
// 11 reserved by PKWARE
BZIP2: 12,
// compressed using BZIP2
// 13 reserved by PKWARE
LZMA: 14,
// LZMA
// 15-17 reserved by PKWARE
IBM_TERSE: 18,
// compressed using IBM TERSE
IBM_LZ77: 19,
// IBM LZ77 z
AES_ENCRYPT: 99,
// WinZIP AES encryption method
/* General purpose bit flag */
// values can obtained with expression 2**bitnr
FLG_ENC: 1,
// Bit 0: encrypted file
FLG_COMP1: 2,
// Bit 1, compression option
FLG_COMP2: 4,
// Bit 2, compression option
FLG_DESC: 8,
// Bit 3, data descriptor
FLG_ENH: 16,
// Bit 4, enhanced deflating
FLG_PATCH: 32,
// Bit 5, indicates that the file is compressed patched data.
FLG_STR: 64,
// Bit 6, strong encryption (patented)
// Bits 7-10: Currently unused.
FLG_EFS: 2048,
// Bit 11: Language encoding flag (EFS)
// Bit 12: Reserved by PKWARE for enhanced compression.
// Bit 13: encrypted the Central Directory (patented).
// Bits 14-15: Reserved by PKWARE.
FLG_MSK: 4096,
// mask header values
/* Load type */
FILE: 2,
BUFFER: 1,
NONE: 0,
/* 4.5 Extensible data fields */
EF_ID: 0,
EF_SIZE: 2,
/* Header IDs */
ID_ZIP64: 0x0001,
ID_AVINFO: 0x0007,
ID_PFS: 0x0008,
ID_OS2: 0x0009,
ID_NTFS: 0x000a,
ID_OPENVMS: 0x000c,
ID_UNIX: 0x000d,
ID_FORK: 0x000e,
ID_PATCH: 0x000f,
ID_X509_PKCS7: 0x0014,
ID_X509_CERTID_F: 0x0015,
ID_X509_CERTID_C: 0x0016,
ID_STRONGENC: 0x0017,
ID_RECORD_MGT: 0x0018,
ID_X509_PKCS7_RL: 0x0019,
ID_IBM1: 0x0065,
ID_IBM2: 0x0066,
ID_POSZIP: 0x4690,
EF_ZIP64_OR_32: 0xffffffff,
EF_ZIP64_OR_16: 0xffff,
EF_ZIP64_SUNCOMP: 0,
EF_ZIP64_SCOMP: 8,
EF_ZIP64_RHO: 16,
EF_ZIP64_DSN: 24
};
/***/ }),
/***/ "./node_modules/adm-zip/util/errors.js":
/*!*********************************************!*\
!*** ./node_modules/adm-zip/util/errors.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = {
/* Header error messages */
INVALID_LOC: "Invalid LOC header (bad signature)",
INVALID_CEN: "Invalid CEN header (bad signature)",
INVALID_END: "Invalid END header (bad signature)",
/* ZipEntry error messages*/
NO_DATA: "Nothing to decompress",
BAD_CRC: "CRC32 checksum failed",
FILE_IN_THE_WAY: "There is a file in the way: %s",
UNKNOWN_METHOD: "Invalid/unsupported compression method",
/* Inflater error messages */
AVAIL_DATA: "inflate::Available inflate data did not terminate",
INVALID_DISTANCE: "inflate::Invalid literal/length or distance code in fixed or dynamic block",
TO_MANY_CODES: "inflate::Dynamic block code description: too many length or distance codes",
INVALID_REPEAT_LEN: "inflate::Dynamic block code description: repeat more than specified lengths",
INVALID_REPEAT_FIRST: "inflate::Dynamic block code description: repeat lengths with no first length",
INCOMPLETE_CODES: "inflate::Dynamic block code description: code lengths codes incomplete",
INVALID_DYN_DISTANCE: "inflate::Dynamic block code description: invalid distance code lengths",
INVALID_CODES_LEN: "inflate::Dynamic block code description: invalid literal/length code lengths",
INVALID_STORE_BLOCK: "inflate::Stored block length did not match one's complement",
INVALID_BLOCK_TYPE: "inflate::Invalid block type (type == 3)",
/* ADM-ZIP error messages */
CANT_EXTRACT_FILE: "Could not extract the file",
CANT_OVERRIDE: "Target file already exists",
NO_ZIP: "No zip file was loaded",
NO_ENTRY: "Entry doesn't exist",
DIRECTORY_CONTENT_ERROR: "A directory cannot have content",
FILE_NOT_FOUND: "File not found: %s",
NOT_IMPLEMENTED: "Not implemented",
INVALID_FILENAME: "Invalid filename",
INVALID_FORMAT: "Invalid or unsupported zip format. No END header found"
};
/***/ }),
/***/ "./node_modules/adm-zip/util/fattr.js":
/*!********************************************!*\
!*** ./node_modules/adm-zip/util/fattr.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const fs = __webpack_require__(/*! ./fileSystem */ "./node_modules/adm-zip/util/fileSystem.js").require();
const pth = __webpack_require__(/*! path */ "path");
fs.existsSync = fs.existsSync || pth.existsSync;
module.exports = function (
/*String*/
path) {
var _path = path || "",
_obj = newAttr(),
_stat = null;
function newAttr() {
return {
directory: false,
readonly: false,
hidden: false,
executable: false,
mtime: 0,
atime: 0
};
}
if (_path && fs.existsSync(_path)) {
_stat = fs.statSync(_path);
_obj.directory = _stat.isDirectory();
_obj.mtime = _stat.mtime;
_obj.atime = _stat.atime;
_obj.executable = (0o111 & _stat.mode) !== 0; // file is executable who ever har right not just owner
_obj.readonly = (0o200 & _stat.mode) === 0; // readonly if owner has no write right
_obj.hidden = pth.basename(_path)[0] === ".";
} else {
console.warn("Invalid path: " + _path);
}
return {
get directory() {
return _obj.directory;
},
get readOnly() {
return _obj.readonly;
},
get hidden() {
return _obj.hidden;
},
get mtime() {
return _obj.mtime;
},
get atime() {
return _obj.atime;
},
get executable() {
return _obj.executable;
},
decodeAttributes: function () {},
encodeAttributes: function () {},
toJSON: function () {
return {
path: _path,
isDirectory: _obj.directory,
isReadOnly: _obj.readonly,
isHidden: _obj.hidden,
isExecutable: _obj.executable,
mTime: _obj.mtime,
aTime: _obj.atime
};
},
toString: function () {
return JSON.stringify(this.toJSON(), null, "\t");
}
};
};
/***/ }),
/***/ "./node_modules/adm-zip/util/fileSystem.js":
/*!*************************************************!*\
!*** ./node_modules/adm-zip/util/fileSystem.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
exports.require = function () {
if (typeof process === "object" && process.versions && process.versions["electron"]) {
try {
const originalFs = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module 'original-fs'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
if (Object.keys(originalFs).length > 0) {
return originalFs;
}
} catch (e) {}
}
return __webpack_require__(/*! fs */ "fs");
};
/***/ }),
/***/ "./node_modules/adm-zip/util/index.js":
/*!********************************************!*\
!*** ./node_modules/adm-zip/util/index.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! ./utils */ "./node_modules/adm-zip/util/utils.js");
module.exports.Constants = __webpack_require__(/*! ./constants */ "./node_modules/adm-zip/util/constants.js");
module.exports.Errors = __webpack_require__(/*! ./errors */ "./node_modules/adm-zip/util/errors.js");
module.exports.FileAttr = __webpack_require__(/*! ./fattr */ "./node_modules/adm-zip/util/fattr.js");
/***/ }),
/***/ "./node_modules/adm-zip/util/utils.js":
/*!********************************************!*\
!*** ./node_modules/adm-zip/util/utils.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const fsystem = __webpack_require__(/*! ./fileSystem */ "./node_modules/adm-zip/util/fileSystem.js").require();
const pth = __webpack_require__(/*! path */ "path");
const Constants = __webpack_require__(/*! ./constants */ "./node_modules/adm-zip/util/constants.js");
const isWin = typeof process === "object" && "win32" === process.platform;
const is_Obj = obj => obj && typeof obj === "object"; // generate CRC32 lookup table
const crcTable = new Uint32Array(256).map((t, c) => {
for (let k = 0; k < 8; k++) {
if ((c & 1) !== 0) {
c = 0xedb88320 ^ c >>> 1;
} else {
c >>>= 1;
}
}
return c >>> 0;
}); // UTILS functions
function Utils(opts) {
this.sep = pth.sep;
this.fs = fsystem;
if (is_Obj(opts)) {
// custom filesystem
if (is_Obj(opts.fs) && typeof opts.fs.statSync === "function") {
this.fs = opts.fs;
}
}
}
module.exports = Utils; // INSTANCED functions
Utils.prototype.makeDir = function (
/*String*/
folder) {
const self = this; // Sync - make directories tree
function mkdirSync(
/*String*/
fpath) {
let resolvedPath = fpath.split(self.sep)[0];
fpath.split(self.sep).forEach(function (name) {
if (!name || name.substr(-1, 1) === ":") return;
resolvedPath += self.sep + name;
var stat;
try {
stat = self.fs.statSync(resolvedPath);
} catch (e) {
self.fs.mkdirSync(resolvedPath);
}
if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY.replace("%s", resolvedPath);
});
}
mkdirSync(folder);
};
Utils.prototype.writeFileTo = function (
/*String*/
path,
/*Buffer*/
content,
/*Boolean*/
overwrite,
/*Number*/
attr) {
const self = this;
if (self.fs.existsSync(path)) {
if (!overwrite) return false; // cannot overwrite
var stat = self.fs.statSync(path);
if (stat.isDirectory()) {
return false;
}
}
var folder = pth.dirname(path);
if (!self.fs.existsSync(folder)) {
self.makeDir(folder);
}
var fd;
try {
fd = self.fs.openSync(path, "w", 438); // 0666
} catch (e) {
self.fs.chmodSync(path, 438);
fd = self.fs.openSync(path, "w", 438);
}
if (fd) {
try {
self.fs.writeSync(fd, content, 0, content.length, 0);
} finally {
self.fs.closeSync(fd);
}
}
self.fs.chmodSync(path, attr || 438);
return true;
};
Utils.prototype.writeFileToAsync = function (
/*String*/
path,
/*Buffer*/
content,
/*Boolean*/
overwrite,
/*Number*/
attr,
/*Function*/
callback) {
if (typeof attr === "function") {
callback = attr;
attr = undefined;
}
const self = this;
self.fs.exists(path, function (exist) {
if (exist && !overwrite) return callback(false);
self.fs.stat(path, function (err, stat) {
if (exist && stat.isDirectory()) {
return callback(false);
}
var folder = pth.dirname(path);
self.fs.exists(folder, function (exists) {
if (!exists) self.makeDir(folder);
self.fs.open(path, "w", 438, function (err, fd) {
if (err) {
self.fs.chmod(path, 438, function () {
self.fs.open(path, "w", 438, function (err, fd) {
self.fs.write(fd, content, 0, content.length, 0, function () {
self.fs.close(fd, function () {
self.fs.chmod(path, attr || 438, function () {
callback(true);
});
});
});
});
});
} else if (fd) {
self.fs.write(fd, content, 0, content.length, 0, function () {
self.fs.close(fd, function () {
self.fs.chmod(path, attr || 438, function () {
callback(true);
});
});
});
} else {
self.fs.chmod(path, attr || 438, function () {
callback(true);
});
}
});
});
});
});
};
Utils.prototype.findFiles = function (
/*String*/
path) {
const self = this;
function findSync(
/*String*/
dir,
/*RegExp*/
pattern,
/*Boolean*/
recursive) {
if (typeof pattern === "boolean") {
recursive = pattern;
pattern = undefined;
}
let files = [];
self.fs.readdirSync(dir).forEach(function (file) {
var path = pth.join(dir, file);
if (self.fs.statSync(path).isDirectory() && recursive) files = files.concat(findSync(path, pattern, recursive));
if (!pattern || pattern.test(path)) {
files.push(pth.normalize(path) + (self.fs.statSync(path).isDirectory() ? self.sep : ""));
}
});
return files;
}
return findSync(path, undefined, true);
};
Utils.prototype.getAttributes = function () {};
Utils.prototype.setAttributes = function () {}; // STATIC functions
// crc32 single update (it is part of crc32)
Utils.crc32update = function (crc, byte) {
return crcTable[(crc ^ byte) & 0xff] ^ crc >>> 8;
};
Utils.crc32 = function (buf) {
if (typeof buf === "string") {
buf = Buffer.from(buf, "utf8");
} // Generate crcTable
if (!crcTable.length) genCRCTable();
let len = buf.length;
let crc = ~0;
for (let off = 0; off < len;) crc = Utils.crc32update(crc, buf[off++]); // xor and cast as uint32 number
return ~crc >>> 0;
};
Utils.methodToString = function (
/*Number*/
method) {
switch (method) {
case Constants.STORED:
return "STORED (" + method + ")";
case Constants.DEFLATED:
return "DEFLATED (" + method + ")";
default:
return "UNSUPPORTED (" + method + ")";
}
}; // removes ".." style path elements
Utils.canonical = function (
/*string*/
path) {
if (!path) return ""; // trick normalize think path is absolute
var safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/"));
return pth.join(".", safeSuffix);
}; // make abolute paths taking prefix as root folder
Utils.sanitize = function (
/*string*/
prefix,
/*string*/
name) {
prefix = pth.resolve(pth.normalize(prefix));
var parts = name.split("/");
for (var i = 0, l = parts.length; i < l; i++) {
var path = pth.normalize(pth.join(prefix, parts.slice(i, l).join(pth.sep)));
if (path.indexOf(prefix) === 0) {
return path;
}
}
return pth.normalize(pth.join(prefix, pth.basename(name)));
}; // converts buffer, Uint8Array, string types to buffer
Utils.toBuffer = function toBuffer(
/*buffer, Uint8Array, string*/
input) {
if (Buffer.isBuffer(input)) {
return input;
} else if (input instanceof Uint8Array) {
return Buffer.from(input);
} else {
// expect string all other values are invalid and return empty buffer
return typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.alloc(0);
}
};
Utils.readBigUInt64LE = function (
/*Buffer*/
buffer,
/*int*/
index) {
var slice = Buffer.from(buffer.slice(index, index + 8));
slice.swap64();
return parseInt(`0x${slice.toString("hex")}`);
};
Utils.isWin = isWin; // Do we have windows system
Utils.crcTable = crcTable;
/***/ }),
/***/ "./node_modules/adm-zip/zipEntry.js":
/*!******************************************!*\
!*** ./node_modules/adm-zip/zipEntry.js ***!
\******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var Utils = __webpack_require__(/*! ./util */ "./node_modules/adm-zip/util/index.js"),
Headers = __webpack_require__(/*! ./headers */ "./node_modules/adm-zip/headers/index.js"),
Constants = Utils.Constants,
Methods = __webpack_require__(/*! ./methods */ "./node_modules/adm-zip/methods/index.js");
module.exports = function (
/*Buffer*/
input) {
var _entryHeader = new Headers.EntryHeader(),
_entryName = Buffer.alloc(0),
_comment = Buffer.alloc(0),
_isDirectory = false,
uncompressedData = null,
_extra = Buffer.alloc(0);
function getCompressedDataFromZip() {
if (!input || !Buffer.isBuffer(input)) {
return Buffer.alloc(0);
}
_entryHeader.loadDataHeaderFromBinary(input);
return input.slice(_entryHeader.realDataOffset, _entryHeader.realDataOffset + _entryHeader.compressedSize);
}
function crc32OK(data) {
// if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the header is written
if ((_entryHeader.flags & 0x8) !== 0x8) {
if (Utils.crc32(data) !== _entryHeader.dataHeader.crc) {
return false;
}
} else {// @TODO: load and check data descriptor header
// The fields in the local header are filled with zero, and the CRC-32 and size are appended in a 12-byte structure
// (optionally preceded by a 4-byte signature) immediately after the compressed data:
}
return true;
}
function decompress(
/*Boolean*/
async,
/*Function*/
callback,
/*String, Buffer*/
pass) {
if (typeof callback === "undefined" && typeof async === "string") {
pass = async;
async = void 0;
}
if (_isDirectory) {
if (async && callback) {
callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR); //si added error.
}
return Buffer.alloc(0);
}
var compressedData = getCompressedDataFromZip();
if (compressedData.length === 0) {
// File is empty, nothing to decompress.
if (async && callback) callback(compressedData);
return compressedData;
}
if (_entryHeader.encripted) {
if ("string" !== typeof pass && !Buffer.isBuffer(pass)) {
throw new Error("ADM-ZIP: Incompatible password parameter");
}
compressedData = Methods.ZipCrypto.decrypt(compressedData, _entryHeader, pass);
}
var data = Buffer.alloc(_entryHeader.size);
switch (_entryHeader.method) {
case Utils.Constants.STORED:
compressedData.copy(data);
if (!crc32OK(data)) {
if (async && callback) callback(data, Utils.Errors.BAD_CRC); //si added error
throw new Error(Utils.Errors.BAD_CRC);
} else {
//si added otherwise did not seem to return data.
if (async && callback) callback(data);
return data;
}
case Utils.Constants.DEFLATED:
var inflater = new Methods.Inflater(compressedData);
if (!async) {
const result = inflater.inflate(data);
result.copy(data, 0);
if (!crc32OK(data)) {
throw new Error(Utils.Errors.BAD_CRC + " " + _entryName.toString());
}
return data;
} else {
inflater.inflateAsync(function (result) {
result.copy(result, 0);
if (callback) {
if (!crc32OK(result)) {
callback(result, Utils.Errors.BAD_CRC); //si added error
} else {
callback(result);
}
}
});
}
break;
default:
if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD);
throw new Error(Utils.Errors.UNKNOWN_METHOD);
}
}
function compress(
/*Boolean*/
async,
/*Function*/
callback) {
if ((!uncompressedData || !uncompressedData.length) && Buffer.isBuffer(input)) {
// no data set or the data wasn't changed to require recompression
if (async && callback) callback(getCompressedDataFromZip());
return getCompressedDataFromZip();
}
if (uncompressedData.length && !_isDirectory) {
var compressedData; // Local file header
switch (_entryHeader.method) {
case Utils.Constants.STORED:
_entryHeader.compressedSize = _entryHeader.size;
compressedData = Buffer.alloc(uncompressedData.length);
uncompressedData.copy(compressedData);
if (async && callback) callback(compressedData);
return compressedData;
default:
case Utils.Constants.DEFLATED:
var deflater = new Methods.Deflater(uncompressedData);
if (!async) {
var deflated = deflater.deflate();
_entryHeader.compressedSize = deflated.length;
return deflated;
} else {
deflater.deflateAsync(function (data) {
compressedData = Buffer.alloc(data.length);
_entryHeader.compressedSize = data.length;
data.copy(compressedData);
callback && callback(compressedData);
});
}
deflater = null;
break;
}
} else if (async && callback) {
callback(Buffer.alloc(0));
} else {
return Buffer.alloc(0);
}
}
function readUInt64LE(buffer, offset) {
return (buffer.readUInt32LE(offset + 4) << 4) + buffer.readUInt32LE(offset);
}
function parseExtra(data) {
var offset = 0;
var signature, size, part;
while (offset < data.length) {
signature = data.readUInt16LE(offset);
offset += 2;
size = data.readUInt16LE(offset);
offset += 2;
part = data.slice(offset, offset + size);
offset += size;
if (Constants.ID_ZIP64 === signature) {
parseZip64ExtendedInformation(part);
}
}
} //Override header field values with values from the ZIP64 extra field
function parseZip64ExtendedInformation(data) {
var size, compressedSize, offset, diskNumStart;
if (data.length >= Constants.EF_ZIP64_SCOMP) {
size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP);
if (_entryHeader.size === Constants.EF_ZIP64_OR_32) {
_entryHeader.size = size;
}
}
if (data.length >= Constants.EF_ZIP64_RHO) {
compressedSize = readUInt64LE(data, Constants.EF_ZIP64_SCOMP);
if (_entryHeader.compressedSize === Constants.EF_ZIP64_OR_32) {
_entryHeader.compressedSize = compressedSize;
}
}
if (data.length >= Constants.EF_ZIP64_DSN) {
offset = readUInt64LE(data, Constants.EF_ZIP64_RHO);
if (_entryHeader.offset === Constants.EF_ZIP64_OR_32) {
_entryHeader.offset = offset;
}
}
if (data.length >= Constants.EF_ZIP64_DSN + 4) {
diskNumStart = data.readUInt32LE(Constants.EF_ZIP64_DSN);
if (_entryHeader.diskNumStart === Constants.EF_ZIP64_OR_16) {
_entryHeader.diskNumStart = diskNumStart;
}
}
}
return {
get entryName() {
return _entryName.toString();
},
get rawEntryName() {
return _entryName;
},
set entryName(val) {
_entryName = Utils.toBuffer(val);
var lastChar = _entryName[_entryName.length - 1];
_isDirectory = lastChar === 47 || lastChar === 92;
_entryHeader.fileNameLength = _entryName.length;
},
get extra() {
return _extra;
},
set extra(val) {
_extra = val;
_entryHeader.extraLength = val.length;
parseExtra(val);
},
get comment() {
return _comment.toString();
},
set comment(val) {
_comment = Utils.toBuffer(val);
_entryHeader.commentLength = _comment.length;
},
get name() {
var n = _entryName.toString();
return _isDirectory ? n.substr(n.length - 1).split("/").pop() : n.split("/").pop();
},
get isDirectory() {
return _isDirectory;
},
getCompressedData: function () {
return compress(false, null);
},
getCompressedDataAsync: function (
/*Function*/
callback) {
compress(true, callback);
},
setData: function (value) {
uncompressedData = Utils.toBuffer(value);
if (!_isDirectory && uncompressedData.length) {
_entryHeader.size = uncompressedData.length;
_entryHeader.method = Utils.Constants.DEFLATED;
_entryHeader.crc = Utils.crc32(value);
_entryHeader.changed = true;
} else {
// folders and blank files should be stored
_entryHeader.method = Utils.Constants.STORED;
}
},
getData: function (pass) {
if (_entryHeader.changed) {
return uncompressedData;
} else {
return decompress(false, null, pass);
}
},
getDataAsync: function (
/*Function*/
callback, pass) {
if (_entryHeader.changed) {
callback(uncompressedData);
} else {
decompress(true, callback, pass);
}
},
set attr(attr) {
_entryHeader.attr = attr;
},
get attr() {
return _entryHeader.attr;
},
set header(
/*Buffer*/
data) {
_entryHeader.loadFromBinary(data);
},
get header() {
return _entryHeader;
},
packHeader: function () {
// 1. create header (buffer)
var header = _entryHeader.entryHeaderToBinary();
var addpos = Utils.Constants.CENHDR; // 2. add file name
_entryName.copy(header, addpos);
addpos += _entryName.length; // 3. add extra data
if (_entryHeader.extraLength) {
_extra.copy(header, addpos);
addpos += _entryHeader.extraLength;
} // 4. add file comment
if (_entryHeader.commentLength) {
_comment.copy(header, addpos);
}
return header;
},
toJSON: function () {
const bytes = function (nr) {
return "<" + (nr && nr.length + " bytes buffer" || "null") + ">";
};
return {
entryName: this.entryName,
name: this.name,
comment: this.comment,
isDirectory: this.isDirectory,
header: _entryHeader.toJSON(),
compressedData: bytes(input),
data: bytes(uncompressedData)
};
},
toString: function () {
return JSON.stringify(this.toJSON(), null, "\t");
}
};
};
/***/ }),
/***/ "./node_modules/adm-zip/zipFile.js":
/*!*****************************************!*\
!*** ./node_modules/adm-zip/zipFile.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const ZipEntry = __webpack_require__(/*! ./zipEntry */ "./node_modules/adm-zip/zipEntry.js");
const Headers = __webpack_require__(/*! ./headers */ "./node_modules/adm-zip/headers/index.js");
const Utils = __webpack_require__(/*! ./util */ "./node_modules/adm-zip/util/index.js");
module.exports = function (
/*Buffer|null*/
inBuffer,
/** object */
options) {
var entryList = [],
entryTable = {},
_comment = Buffer.alloc(0),
mainHeader = new Headers.MainHeader(),
loadedEntries = false; // assign options
const opts = Object.assign(Object.create(null), options);
const noSort = opts.noSort;
if (inBuffer) {
// is a memory buffer
readMainHeader(opts.readEntries);
} else {
// none. is a new file
loadedEntries = true;
}
function iterateEntries(callback) {
const totalEntries = mainHeader.diskEntries; // total number of entries
let index = mainHeader.offset; // offset of first CEN header
for (let i = 0; i < totalEntries; i++) {
let tmp = index;
const entry = new ZipEntry(inBuffer);
entry.header = inBuffer.slice(tmp, tmp += Utils.Constants.CENHDR);
entry.entryName = inBuffer.slice(tmp, tmp += entry.header.fileNameLength);
index += entry.header.entryHeaderSize;
callback(entry);
}
}
function readEntries() {
loadedEntries = true;
entryTable = {};
entryList = new Array(mainHeader.diskEntries); // total number of entries
var index = mainHeader.offset; // offset of first CEN header
for (var i = 0; i < entryList.length; i++) {
var tmp = index,
entry = new ZipEntry(inBuffer);
entry.header = inBuffer.slice(tmp, tmp += Utils.Constants.CENHDR);
entry.entryName = inBuffer.slice(tmp, tmp += entry.header.fileNameLength);
if (entry.header.extraLength) {
entry.extra = inBuffer.slice(tmp, tmp += entry.header.extraLength);
}
if (entry.header.commentLength) entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength);
index += entry.header.entryHeaderSize;
entryList[i] = entry;
entryTable[entry.entryName] = entry;
}
}
function readMainHeader(
/*Boolean*/
readNow) {
var i = inBuffer.length - Utils.Constants.ENDHDR,
// END header size
max = Math.max(0, i - 0xffff),
// 0xFFFF is the max zip file comment length
n = max,
endStart = inBuffer.length,
endOffset = -1,
// Start offset of the END header
commentEnd = 0;
for (i; i >= n; i--) {
if (inBuffer[i] !== 0x50) continue; // quick check that the byte is 'P'
if (inBuffer.readUInt32LE(i) === Utils.Constants.ENDSIG) {
// "PK\005\006"
endOffset = i;
commentEnd = i;
endStart = i + Utils.Constants.ENDHDR; // We already found a regular signature, let's look just a bit further to check if there's any zip64 signature
n = i - Utils.Constants.END64HDR;
continue;
}
if (inBuffer.readUInt32LE(i) === Utils.Constants.END64SIG) {
// Found a zip64 signature, let's continue reading the whole zip64 record
n = max;
continue;
}
if (inBuffer.readUInt32LE(i) === Utils.Constants.ZIP64SIG) {
// Found the zip64 record, let's determine it's size
endOffset = i;
endStart = i + Utils.readBigUInt64LE(inBuffer, i + Utils.Constants.ZIP64SIZE) + Utils.Constants.ZIP64LEAD;
break;
}
}
if (!~endOffset) throw new Error(Utils.Errors.INVALID_FORMAT);
mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart));
if (mainHeader.commentLength) {
_comment = inBuffer.slice(commentEnd + Utils.Constants.ENDHDR);
}
if (readNow) readEntries();
}
function sortEntries() {
if (entryList.length > 1 && !noSort) {
entryList.sort((a, b) => a.entryName.toLowerCase().localeCompare(b.entryName.toLowerCase()));
}
}
return {
/**
* Returns an array of ZipEntry objects existent in the current opened archive
* @return Array
*/
get entries() {
if (!loadedEntries) {
readEntries();
}
return entryList;
},
/**
* Archive comment
* @return {String}
*/
get comment() {
return _comment.toString();
},
set comment(val) {
_comment = Utils.toBuffer(val);
mainHeader.commentLength = _comment.length;
},
getEntryCount: function () {
if (!loadedEntries) {
return mainHeader.diskEntries;
}
return entryList.length;
},
forEach: function (callback) {
if (!loadedEntries) {
iterateEntries(callback);
return;
}
entryList.forEach(callback);
},
/**
* Returns a reference to the entry with the given name or null if entry is inexistent
*
* @param entryName
* @return ZipEntry
*/
getEntry: function (
/*String*/
entryName) {
if (!loadedEntries) {
readEntries();
}
return entryTable[entryName] || null;
},
/**
* Adds the given entry to the entry list
*
* @param entry
*/
setEntry: function (
/*ZipEntry*/
entry) {
if (!loadedEntries) {
readEntries();
}
entryList.push(entry);
entryTable[entry.entryName] = entry;
mainHeader.totalEntries = entryList.length;
},
/**
* Removes the entry with the given name from the entry list.
*
* If the entry is a directory, then all nested files and directories will be removed
* @param entryName
*/
deleteEntry: function (
/*String*/
entryName) {
if (!loadedEntries) {
readEntries();
}
var entry = entryTable[entryName];
if (entry && entry.isDirectory) {
var _self = this;
this.getEntryChildren(entry).forEach(function (child) {
if (child.entryName !== entryName) {
_self.deleteEntry(child.entryName);
}
});
}
entryList.splice(entryList.indexOf(entry), 1);
delete entryTable[entryName];
mainHeader.totalEntries = entryList.length;
},
/**
* Iterates and returns all nested files and directories of the given entry
*
* @param entry
* @return Array
*/
getEntryChildren: function (
/*ZipEntry*/
entry) {
if (!loadedEntries) {
readEntries();
}
if (entry && entry.isDirectory) {
const list = [];
const name = entry.entryName;
const len = name.length;
entryList.forEach(function (zipEntry) {
if (zipEntry.entryName.substr(0, len) === name) {
list.push(zipEntry);
}
});
return list;
}
return [];
},
/**
* Returns the zip file
*
* @return Buffer
*/
compressToBuffer: function () {
if (!loadedEntries) {
readEntries();
}
sortEntries();
const dataBlock = [];
const entryHeaders = [];
let totalSize = 0;
let dindex = 0;
mainHeader.size = 0;
mainHeader.offset = 0;
for (const entry of entryList) {
// compress data and set local and entry header accordingly. Reason why is called first
const compressedData = entry.getCompressedData(); // 1. construct data header
entry.header.offset = dindex;
const dataHeader = entry.header.dataHeaderToBinary();
const entryNameLen = entry.rawEntryName.length; // 1.2. postheader - data after data header
const postHeader = Buffer.alloc(entryNameLen + entry.extra.length);
entry.rawEntryName.copy(postHeader, 0);
postHeader.copy(entry.extra, entryNameLen); // 2. offsets
const dataLength = dataHeader.length + postHeader.length + compressedData.length;
dindex += dataLength; // 3. store values in sequence
dataBlock.push(dataHeader);
dataBlock.push(postHeader);
dataBlock.push(compressedData); // 4. construct entry header
const entryHeader = entry.packHeader();
entryHeaders.push(entryHeader); // 5. update main header
mainHeader.size += entryHeader.length;
totalSize += dataLength + entryHeader.length;
}
totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length
// point to end of data and beginning of central directory first record
mainHeader.offset = dindex;
dindex = 0;
const outBuffer = Buffer.alloc(totalSize); // write data blocks
for (const content of dataBlock) {
content.copy(outBuffer, dindex);
dindex += content.length;
} // write central directory entries
for (const content of entryHeaders) {
content.copy(outBuffer, dindex);
dindex += content.length;
} // write main header
const mh = mainHeader.toBinary();
if (_comment) {
_comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment
}
mh.copy(outBuffer, dindex);
return outBuffer;
},
toAsyncBuffer: function (
/*Function*/
onSuccess,
/*Function*/
onFail,
/*Function*/
onItemStart,
/*Function*/
onItemEnd) {
try {
if (!loadedEntries) {
readEntries();
}
sortEntries();
const dataBlock = [];
const entryHeaders = [];
let totalSize = 0;
let dindex = 0;
mainHeader.size = 0;
mainHeader.offset = 0;
const compress2Buffer = function (entryLists) {
if (entryLists.length) {
const entry = entryLists.pop();
const name = entry.entryName + entry.extra.toString();
if (onItemStart) onItemStart(name);
entry.getCompressedDataAsync(function (compressedData) {
if (onItemEnd) onItemEnd(name);
entry.header.offset = dindex; // data header
const dataHeader = entry.header.dataHeaderToBinary();
const postHeader = Buffer.alloc(name.length, name);
const dataLength = dataHeader.length + postHeader.length + compressedData.length;
dindex += dataLength;
dataBlock.push(dataHeader);
dataBlock.push(postHeader);
dataBlock.push(compressedData);
const entryHeader = entry.packHeader();
entryHeaders.push(entryHeader);
mainHeader.size += entryHeader.length;
totalSize += dataLength + entryHeader.length;
compress2Buffer(entryLists);
});
} else {
totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length
// point to end of data and beginning of central directory first record
mainHeader.offset = dindex;
dindex = 0;
const outBuffer = Buffer.alloc(totalSize);
dataBlock.forEach(function (content) {
content.copy(outBuffer, dindex); // write data blocks
dindex += content.length;
});
entryHeaders.forEach(function (content) {
content.copy(outBuffer, dindex); // write central directory entries
dindex += content.length;
});
const mh = mainHeader.toBinary();
if (_comment) {
_comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment
}
mh.copy(outBuffer, dindex); // write main header
onSuccess(outBuffer);
}
};
compress2Buffer(entryList);
} catch (e) {
onFail(e);
}
}
};
};
/***/ }),
/***/ "./node_modules/array.prototype.filter/implementation.js":
/*!***************************************************************!*\
!*** ./node_modules/array.prototype.filter/implementation.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ArraySpeciesCreate = __webpack_require__(/*! es-abstract/2020/ArraySpeciesCreate */ "./node_modules/es-abstract/2020/ArraySpeciesCreate.js");
var Call = __webpack_require__(/*! es-abstract/2020/Call */ "./node_modules/es-abstract/2020/Call.js");
var CreateDataPropertyOrThrow = __webpack_require__(/*! es-abstract/2020/CreateDataPropertyOrThrow */ "./node_modules/es-abstract/2020/CreateDataPropertyOrThrow.js");
var Get = __webpack_require__(/*! es-abstract/2020/Get */ "./node_modules/es-abstract/2020/Get.js");
var HasProperty = __webpack_require__(/*! es-abstract/2020/HasProperty */ "./node_modules/es-abstract/2020/HasProperty.js");
var IsCallable = __webpack_require__(/*! es-abstract/2020/IsCallable */ "./node_modules/es-abstract/2020/IsCallable.js");
var LengthOfArrayLike = __webpack_require__(/*! es-abstract/2020/LengthOfArrayLike */ "./node_modules/es-abstract/2020/LengthOfArrayLike.js");
var ToBoolean = __webpack_require__(/*! es-abstract/2020/ToBoolean */ "./node_modules/es-abstract/2020/ToBoolean.js");
var ToObject = __webpack_require__(/*! es-abstract/2020/ToObject */ "./node_modules/es-abstract/2020/ToObject.js");
var ToString = __webpack_require__(/*! es-abstract/2020/ToString */ "./node_modules/es-abstract/2020/ToString.js");
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var isString = __webpack_require__(/*! is-string */ "./node_modules/is-string/index.js"); // Check failure of by-index access of string characters (IE < 9) and failure of `0 in boxedString` (Rhino)
var boxedString = Object('a');
var splitString = boxedString[0] !== 'a' || !(0 in boxedString);
var strSplit = callBound('String.prototype.split');
module.exports = function filter(callbackfn) {
var O = ToObject(this);
var self = splitString && isString(O) ? strSplit(O, '') : O;
var len = LengthOfArrayLike(self); // If no callback function or if callback is not a callable function
if (!IsCallable(callbackfn)) {
throw new TypeError('Array.prototype.filter callback must be a function');
}
var thisArg;
if (arguments.length > 1) {
thisArg = arguments[1];
}
var A = ArraySpeciesCreate(O, 0);
var k = 0;
var to = 0;
while (k < len) {
var Pk = ToString(k);
var kPresent = HasProperty(O, Pk);
if (kPresent) {
var kValue = Get(O, Pk);
var selected = ToBoolean(Call(callbackfn, thisArg, [kValue, k, O]));
if (selected) {
CreateDataPropertyOrThrow(A, ToString(to), kValue);
to += 1;
}
}
k += 1;
}
return A;
};
/***/ }),
/***/ "./node_modules/array.prototype.filter/index.js":
/*!******************************************************!*\
!*** ./node_modules/array.prototype.filter/index.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var define = __webpack_require__(/*! define-properties */ "./node_modules/define-properties/index.js");
var RequireObjectCoercible = __webpack_require__(/*! es-abstract/2020/RequireObjectCoercible */ "./node_modules/es-abstract/2020/RequireObjectCoercible.js");
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/array.prototype.filter/implementation.js");
var getPolyfill = __webpack_require__(/*! ./polyfill */ "./node_modules/array.prototype.filter/polyfill.js");
var polyfill = getPolyfill();
var shim = __webpack_require__(/*! ./shim */ "./node_modules/array.prototype.filter/shim.js");
var $slice = callBound('Array.prototype.slice'); // eslint-disable-next-line no-unused-vars
var bound = function filter(array, callbackfn) {
RequireObjectCoercible(array);
return polyfill.apply(array, $slice(arguments, 1));
};
define(bound, {
getPolyfill: getPolyfill,
implementation: implementation,
shim: shim
});
module.exports = bound;
/***/ }),
/***/ "./node_modules/array.prototype.filter/polyfill.js":
/*!*********************************************************!*\
!*** ./node_modules/array.prototype.filter/polyfill.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var arrayMethodBoxesProperly = __webpack_require__(/*! es-array-method-boxes-properly */ "./node_modules/es-array-method-boxes-properly/index.js");
var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/array.prototype.filter/implementation.js");
module.exports = function getPolyfill() {
var method = Array.prototype.filter;
return arrayMethodBoxesProperly(method) ? method : implementation;
};
/***/ }),
/***/ "./node_modules/array.prototype.filter/shim.js":
/*!*****************************************************!*\
!*** ./node_modules/array.prototype.filter/shim.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var define = __webpack_require__(/*! define-properties */ "./node_modules/define-properties/index.js");
var getPolyfill = __webpack_require__(/*! ./polyfill */ "./node_modules/array.prototype.filter/polyfill.js");
module.exports = function shimArrayPrototypeMap() {
var polyfill = getPolyfill();
define(Array.prototype, {
filter: polyfill
}, {
filter: function () {
return Array.prototype.filter !== polyfill;
}
});
return polyfill;
};
/***/ }),
/***/ "./node_modules/available-typed-arrays/index.js":
/*!******************************************************!*\
!*** ./node_modules/available-typed-arrays/index.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var filter = __webpack_require__(/*! array.prototype.filter */ "./node_modules/array.prototype.filter/index.js");
module.exports = function availableTypedArrays() {
return filter(['BigInt64Array', 'BigUint64Array', 'Float32Array', 'Float64Array', 'Int16Array', 'Int32Array', 'Int8Array', 'Uint16Array', 'Uint32Array', 'Uint8Array', 'Uint8ClampedArray'], function (typedArray) {
return typeof global[typedArray] === 'function';
});
};
/***/ }),
/***/ "./node_modules/call-bind/callBound.js":
/*!*********************************************!*\
!*** ./node_modules/call-bind/callBound.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var callBind = __webpack_require__(/*! ./ */ "./node_modules/call-bind/index.js");
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
/***/ }),
/***/ "./node_modules/call-bind/index.js":
/*!*****************************************!*\
!*** ./node_modules/call-bind/index.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(/*! function-bind */ "./node_modules/function-bind/index.js");
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
var $max = GetIntrinsic('%Math.max%');
if ($defineProperty) {
try {
$defineProperty({}, 'a', {
value: 1
});
} catch (e) {
// IE 8 has a broken defineProperty
$defineProperty = null;
}
}
module.exports = function callBind(originalFunction) {
var func = $reflectApply(bind, $call, arguments);
if ($gOPD && $defineProperty) {
var desc = $gOPD(func, 'length');
if (desc.configurable) {
// original length, plus the receiver, minus any additional arguments (after the receiver)
$defineProperty(func, 'length', {
value: 1 + $max(0, originalFunction.length - (arguments.length - 1))
});
}
}
return func;
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', {
value: applyBind
});
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ "./node_modules/charenc/charenc.js":
/*!*****************************************!*\
!*** ./node_modules/charenc/charenc.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {
var charenc = {
// UTF-8 encoding
utf8: {
// Convert a string to a byte array
stringToBytes: function (str) {
return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));
},
// Convert a byte array to a string
bytesToString: function (bytes) {
return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));
}
},
// Binary encoding
bin: {
// Convert a string to a byte array
stringToBytes: function (str) {
for (var bytes = [], i = 0; i < str.length; i++) bytes.push(str.charCodeAt(i) & 0xFF);
return bytes;
},
// Convert a byte array to a string
bytesToString: function (bytes) {
for (var str = [], i = 0; i < bytes.length; i++) str.push(String.fromCharCode(bytes[i]));
return str.join('');
}
}
};
module.exports = charenc;
/***/ }),
/***/ "./node_modules/crypt/crypt.js":
/*!*************************************!*\
!*** ./node_modules/crypt/crypt.js ***!
\*************************************/
/*! no static exports found */
/***/ (function(module, exports) {
(function () {
var base64map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
crypt = {
// Bit-wise rotation left
rotl: function (n, b) {
return n << b | n >>> 32 - b;
},
// Bit-wise rotation right
rotr: function (n, b) {
return n << 32 - b | n >>> b;
},
// Swap big-endian to little-endian and vice versa
endian: function (n) {
// If number given, swap endian
if (n.constructor == Number) {
return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;
} // Else, assume array and swap all items
for (var i = 0; i < n.length; i++) n[i] = crypt.endian(n[i]);
return n;
},
// Generate an array of any length of random bytes
randomBytes: function (n) {
for (var bytes = []; n > 0; n--) bytes.push(Math.floor(Math.random() * 256));
return bytes;
},
// Convert a byte array to big-endian 32-bit words
bytesToWords: function (bytes) {
for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) words[b >>> 5] |= bytes[i] << 24 - b % 32;
return words;
},
// Convert big-endian 32-bit words to a byte array
wordsToBytes: function (words) {
for (var bytes = [], b = 0; b < words.length * 32; b += 8) bytes.push(words[b >>> 5] >>> 24 - b % 32 & 0xFF);
return bytes;
},
// Convert a byte array to a hex string
bytesToHex: function (bytes) {
for (var hex = [], i = 0; i < bytes.length; i++) {
hex.push((bytes[i] >>> 4).toString(16));
hex.push((bytes[i] & 0xF).toString(16));
}
return hex.join('');
},
// Convert a hex string to a byte array
hexToBytes: function (hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
},
// Convert a byte array to a base-64 string
bytesToBase64: function (bytes) {
for (var base64 = [], i = 0; i < bytes.length; i += 3) {
var triplet = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
for (var j = 0; j < 4; j++) if (i * 8 + j * 6 <= bytes.length * 8) base64.push(base64map.charAt(triplet >>> 6 * (3 - j) & 0x3F));else base64.push('=');
}
return base64.join('');
},
// Convert a base-64 string to a byte array
base64ToBytes: function (base64) {
// Remove non-base-64 characters
base64 = base64.replace(/[^A-Z0-9+\/]/ig, '');
for (var bytes = [], i = 0, imod4 = 0; i < base64.length; imod4 = ++i % 4) {
if (imod4 == 0) continue;
bytes.push((base64map.indexOf(base64.charAt(i - 1)) & Math.pow(2, -2 * imod4 + 8) - 1) << imod4 * 2 | base64map.indexOf(base64.charAt(i)) >>> 6 - imod4 * 2);
}
return bytes;
}
};
module.exports = crypt;
})();
/***/ }),
/***/ "./node_modules/csv-parse/lib/ResizeableBuffer.js":
/*!********************************************************!*\
!*** ./node_modules/csv-parse/lib/ResizeableBuffer.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
class ResizeableBuffer {
constructor(size = 100) {
this.size = size;
this.length = 0;
this.buf = Buffer.alloc(size);
}
prepend(val) {
const length = this.length++;
if (length === this.size) {
this.resize();
}
const buf = this.clone();
this.buf[0] = val;
buf.copy(this.buf, 1, 0, length);
}
append(val) {
const length = this.length++;
if (length === this.size) {
this.resize();
}
this.buf[length] = val;
}
clone() {
return Buffer.from(this.buf.slice(0, this.length));
}
resize() {
const length = this.length;
this.size = this.size * 2;
const buf = Buffer.alloc(this.size);
this.buf.copy(buf, 0, 0, length);
this.buf = buf;
}
toString() {
return this.buf.slice(0, this.length).toString();
}
toJSON() {
return this.toString();
}
reset() {
this.length = 0;
}
}
module.exports = ResizeableBuffer;
/***/ }),
/***/ "./node_modules/csv-parse/lib/index.js":
/*!*********************************************!*\
!*** ./node_modules/csv-parse/lib/index.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/*
CSV Parse
Please look at the [project documentation](https://csv.js.org/parse/) for
additional information.
*/
const _require = __webpack_require__(/*! stream */ "stream"),
Transform = _require.Transform;
const ResizeableBuffer = __webpack_require__(/*! ./ResizeableBuffer */ "./node_modules/csv-parse/lib/ResizeableBuffer.js");
const tab = 9;
const nl = 10;
const np = 12;
const cr = 13;
const space = 32;
const bom_utf8 = Buffer.from([239, 187, 191]);
class Parser extends Transform {
constructor(opts = {}) {
super(_objectSpread(_objectSpread({}, {
readableObjectMode: true
}), opts));
const options = {}; // Merge with user options
for (let opt in opts) {
options[underscore(opt)] = opts[opt];
} // Normalize option `bom`
if (options.bom === undefined || options.bom === null || options.bom === false) {
options.bom = false;
} else if (options.bom !== true) {
throw new CsvError('CSV_INVALID_OPTION_BOM', ['Invalid option bom:', 'bom must be true,', `got ${JSON.stringify(options.bom)}`]);
} // Normalize option `cast`
let fnCastField = null;
if (options.cast === undefined || options.cast === null || options.cast === false || options.cast === '') {
options.cast = undefined;
} else if (typeof options.cast === 'function') {
fnCastField = options.cast;
options.cast = true;
} else if (options.cast !== true) {
throw new CsvError('CSV_INVALID_OPTION_CAST', ['Invalid option cast:', 'cast must be true or a function,', `got ${JSON.stringify(options.cast)}`]);
} // Normalize option `cast_date`
if (options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === '') {
options.cast_date = false;
} else if (options.cast_date === true) {
options.cast_date = function (value) {
const date = Date.parse(value);
return !isNaN(date) ? new Date(date) : value;
};
} else if (typeof options.cast_date !== 'function') {
throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', ['Invalid option cast_date:', 'cast_date must be true or a function,', `got ${JSON.stringify(options.cast_date)}`]);
} // Normalize option `columns`
let fnFirstLineToHeaders = null;
if (options.columns === true) {
// Fields in the first line are converted as-is to columns
fnFirstLineToHeaders = undefined;
} else if (typeof options.columns === 'function') {
fnFirstLineToHeaders = options.columns;
options.columns = true;
} else if (Array.isArray(options.columns)) {
options.columns = normalizeColumnsArray(options.columns);
} else if (options.columns === undefined || options.columns === null || options.columns === false) {
options.columns = false;
} else {
throw new CsvError('CSV_INVALID_OPTION_COLUMNS', ['Invalid option columns:', 'expect an object, a function or true,', `got ${JSON.stringify(options.columns)}`]);
} // Normalize option `columns_duplicates_to_array`
if (options.columns_duplicates_to_array === undefined || options.columns_duplicates_to_array === null || options.columns_duplicates_to_array === false) {
options.columns_duplicates_to_array = false;
} else if (options.columns_duplicates_to_array !== true) {
throw new CsvError('CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY', ['Invalid option columns_duplicates_to_array:', 'expect an boolean,', `got ${JSON.stringify(options.columns_duplicates_to_array)}`]);
} // Normalize option `comment`
if (options.comment === undefined || options.comment === null || options.comment === false || options.comment === '') {
options.comment = null;
} else {
if (typeof options.comment === 'string') {
options.comment = Buffer.from(options.comment);
}
if (!Buffer.isBuffer(options.comment)) {
throw new CsvError('CSV_INVALID_OPTION_COMMENT', ['Invalid option comment:', 'comment must be a buffer or a string,', `got ${JSON.stringify(options.comment)}`]);
}
} // Normalize option `delimiter`
const delimiter_json = JSON.stringify(options.delimiter);
if (!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter];
if (options.delimiter.length === 0) {
throw new CsvError('CSV_INVALID_OPTION_DELIMITER', ['Invalid option delimiter:', 'delimiter must be a non empty string or buffer or array of string|buffer,', `got ${delimiter_json}`]);
}
options.delimiter = options.delimiter.map(function (delimiter) {
if (delimiter === undefined || delimiter === null || delimiter === false) {
return Buffer.from(',');
}
if (typeof delimiter === 'string') {
delimiter = Buffer.from(delimiter);
}
if (!Buffer.isBuffer(delimiter) || delimiter.length === 0) {
throw new CsvError('CSV_INVALID_OPTION_DELIMITER', ['Invalid option delimiter:', 'delimiter must be a non empty string or buffer or array of string|buffer,', `got ${delimiter_json}`]);
}
return delimiter;
}); // Normalize option `escape`
if (options.escape === undefined || options.escape === null) {
options.escape = Buffer.from('"');
} else if (typeof options.escape === 'string') {
options.escape = Buffer.from(options.escape);
}
if (!Buffer.isBuffer(options.escape)) {
throw new Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`);
} else if (options.escape.length !== 1) {
throw new Error(`Invalid Option Length: escape must be one character, got ${options.escape.length}`);
} else {
options.escape = options.escape[0];
} // Normalize option `from`
if (options.from === undefined || options.from === null) {
options.from = 1;
} else {
if (typeof options.from === 'string' && /\d+/.test(options.from)) {
options.from = parseInt(options.from);
}
if (Number.isInteger(options.from)) {
if (options.from < 0) {
throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`);
}
} else {
throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`);
}
} // Normalize option `from_line`
if (options.from_line === undefined || options.from_line === null) {
options.from_line = 1;
} else {
if (typeof options.from_line === 'string' && /\d+/.test(options.from_line)) {
options.from_line = parseInt(options.from_line);
}
if (Number.isInteger(options.from_line)) {
if (options.from_line <= 0) {
throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`);
}
} else {
throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`);
}
} // Normalize option `info`
if (options.info === undefined || options.info === null || options.info === false) {
options.info = false;
} else if (options.info !== true) {
throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`);
} // Normalize option `max_record_size`
if (options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false) {
options.max_record_size = 0;
} else if (Number.isInteger(options.max_record_size) && options.max_record_size >= 0) {// Great, nothing to do
} else if (typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)) {
options.max_record_size = parseInt(options.max_record_size);
} else {
throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`);
} // Normalize option `objname`
if (options.objname === undefined || options.objname === null || options.objname === false) {
options.objname = undefined;
} else if (Buffer.isBuffer(options.objname)) {
if (options.objname.length === 0) {
throw new Error(`Invalid Option: objname must be a non empty buffer`);
}
options.objname = options.objname.toString();
} else if (typeof options.objname === 'string') {
if (options.objname.length === 0) {
throw new Error(`Invalid Option: objname must be a non empty string`);
} // Great, nothing to do
} else {
throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`);
} // Normalize option `on_record`
if (options.on_record === undefined || options.on_record === null) {
options.on_record = undefined;
} else if (typeof options.on_record !== 'function') {
throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', ['Invalid option `on_record`:', 'expect a function,', `got ${JSON.stringify(options.on_record)}`]);
} // Normalize option `quote`
if (options.quote === null || options.quote === false || options.quote === '') {
options.quote = null;
} else {
if (options.quote === undefined || options.quote === true) {
options.quote = Buffer.from('"');
} else if (typeof options.quote === 'string') {
options.quote = Buffer.from(options.quote);
}
if (!Buffer.isBuffer(options.quote)) {
throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`);
} else if (options.quote.length !== 1) {
throw new Error(`Invalid Option Length: quote must be one character, got ${options.quote.length}`);
} else {
options.quote = options.quote[0];
}
} // Normalize option `raw`
if (options.raw === undefined || options.raw === null || options.raw === false) {
options.raw = false;
} else if (options.raw !== true) {
throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`);
} // Normalize option `record_delimiter`
if (!options.record_delimiter) {
options.record_delimiter = [];
} else if (!Array.isArray(options.record_delimiter)) {
options.record_delimiter = [options.record_delimiter];
}
options.record_delimiter = options.record_delimiter.map(function (rd) {
if (typeof rd === 'string') {
rd = Buffer.from(rd);
}
return rd;
}); // Normalize option `relax`
if (typeof options.relax === 'boolean') {// Great, nothing to do
} else if (options.relax === undefined || options.relax === null) {
options.relax = false;
} else {
throw new Error(`Invalid Option: relax must be a boolean, got ${JSON.stringify(options.relax)}`);
} // Normalize option `relax_column_count`
if (typeof options.relax_column_count === 'boolean') {// Great, nothing to do
} else if (options.relax_column_count === undefined || options.relax_column_count === null) {
options.relax_column_count = false;
} else {
throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`);
}
if (typeof options.relax_column_count_less === 'boolean') {// Great, nothing to do
} else if (options.relax_column_count_less === undefined || options.relax_column_count_less === null) {
options.relax_column_count_less = false;
} else {
throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`);
}
if (typeof options.relax_column_count_more === 'boolean') {// Great, nothing to do
} else if (options.relax_column_count_more === undefined || options.relax_column_count_more === null) {
options.relax_column_count_more = false;
} else {
throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`);
} // Normalize option `skip_empty_lines`
if (typeof options.skip_empty_lines === 'boolean') {// Great, nothing to do
} else if (options.skip_empty_lines === undefined || options.skip_empty_lines === null) {
options.skip_empty_lines = false;
} else {
throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`);
} // Normalize option `skip_lines_with_empty_values`
if (typeof options.skip_lines_with_empty_values === 'boolean') {// Great, nothing to do
} else if (options.skip_lines_with_empty_values === undefined || options.skip_lines_with_empty_values === null) {
options.skip_lines_with_empty_values = false;
} else {
throw new Error(`Invalid Option: skip_lines_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_lines_with_empty_values)}`);
} // Normalize option `skip_lines_with_error`
if (typeof options.skip_lines_with_error === 'boolean') {// Great, nothing to do
} else if (options.skip_lines_with_error === undefined || options.skip_lines_with_error === null) {
options.skip_lines_with_error = false;
} else {
throw new Error(`Invalid Option: skip_lines_with_error must be a boolean, got ${JSON.stringify(options.skip_lines_with_error)}`);
} // Normalize option `rtrim`
if (options.rtrim === undefined || options.rtrim === null || options.rtrim === false) {
options.rtrim = false;
} else if (options.rtrim !== true) {
throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`);
} // Normalize option `ltrim`
if (options.ltrim === undefined || options.ltrim === null || options.ltrim === false) {
options.ltrim = false;
} else if (options.ltrim !== true) {
throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`);
} // Normalize option `trim`
if (options.trim === undefined || options.trim === null || options.trim === false) {
options.trim = false;
} else if (options.trim !== true) {
throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`);
} // Normalize options `trim`, `ltrim` and `rtrim`
if (options.trim === true && opts.ltrim !== false) {
options.ltrim = true;
} else if (options.ltrim !== true) {
options.ltrim = false;
}
if (options.trim === true && opts.rtrim !== false) {
options.rtrim = true;
} else if (options.rtrim !== true) {
options.rtrim = false;
} // Normalize option `to`
if (options.to === undefined || options.to === null) {
options.to = -1;
} else {
if (typeof options.to === 'string' && /\d+/.test(options.to)) {
options.to = parseInt(options.to);
}
if (Number.isInteger(options.to)) {
if (options.to <= 0) {
throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`);
}
} else {
throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`);
}
} // Normalize option `to_line`
if (options.to_line === undefined || options.to_line === null) {
options.to_line = -1;
} else {
if (typeof options.to_line === 'string' && /\d+/.test(options.to_line)) {
options.to_line = parseInt(options.to_line);
}
if (Number.isInteger(options.to_line)) {
if (options.to_line <= 0) {
throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`);
}
} else {
throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`);
}
}
this.info = {
comment_lines: 0,
empty_lines: 0,
invalid_field_length: 0,
lines: 1,
records: 0
};
this.options = options;
this.state = {
bomSkipped: false,
castField: fnCastField,
commenting: false,
enabled: options.from_line === 1,
escaping: false,
escapeIsQuote: options.escape === options.quote,
expectedRecordLength: options.columns === null ? 0 : options.columns.length,
field: new ResizeableBuffer(20),
firstLineToHeaders: fnFirstLineToHeaders,
info: Object.assign({}, this.info),
previousBuf: undefined,
quoting: false,
stop: false,
rawBuffer: new ResizeableBuffer(100),
record: [],
recordHasError: false,
record_length: 0,
recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 2 : Math.max(...options.record_delimiter.map(v => v.length)),
trimChars: [Buffer.from(' ')[0], Buffer.from('\t')[0]],
wasQuoting: false,
wasRowDelimiter: false
};
} // Implementation of `Transform._transform`
_transform(buf, encoding, callback) {
if (this.state.stop === true) {
return;
}
const err = this.__parse(buf, false);
if (err !== undefined) {
this.state.stop = true;
}
callback(err);
} // Implementation of `Transform._flush`
_flush(callback) {
if (this.state.stop === true) {
return;
}
const err = this.__parse(undefined, true);
callback(err);
} // Central parser implementation
__parse(nextBuf, end) {
const _this$options = this.options,
bom = _this$options.bom,
comment = _this$options.comment,
escape = _this$options.escape,
from_line = _this$options.from_line,
info = _this$options.info,
ltrim = _this$options.ltrim,
max_record_size = _this$options.max_record_size,
quote = _this$options.quote,
raw = _this$options.raw,
relax = _this$options.relax,
rtrim = _this$options.rtrim,
skip_empty_lines = _this$options.skip_empty_lines,
to = _this$options.to,
to_line = _this$options.to_line;
let record_delimiter = this.options.record_delimiter;
const _this$state = this.state,
bomSkipped = _this$state.bomSkipped,
previousBuf = _this$state.previousBuf,
rawBuffer = _this$state.rawBuffer,
escapeIsQuote = _this$state.escapeIsQuote;
let buf;
if (previousBuf === undefined) {
if (nextBuf === undefined) {
// Handle empty string
this.push(null);
return;
} else {
buf = nextBuf;
}
} else if (previousBuf !== undefined && nextBuf === undefined) {
buf = previousBuf;
} else {
buf = Buffer.concat([previousBuf, nextBuf]);
} // Handle UTF BOM
if (bomSkipped === false) {
if (bom === false) {
this.state.bomSkipped = true;
} else if (buf.length < 3) {
// No enough data
if (end === false) {
// Wait for more data
this.state.previousBuf = buf;
return;
} // skip BOM detect because data length < 3
} else {
if (bom_utf8.compare(buf, 0, 3) === 0) {
// Skip BOM
buf = buf.slice(3);
}
this.state.bomSkipped = true;
}
}
const bufLen = buf.length;
let pos;
for (pos = 0; pos < bufLen; pos++) {
// Ensure we get enough space to look ahead
// There should be a way to move this out of the loop
if (this.__needMoreData(pos, bufLen, end)) {
break;
}
if (this.state.wasRowDelimiter === true) {
this.info.lines++;
if (info === true && this.state.record.length === 0 && this.state.field.length === 0 && this.state.wasQuoting === false) {
this.state.info = Object.assign({}, this.info);
}
this.state.wasRowDelimiter = false;
}
if (to_line !== -1 && this.info.lines > to_line) {
this.state.stop = true;
this.push(null);
return;
} // Auto discovery of record_delimiter, unix, mac and windows supported
if (this.state.quoting === false && record_delimiter.length === 0) {
const record_delimiterCount = this.__autoDiscoverRowDelimiter(buf, pos);
if (record_delimiterCount) {
record_delimiter = this.options.record_delimiter;
}
}
const chr = buf[pos];
if (raw === true) {
rawBuffer.append(chr);
}
if ((chr === cr || chr === nl) && this.state.wasRowDelimiter === false) {
this.state.wasRowDelimiter = true;
} // Previous char was a valid escape char
// treat the current char as a regular char
if (this.state.escaping === true) {
this.state.escaping = false;
} else {
// Escape is only active inside quoted fields
// We are quoting, the char is an escape chr and there is a chr to escape
if (this.state.quoting === true && chr === escape && pos + 1 < bufLen) {
if (escapeIsQuote) {
if (buf[pos + 1] === quote) {
this.state.escaping = true;
continue;
}
} else {
this.state.escaping = true;
continue;
}
} // Not currently escaping and chr is a quote
// TODO: need to compare bytes instead of single char
if (this.state.commenting === false && chr === quote) {
if (this.state.quoting === true) {
const nextChr = buf[pos + 1];
const isNextChrTrimable = rtrim && this.__isCharTrimable(nextChr); // const isNextChrComment = nextChr === comment
const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos + 1, nextChr);
const isNextChrDelimiter = this.__isDelimiter(nextChr, buf, pos + 1);
const isNextChrRowDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRowDelimiter(buf, pos + 1) : this.__isRecordDelimiter(nextChr, buf, pos + 1); // Escape a quote
// Treat next char as a regular character
// TODO: need to compare bytes instead of single char
if (chr === escape && nextChr === quote) {
pos++;
} else if (!nextChr || isNextChrDelimiter || isNextChrRowDelimiter || isNextChrComment || isNextChrTrimable) {
this.state.quoting = false;
this.state.wasQuoting = true;
continue;
} else if (relax === false) {
const err = this.__error(new CsvError('CSV_INVALID_CLOSING_QUOTE', ['Invalid Closing Quote:', `got "${String.fromCharCode(nextChr)}"`, `at line ${this.info.lines}`, 'instead of delimiter, row delimiter, trimable character', '(if activated) or comment'], this.__context()));
if (err !== undefined) return err;
} else {
this.state.quoting = false;
this.state.wasQuoting = true; // continue
this.state.field.prepend(quote);
}
} else {
if (this.state.field.length !== 0) {
// In relax mode, treat opening quote preceded by chrs as regular
if (relax === false) {
const err = this.__error(new CsvError('INVALID_OPENING_QUOTE', ['Invalid Opening Quote:', `a quote is found inside a field at line ${this.info.lines}`], this.__context(), {
field: this.state.field
}));
if (err !== undefined) return err;
}
} else {
this.state.quoting = true;
continue;
}
}
}
if (this.state.quoting === false) {
let recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos);
if (recordDelimiterLength !== 0) {
// Do not emit comments which take a full line
const skipCommentLine = this.state.commenting && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0;
if (skipCommentLine) {
this.info.comment_lines++; // Skip full comment line
} else {
// Skip if line is empty and skip_empty_lines activated
if (skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0) {
this.info.empty_lines++;
pos += recordDelimiterLength - 1;
continue;
} // Activate records emition if above from_line
if (this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1 : 0) >= from_line) {
this.state.enabled = true;
this.__resetField();
this.__resetRow();
pos += recordDelimiterLength - 1;
continue;
} else {
const errField = this.__onField();
if (errField !== undefined) return errField;
const errRecord = this.__onRow();
if (errRecord !== undefined) return errRecord;
}
if (to !== -1 && this.info.records >= to) {
this.state.stop = true;
this.push(null);
return;
}
}
this.state.commenting = false;
pos += recordDelimiterLength - 1;
continue;
}
if (this.state.commenting) {
continue;
}
const commentCount = comment === null ? 0 : this.__compareBytes(comment, buf, pos, chr);
if (commentCount !== 0) {
this.state.commenting = true;
continue;
}
let delimiterLength = this.__isDelimiter(chr, buf, pos);
if (delimiterLength !== 0) {
const errField = this.__onField();
if (errField !== undefined) return errField;
pos += delimiterLength - 1;
continue;
}
}
}
if (this.state.commenting === false) {
if (max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size) {
const err = this.__error(new CsvError('CSV_MAX_RECORD_SIZE', ['Max Record Size:', 'record exceed the maximum number of tolerated bytes', `of ${max_record_size}`, `at line ${this.info.lines}`], this.__context()));
if (err !== undefined) return err;
}
}
const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(chr); // rtrim in non quoting is handle in __onField
const rappend = rtrim === false || this.state.wasQuoting === false;
if (lappend === true && rappend === true) {
this.state.field.append(chr);
} else if (rtrim === true && !this.__isCharTrimable(chr)) {
const err = this.__error(new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', ['Invalid Closing Quote:', 'found non trimable byte after quote', `at line ${this.info.lines}`], this.__context()));
if (err !== undefined) return err;
}
}
if (end === true) {
// Ensure we are not ending in a quoting state
if (this.state.quoting === true) {
const err = this.__error(new CsvError('CSV_QUOTE_NOT_CLOSED', ['Quote Not Closed:', `the parsing is finished with an opening quote at line ${this.info.lines}`], this.__context()));
if (err !== undefined) return err;
} else {
// Skip last line if it has no characters
if (this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0) {
const errField = this.__onField();
if (errField !== undefined) return errField;
const errRecord = this.__onRow();
if (errRecord !== undefined) return errRecord;
} else if (this.state.wasRowDelimiter === true) {
this.info.empty_lines++;
} else if (this.state.commenting === true) {
this.info.comment_lines++;
}
}
} else {
this.state.previousBuf = buf.slice(pos);
}
if (this.state.wasRowDelimiter === true) {
this.info.lines++;
this.state.wasRowDelimiter = false;
}
} // Helper to test if a character is a space or a line delimiter
__isCharTrimable(chr) {
return chr === space || chr === tab || chr === cr || chr === nl || chr === np;
}
__onRow() {
const _this$options2 = this.options,
columns = _this$options2.columns,
columns_duplicates_to_array = _this$options2.columns_duplicates_to_array,
info = _this$options2.info,
from = _this$options2.from,
relax_column_count = _this$options2.relax_column_count,
relax_column_count_less = _this$options2.relax_column_count_less,
relax_column_count_more = _this$options2.relax_column_count_more,
raw = _this$options2.raw,
skip_lines_with_empty_values = _this$options2.skip_lines_with_empty_values;
const _this$state2 = this.state,
enabled = _this$state2.enabled,
record = _this$state2.record;
if (enabled === false) {
return this.__resetRow();
} // Convert the first line into column names
const recordLength = record.length;
if (columns === true) {
if (isRecordEmpty(record)) {
this.__resetRow();
return;
}
return this.__firstLineToColumns(record);
}
if (columns === false && this.info.records === 0) {
this.state.expectedRecordLength = recordLength;
}
if (recordLength !== this.state.expectedRecordLength) {
if (relax_column_count === true || relax_column_count_less === true && recordLength < this.state.expectedRecordLength || relax_column_count_more === true && recordLength > this.state.expectedRecordLength) {
this.info.invalid_field_length++;
} else {
if (columns === false) {
const err = this.__error(new CsvError('CSV_INCONSISTENT_RECORD_LENGTH', ['Invalid Record Length:', `expect ${this.state.expectedRecordLength},`, `got ${recordLength} on line ${this.info.lines}`], this.__context(), {
record: record
}));
if (err !== undefined) return err;
} else {
const err = this.__error( // CSV_INVALID_RECORD_LENGTH_DONT_MATCH_COLUMNS
new CsvError('CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH', ['Invalid Record Length:', `columns length is ${columns.length},`, // rename columns
`got ${recordLength} on line ${this.info.lines}`], this.__context(), {
record: record
}));
if (err !== undefined) return err;
}
}
}
if (skip_lines_with_empty_values === true) {
if (isRecordEmpty(record)) {
this.__resetRow();
return;
}
}
if (this.state.recordHasError === true) {
this.__resetRow();
this.state.recordHasError = false;
return;
}
this.info.records++;
if (from === 1 || this.info.records >= from) {
if (columns !== false) {
const obj = {}; // Transform record array to an object
for (let i = 0, l = record.length; i < l; i++) {
if (columns[i] === undefined || columns[i].disabled) continue; // obj[columns[i].name] = record[i]
// Turn duplicate columns into an array
if (columns_duplicates_to_array === true && obj[columns[i].name]) {
if (Array.isArray(obj[columns[i].name])) {
obj[columns[i].name] = obj[columns[i].name].concat(record[i]);
} else {
obj[columns[i].name] = [obj[columns[i].name], record[i]];
}
} else {
obj[columns[i].name] = record[i];
}
}
const objname = this.options.objname;
if (objname === undefined) {
if (raw === true || info === true) {
const err = this.__push(Object.assign({
record: obj
}, raw === true ? {
raw: this.state.rawBuffer.toString()
} : {}, info === true ? {
info: this.state.info
} : {}));
if (err) {
return err;
}
} else {
const err = this.__push(obj);
if (err) {
return err;
}
}
} else {
if (raw === true || info === true) {
const err = this.__push(Object.assign({
record: [obj[objname], obj]
}, raw === true ? {
raw: this.state.rawBuffer.toString()
} : {}, info === true ? {
info: this.state.info
} : {}));
if (err) {
return err;
}
} else {
const err = this.__push([obj[objname], obj]);
if (err) {
return err;
}
}
}
} else {
if (raw === true || info === true) {
const err = this.__push(Object.assign({
record: record
}, raw === true ? {
raw: this.state.rawBuffer.toString()
} : {}, info === true ? {
info: this.state.info
} : {}));
if (err) {
return err;
}
} else {
const err = this.__push(record);
if (err) {
return err;
}
}
}
}
this.__resetRow();
}
__firstLineToColumns(record) {
const firstLineToHeaders = this.state.firstLineToHeaders;
try {
const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record);
if (!Array.isArray(headers)) {
return this.__error(new CsvError('CSV_INVALID_COLUMN_MAPPING', ['Invalid Column Mapping:', 'expect an array from column function,', `got ${JSON.stringify(headers)}`], this.__context(), {
headers: headers
}));
}
const normalizedHeaders = normalizeColumnsArray(headers);
this.state.expectedRecordLength = normalizedHeaders.length;
this.options.columns = normalizedHeaders;
this.__resetRow();
return;
} catch (err) {
return err;
}
}
__resetRow() {
if (this.options.raw === true) {
this.state.rawBuffer.reset();
}
this.state.record = [];
this.state.record_length = 0;
}
__onField() {
const _this$options3 = this.options,
cast = _this$options3.cast,
rtrim = _this$options3.rtrim,
max_record_size = _this$options3.max_record_size;
const _this$state3 = this.state,
enabled = _this$state3.enabled,
wasQuoting = _this$state3.wasQuoting; // Short circuit for the from_line options
if (enabled === false) {
/* this.options.columns !== true && */
return this.__resetField();
}
let field = this.state.field.toString();
if (rtrim === true && wasQuoting === false) {
field = field.trimRight();
}
if (cast === true) {
const _this$__cast = this.__cast(field),
_this$__cast2 = _slicedToArray(_this$__cast, 2),
err = _this$__cast2[0],
f = _this$__cast2[1];
if (err !== undefined) return err;
field = f;
}
this.state.record.push(field); // Increment record length if record size must not exceed a limit
if (max_record_size !== 0 && typeof field === 'string') {
this.state.record_length += field.length;
}
this.__resetField();
}
__resetField() {
this.state.field.reset();
this.state.wasQuoting = false;
}
__push(record) {
const on_record = this.options.on_record;
if (on_record !== undefined) {
const context = this.__context();
try {
record = on_record.call(null, record, context);
} catch (err) {
return err;
}
if (record === undefined || record === null) {
return;
}
}
this.push(record);
} // Return a tuple with the error and the casted value
__cast(field) {
const _this$options4 = this.options,
columns = _this$options4.columns,
relax_column_count = _this$options4.relax_column_count;
const isColumns = Array.isArray(columns); // Dont loose time calling cast
// because the final record is an object
// and this field can't be associated to a key present in columns
if (isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length) {
return [undefined, undefined];
}
const context = this.__context();
if (this.state.castField !== null) {
try {
return [undefined, this.state.castField.call(null, field, context)];
} catch (err) {
return [err];
}
}
if (this.__isFloat(field)) {
return [undefined, parseFloat(field)];
} else if (this.options.cast_date !== false) {
return [undefined, this.options.cast_date.call(null, field, context)];
}
return [undefined, field];
} // Keep it in case we implement the `cast_int` option
// __isInt(value){
// // return Number.isInteger(parseInt(value))
// // return !isNaN( parseInt( obj ) );
// return /^(\-|\+)?[1-9][0-9]*$/.test(value)
// }
__isFloat(value) {
return value - parseFloat(value) + 1 >= 0; // Borrowed from jquery
}
__compareBytes(sourceBuf, targetBuf, pos, firtByte) {
if (sourceBuf[0] !== firtByte) return 0;
const sourceLength = sourceBuf.length;
for (let i = 1; i < sourceLength; i++) {
if (sourceBuf[i] !== targetBuf[pos + i]) return 0;
}
return sourceLength;
}
__needMoreData(i, bufLen, end) {
if (end) {
return false;
}
const _this$options5 = this.options,
comment = _this$options5.comment,
delimiter = _this$options5.delimiter;
const _this$state4 = this.state,
quoting = _this$state4.quoting,
recordDelimiterMaxLength = _this$state4.recordDelimiterMaxLength;
const numOfCharLeft = bufLen - i - 1;
const requiredLength = Math.max( // Skip if the remaining buffer smaller than comment
comment ? comment.length : 0, // Skip if the remaining buffer smaller than row delimiter
recordDelimiterMaxLength, // Skip if the remaining buffer can be row delimiter following the closing quote
// 1 is for quote.length
quoting ? 1 + recordDelimiterMaxLength : 0, // Skip if the remaining buffer can be delimiter
delimiter.length, // Skip if the remaining buffer can be escape sequence
// 1 is for escape.length
1);
return numOfCharLeft < requiredLength;
}
__isDelimiter(chr, buf, pos) {
const delimiter = this.options.delimiter;
loop1: for (let i = 0; i < delimiter.length; i++) {
const del = delimiter[i];
if (del[0] === chr) {
for (let j = 1; j < del.length; j++) {
if (del[j] !== buf[pos + j]) continue loop1;
}
return del.length;
}
}
return 0;
}
__isRecordDelimiter(chr, buf, pos) {
const record_delimiter = this.options.record_delimiter;
const recordDelimiterLength = record_delimiter.length;
loop1: for (let i = 0; i < recordDelimiterLength; i++) {
const rd = record_delimiter[i];
const rdLength = rd.length;
if (rd[0] !== chr) {
continue;
}
for (let j = 1; j < rdLength; j++) {
if (rd[j] !== buf[pos + j]) {
continue loop1;
}
}
return rd.length;
}
return 0;
}
__autoDiscoverRowDelimiter(buf, pos) {
const chr = buf[pos];
if (chr === cr) {
if (buf[pos + 1] === nl) {
this.options.record_delimiter.push(Buffer.from('\r\n'));
this.state.recordDelimiterMaxLength = 2;
return 2;
} else {
this.options.record_delimiter.push(Buffer.from('\r'));
this.state.recordDelimiterMaxLength = 1;
return 1;
}
} else if (chr === nl) {
this.options.record_delimiter.push(Buffer.from('\n'));
this.state.recordDelimiterMaxLength = 1;
return 1;
}
return 0;
}
__error(msg) {
const skip_lines_with_error = this.options.skip_lines_with_error;
const err = typeof msg === 'string' ? new Error(msg) : msg;
if (skip_lines_with_error) {
this.state.recordHasError = true;
this.emit('skip', err);
return undefined;
} else {
return err;
}
}
__context() {
const columns = this.options.columns;
const isColumns = Array.isArray(columns);
return {
column: isColumns === true ? columns.length > this.state.record.length ? columns[this.state.record.length].name : null : this.state.record.length,
empty_lines: this.info.empty_lines,
header: columns === true,
index: this.state.record.length,
invalid_field_length: this.info.invalid_field_length,
quoting: this.state.wasQuoting,
lines: this.info.lines,
records: this.info.records
};
}
}
const parse = function () {
let data, options, callback;
for (let i in arguments) {
const argument = arguments[i];
const type = typeof argument;
if (data === undefined && (typeof argument === 'string' || Buffer.isBuffer(argument))) {
data = argument;
} else if (options === undefined && isObject(argument)) {
options = argument;
} else if (callback === undefined && type === 'function') {
callback = argument;
} else {
throw new CsvError('CSV_INVALID_ARGUMENT', ['Invalid argument:', `got ${JSON.stringify(argument)} at index ${i}`]);
}
}
const parser = new Parser(options);
if (callback) {
const records = options === undefined || options.objname === undefined ? [] : {};
parser.on('readable', function () {
let record;
while ((record = this.read()) !== null) {
if (options === undefined || options.objname === undefined) {
records.push(record);
} else {
records[record[0]] = record[1];
}
}
});
parser.on('error', function (err) {
callback(err, undefined, parser.info);
});
parser.on('end', function () {
callback(undefined, records, parser.info);
});
}
if (data !== undefined) {
// Give a chance for events to be registered later
if (typeof setImmediate === 'function') {
setImmediate(function () {
parser.write(data);
parser.end();
});
} else {
parser.write(data);
parser.end();
}
}
return parser;
};
class CsvError extends Error {
constructor(code, message, ...contexts) {
if (Array.isArray(message)) message = message.join(' ');
super(message);
if (Error.captureStackTrace !== undefined) {
Error.captureStackTrace(this, CsvError);
}
this.code = code;
for (const context of contexts) {
for (const key in context) {
const value = context[key];
this[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value));
}
}
}
}
parse.Parser = Parser;
parse.CsvError = CsvError;
module.exports = parse;
const underscore = function (str) {
return str.replace(/([A-Z])/g, function (_, match) {
return '_' + match.toLowerCase();
});
};
const isObject = function (obj) {
return typeof obj === 'object' && obj !== null && !Array.isArray(obj);
};
const isRecordEmpty = function (record) {
return record.every(field => field == null || field.toString && field.toString().trim() === '');
};
const normalizeColumnsArray = function (columns) {
const normalizedColumns = [];
for (let i = 0, l = columns.length; i < l; i++) {
const column = columns[i];
if (column === undefined || column === null || column === false) {
normalizedColumns[i] = {
disabled: true
};
} else if (typeof column === 'string') {
normalizedColumns[i] = {
name: column
};
} else if (isObject(column)) {
if (typeof column.name !== 'string') {
throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', ['Option columns missing name:', `property "name" is required at position ${i}`, 'when column is an object literal']);
}
normalizedColumns[i] = column;
} else {
throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', ['Invalid column definition:', 'expect a string or a literal object,', `got ${JSON.stringify(column)} at position ${i}`]);
}
}
return normalizedColumns;
};
/***/ }),
/***/ "./node_modules/csv-parse/lib/sync.js":
/*!********************************************!*\
!*** ./node_modules/csv-parse/lib/sync.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const parse = __webpack_require__(/*! . */ "./node_modules/csv-parse/lib/index.js");
module.exports = function (data, options = {}) {
if (typeof data === 'string') {
data = Buffer.from(data);
}
const records = options && options.objname ? {} : [];
const parser = new parse.Parser(options);
parser.push = function (record) {
if (record === null) {
return;
}
if (options.objname === undefined) records.push(record);else {
records[record[0]] = record[1];
}
};
const err1 = parser.__parse(data, false);
if (err1 !== undefined) throw err1;
const err2 = parser.__parse(undefined, true);
if (err2 !== undefined) throw err2;
return records;
};
/***/ }),
/***/ "./node_modules/csv-stringify/lib/index.js":
/*!*************************************************!*\
!*** ./node_modules/csv-stringify/lib/index.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const _excluded = ["value"];
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
// Generated by CoffeeScript 2.4.1
// # CSV Stringifier
// Please look at the [project documentation](https://csv.js.org/stringify/) for additional
// information.
var Stringifier, castPath, charCodeOfDot, get, getTag, isKey, isObject, isSymbol, reEscapeChar, reIsDeepProp, reIsPlainProp, rePropName, stream, stringToPath, toKey, underscore, util;
stream = __webpack_require__(/*! stream */ "stream");
util = __webpack_require__(/*! util */ "util"); // ## Usage
// This module export a function as its main entry point and return a transform
// stream.
// Refers to the [official prject documentation](http://csv.js.org/stringify/)
// on how to call this function.
module.exports = function () {
var callback, chunks, data, options, stringifier;
if (arguments.length === 3) {
data = arguments[0];
options = arguments[1];
callback = arguments[2];
} else if (arguments.length === 2) {
if (Array.isArray(arguments[0])) {
data = arguments[0];
} else {
options = arguments[0];
}
if (typeof arguments[1] === 'function') {
callback = arguments[1];
} else {
options = arguments[1];
}
} else if (arguments.length === 1) {
if (typeof arguments[0] === 'function') {
callback = arguments[0];
} else if (Array.isArray(arguments[0])) {
data = arguments[0];
} else {
options = arguments[0];
}
}
if (options == null) {
options = {};
}
stringifier = new Stringifier(options);
if (data) {
process.nextTick(function () {
var d, j, len;
for (j = 0, len = data.length; j < len; j++) {
d = data[j];
stringifier.write(d);
}
return stringifier.end();
});
}
if (callback) {
chunks = [];
stringifier.on('readable', function () {
var chunk, results;
results = [];
while (chunk = stringifier.read()) {
results.push(chunks.push(chunk));
}
return results;
});
stringifier.on('error', function (err) {
return callback(err);
});
stringifier.on('end', function () {
return callback(null, chunks.join(''));
});
}
return stringifier;
}; // You can also use *util.promisify* native function (Node.js 8+) in order to wrap callbacks into promises for more convenient use when source is a readable stream and you are OK with storing entire result set in memory:
// ```
// const { promisify } = require('util');
// const csv = require('csv');
// const stringifyAsync = promisify(csv.stringify);
// //returns promise
// function generateCsv(sourceData) {
// return stringifyAsync(sourceData);
// }
// ```
// ## `Stringifier([options])`
// Options are documented [here](http://csv.adaltas.com/stringify/).
Stringifier = class Stringifier extends stream.Transform {
constructor(opts = {}) {
var base, base1, base2, base3, base4, isRegExp, isString, j, k, len, options, quoted_match, ref, v;
super(_objectSpread(_objectSpread({}, {
writableObjectMode: true
}), opts));
options = {};
for (k in opts) {
v = opts[k]; // Immutable options and camelcase conversion
options[underscore(k)] = v;
} // Normalize option `delimiter`
if (options.delimiter === null || options.delimiter === void 0) {
options.delimiter = ',';
} else {
if (Buffer.isBuffer(options.delimiter)) {
options.delimiter = options.delimiter.toString();
} else if (typeof options.delimiter !== 'string') {
throw new Error(`Invalid Option: delimiter must be a buffer or a string, got ${JSON.stringify(options.delimiter)}`);
}
} // Normalize option `quote`
if (options.quote === null || options.quote === void 0) {
options.quote = '"';
} else {
if (options.quote === true) {
options.quote = '"';
} else if (options.quote === false) {
options.quote = '';
} else if (Buffer.isBuffer(options.quote)) {
options.quote = options.quote.toString();
} else if (typeof options.quote !== 'string') {
throw new Error(`Invalid Option: quote must be a boolean, a buffer or a string, got ${JSON.stringify(options.quote)}`);
}
} // Normalize option `quoted`
if (options.quoted == null) {
options.quoted = false;
}
if (options.quoted_empty == null) {
options.quoted_empty = void 0;
}
if (options.quoted_string == null) {
options.quoted_string = false;
}
if (options.eof == null) {
options.eof = true;
} // Normalize option `escape`
if (options.escape === null || options.escape === void 0) {
options.escape = '"';
} else {
if (Buffer.isBuffer(options.escape)) {
options.escape = options.escape.toString();
}
if (typeof options.escape !== 'string') {
throw new Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`);
} else if (options.escape.length > 1) {
throw new Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`);
}
}
if (options.header == null) {
options.header = false;
} // Normalize the columns option
options.columns = this.normalize_columns(options.columns);
if (options.cast == null) {
options.cast = {};
} // Normalize option `quoted_match`
if (options.quoted_match === void 0 || options.quoted_match === null || options.quoted_match === false) {
options.quoted_match = null;
} else if (!Array.isArray(options.quoted_match)) {
options.quoted_match = [options.quoted_match];
}
if (options.quoted_match) {
ref = options.quoted_match;
for (j = 0, len = ref.length; j < len; j++) {
quoted_match = ref[j];
isString = typeof quoted_match === 'string';
isRegExp = quoted_match instanceof RegExp;
if (!isString && !isRegExp) {
throw new Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`);
}
}
}
if (options.cast.bool) {
// Backward compatibility
options.cast.boolean = options.cast.bool;
} // Custom cast
if ((base = options.cast).boolean == null) {
base.boolean = function (value) {
// Cast boolean to string by default
if (value) {
return '1';
} else {
return '';
}
};
}
if ((base1 = options.cast).date == null) {
base1.date = function (value) {
// Cast date to timestamp string by default
return '' + value.getTime();
};
}
if ((base2 = options.cast).number == null) {
base2.number = function (value) {
// Cast number to string using native casting by default
return '' + value;
};
}
if ((base3 = options.cast).object == null) {
base3.object = function (value) {
// Stringify object as JSON by default
return JSON.stringify(value);
};
}
if ((base4 = options.cast).string == null) {
base4.string = function (value) {
return value;
};
} // Normalize option `record_delimiter`
if (options.record_delimiter === void 0 || options.record_delimiter === null) {
if (options.record_delimiter == null) {
options.record_delimiter = '\n';
}
} else {
if (Buffer.isBuffer(options.record_delimiter)) {
options.record_delimiter = options.record_delimiter.toString();
} else if (typeof options.record_delimiter !== 'string') {
throw new Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`);
}
switch (options.record_delimiter) {
case 'auto':
options.record_delimiter = null;
break;
case 'unix':
options.record_delimiter = "\n";
break;
case 'mac':
options.record_delimiter = "\r";
break;
case 'windows':
options.record_delimiter = "\r\n";
break;
case 'ascii':
options.record_delimiter = "\u001e";
break;
case 'unicode':
options.record_delimiter = "\u2028";
}
} // Expose options
this.options = options; // Internal state
this.state = {
stop: false
}; // Information
this.info = {
records: 0
};
this;
} // ## `Stringifier.prototype._transform(chunk, encoding, callback)`
// Implementation of the [transform._transform function](https://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callback).
_transform(chunk, encoding, callback) {
var base, e;
if (this.state.stop === true) {
return;
} // Chunk validation
if (!(Array.isArray(chunk) || typeof chunk === 'object')) {
this.state.stop = true;
return callback(Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`));
} // Detect columns from the first record
if (this.info.records === 0) {
if (Array.isArray(chunk)) {
if (this.options.header === true && !this.options.columns) {
this.state.stop = true;
return callback(Error('Undiscoverable Columns: header option requires column option or object records'));
}
} else {
if ((base = this.options).columns == null) {
base.columns = this.normalize_columns(Object.keys(chunk));
}
}
}
if (this.info.records === 0) {
// Emit the header
this.headers();
}
try {
// Emit and stringify the record if an object or an array
this.emit('record', chunk, this.info.records);
} catch (error) {
e = error;
this.state.stop = true;
return this.emit('error', e);
} // Convert the record into a string
if (this.options.eof) {
chunk = this.stringify(chunk);
if (chunk == null) {
return;
}
chunk = chunk + this.options.record_delimiter;
} else {
chunk = this.stringify(chunk);
if (chunk == null) {
return;
}
if (this.options.header || this.info.records) {
chunk = this.options.record_delimiter + chunk;
}
} // Emit the csv
this.info.records++;
this.push(chunk);
return callback();
} // ## `Stringifier.prototype._flush(callback)`
// Implementation of the [transform._flush function](https://nodejs.org/api/stream.html#stream_transform_flush_callback).
_flush(callback) {
if (this.info.records === 0) {
this.headers();
}
return callback();
} // ## `Stringifier.prototype.stringify(line)`
// Convert a line to a string. Line may be an object, an array or a string.
stringify(chunk, chunkIsHeader = false) {
var column, columns, containsEscape, containsQuote, containsRowDelimiter, containsdelimiter, csvrecord, delimiter, err, escape, field, header, i, j, l, len, m, options, quote, quoted, quotedMatch, quotedString, quoted_empty, quoted_match, quoted_string, record, record_delimiter, ref, ref1, regexp, shouldQuote, value;
if (typeof chunk !== 'object') {
return chunk;
}
var _this$options = this.options;
columns = _this$options.columns;
header = _this$options.header;
record = []; // Record is an array
if (Array.isArray(chunk)) {
if (columns) {
// We are getting an array but the user has specified output columns. In
// this case, we respect the columns indexes
chunk.splice(columns.length);
} // Cast record elements
for (i = j = 0, len = chunk.length; j < len; i = ++j) {
field = chunk[i];
var _this$__cast = this.__cast(field, {
index: i,
column: i,
records: this.info.records,
header: chunkIsHeader
});
var _this$__cast2 = _slicedToArray(_this$__cast, 2);
err = _this$__cast2[0];
value = _this$__cast2[1];
if (err) {
this.emit('error', err);
return;
}
record[i] = [value, field];
}
} else {
// Record is a literal object
if (columns) {
for (i = l = 0, ref = columns.length; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
field = get(chunk, columns[i].key);
var _this$__cast3 = this.__cast(field, {
index: i,
column: columns[i].key,
records: this.info.records,
header: chunkIsHeader
});
var _this$__cast4 = _slicedToArray(_this$__cast3, 2);
err = _this$__cast4[0];
value = _this$__cast4[1];
if (err) {
this.emit('error', err);
return;
}
record[i] = [value, field];
}
} else {
for (column in chunk) {
field = chunk[column];
var _this$__cast5 = this.__cast(field, {
index: i,
column: columns[i].key,
records: this.info.records,
header: chunkIsHeader
});
var _this$__cast6 = _slicedToArray(_this$__cast5, 2);
err = _this$__cast6[0];
value = _this$__cast6[1];
if (err) {
this.emit('error', err);
return;
}
record.push([value, field]);
}
}
}
csvrecord = '';
for (i = m = 0, ref1 = record.length; 0 <= ref1 ? m < ref1 : m > ref1; i = 0 <= ref1 ? ++m : --m) {
var _record$i = _slicedToArray(record[i], 2);
value = _record$i[0];
field = _record$i[1];
if (typeof value === 'string') {
options = this.options;
} else if (isObject(value)) {
var _value = value;
value = _value.value;
options = _objectWithoutProperties(_value, _excluded);
if (!(typeof value === 'string' || value === void 0 || value === null)) {
this.emit('error', Error(`Invalid Casting Value: returned value must return a string, null or undefined, got ${JSON.stringify(value)}`));
return;
}
options = _objectSpread(_objectSpread({}, this.options), options);
} else if (value === void 0 || value === null) {
options = this.options;
} else {
this.emit('error', Error(`Invalid Casting Value: returned value must return a string, an object, null or undefined, got ${JSON.stringify(value)}`));
return;
}
var _options = options;
delimiter = _options.delimiter;
escape = _options.escape;
quote = _options.quote;
quoted = _options.quoted;
quoted_empty = _options.quoted_empty;
quoted_string = _options.quoted_string;
quoted_match = _options.quoted_match;
record_delimiter = _options.record_delimiter;
if (value) {
if (typeof value !== 'string') {
this.emit('error', Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`));
return null;
}
containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0;
containsQuote = quote !== '' && value.indexOf(quote) >= 0;
containsEscape = value.indexOf(escape) >= 0 && escape !== quote;
containsRowDelimiter = value.indexOf(record_delimiter) >= 0;
quotedString = quoted_string && typeof field === 'string';
quotedMatch = quoted_match && typeof field === 'string' && quoted_match.filter(function (quoted_match) {
if (typeof quoted_match === 'string') {
return value.indexOf(quoted_match) !== -1;
} else {
return quoted_match.test(value);
}
});
quotedMatch = quotedMatch && quotedMatch.length > 0;
shouldQuote = containsQuote === true || containsdelimiter || containsRowDelimiter || quoted || quotedString || quotedMatch;
if (shouldQuote === true && containsEscape === true) {
regexp = escape === '\\' ? new RegExp(escape + escape, 'g') : new RegExp(escape, 'g');
value = value.replace(regexp, escape + escape);
}
if (containsQuote === true) {
regexp = new RegExp(quote, 'g');
value = value.replace(regexp, escape + quote);
}
if (shouldQuote === true) {
value = quote + value + quote;
}
csvrecord += value;
} else if (quoted_empty === true || quoted_empty == null && field === '' && quoted_string !== false) {
csvrecord += quote + quote;
}
if (i !== record.length - 1) {
csvrecord += delimiter;
}
}
return csvrecord;
} // ## `Stringifier.prototype.headers`
// Print the header line if the option "header" is "true".
headers() {
var headers;
if (!this.options.header) {
return;
}
if (!this.options.columns) {
return;
}
headers = this.options.columns.map(function (column) {
return column.header;
});
if (this.options.eof) {
headers = this.stringify(headers, true) + this.options.record_delimiter;
} else {
headers = this.stringify(headers);
}
return this.push(headers);
}
__cast(value, context) {
var err, type;
type = typeof value;
try {
if (type === 'string') {
// Fine for 99% of the cases
return [void 0, this.options.cast.string(value, context)];
} else if (type === 'number') {
return [void 0, this.options.cast.number(value, context)];
} else if (type === 'boolean') {
return [void 0, this.options.cast.boolean(value, context)];
} else if (value instanceof Date) {
return [void 0, this.options.cast.date(value, context)];
} else if (type === 'object' && value !== null) {
return [void 0, this.options.cast.object(value, context)];
} else {
return [void 0, value, value];
}
} catch (error) {
err = error;
return [err];
}
} // ## `Stringifier.prototype.normalize_columns`
normalize_columns(columns) {
var column, k, v;
if (columns == null) {
return null;
}
if (columns != null) {
if (typeof columns !== 'object') {
throw Error('Invalid option "columns": expect an array or an object');
}
if (!Array.isArray(columns)) {
columns = function () {
var results;
results = [];
for (k in columns) {
v = columns[k];
results.push({
key: k,
header: v
});
}
return results;
}();
} else {
columns = function () {
var j, len, results;
results = [];
for (j = 0, len = columns.length; j < len; j++) {
column = columns[j];
if (typeof column === 'string') {
results.push({
key: column,
header: column
});
} else if (typeof column === 'object' && column != null && !Array.isArray(column)) {
if (!column.key) {
throw Error('Invalid column definition: property "key" is required');
}
if (column.header == null) {
column.header = column.key;
}
results.push(column);
} else {
throw Error('Invalid column definition: expect a string or an object');
}
}
return results;
}();
}
}
return columns;
}
};
module.exports.Stringifier = Stringifier;
isObject = function (obj) {
return typeof obj === 'object' && obj !== null && !Array.isArray(obj);
};
underscore = function (str) {
return str.replace(/([A-Z])/g, function (_, match, index) {
return '_' + match.toLowerCase();
});
}; // ## Lodash implementation of `get`
charCodeOfDot = '.'.charCodeAt(0);
reEscapeChar = /\\(\\)?/g; // Match anything that isn't a dot or bracket.
// Or match property names within brackets.
// Match a non-string expression.
// Or match strings (supports escaping characters).
// Or match "" as the space between consecutive dots or empty brackets.
rePropName = RegExp('[^.[\\]]+' + '|' + '\\[(?:' + '([^"\'][^[]*)' + '|' + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + ')\\]' + '|' + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))', 'g');
reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
reIsPlainProp = /^\w*$/;
getTag = function (value) {
if (value != null) {
if (value === void 0) {
'[object Undefined]';
} else {
'[object Null]';
}
}
return Object.prototype.toString.call(value);
};
isKey = function (value, object) {
var type;
if (Array.isArray(value)) {
return false;
}
type = typeof value;
if (type === 'number' || type === 'symbol' || type === 'boolean' || value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
};
isSymbol = function (value) {
var type;
type = typeof value;
return type === 'symbol' || type === 'object' && value != null && getTag(value) === '[object Symbol]';
};
stringToPath = function (string) {
var result;
result = [];
if (string.charCodeAt(0) === charCodeOfDot) {
result.push('');
}
string.replace(rePropName, function (match, expression, quote, subString) {
var key;
key = match;
if (quote) {
key = subString.replace(reEscapeChar, '$1');
} else if (expression) {
key = expression.trim();
}
return result.push(key);
});
return result;
};
castPath = function (value, object) {
if (Array.isArray(value)) {
return value;
} else {
if (isKey(value, object)) {
return [value];
} else {
return stringToPath(value);
}
}
};
toKey = function (value) {
var ref, result;
if (typeof value === 'string' || isSymbol(value)) {
return value;
}
result = `${value}`;
return (ref = result === '0' && 1 / value === -INFINITY) != null ? ref : {
'-0': result
};
};
get = function (object, path) {
var index, length;
path = Array.isArray(path) ? path : castPath(path, object);
index = 0;
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
if (index && index === length) {
return object;
} else {
return void 0;
}
};
/***/ }),
/***/ "./node_modules/csv-stringify/lib/sync.js":
/*!************************************************!*\
!*** ./node_modules/csv-stringify/lib/sync.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// Generated by CoffeeScript 2.4.1
// # CSV Stringify Sync
// Provides a synchronous alternative to the CSV stringifier.
// ## Usage
// `const csv = stringify(records, [options]`
var StringDecoder, stringify;
var _require = __webpack_require__(/*! string_decoder */ "string_decoder");
StringDecoder = _require.StringDecoder;
stringify = __webpack_require__(/*! ./index */ "./node_modules/csv-stringify/lib/index.js");
module.exports = function (records, options = {}) {
var data, decoder, i, len, record, stringifier;
data = [];
if (records instanceof Buffer) {
decoder = new StringDecoder();
records = decoder.write(records);
}
stringifier = new stringify.Stringifier(options);
stringifier.push = function (record) {
if (record) {
return data.push(record.toString());
}
};
for (i = 0, len = records.length; i < len; i++) {
record = records[i];
stringifier.write(record);
}
stringifier.end();
return data.join('');
};
/***/ }),
/***/ "./node_modules/currency-formatter/currencies.json":
/*!*********************************************************!*\
!*** ./node_modules/currency-formatter/currencies.json ***!
\*********************************************************/
/*! exports provided: AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTC, BTN, BWP, BYR, BZD, CAD, CDF, CHF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRO, MTL, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDD, SDG, SEK, SGD, SHP, SLL, SOS, SRD, STD, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TVD, TWD, TZS, UAH, UGX, USD, UYU, UZS, VEB, VEF, VND, VUV, WST, XAF, XCD, XBT, XOF, XPF, YER, ZAR, ZMW, WON, default */
/***/ (function(module) {
module.exports = JSON.parse("{\"AED\":{\"code\":\"AED\",\"symbol\":\"د.إ.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"AFN\":{\"code\":\"AFN\",\"symbol\":\"؋\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"ALL\":{\"code\":\"ALL\",\"symbol\":\"Lek\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"AMD\":{\"code\":\"AMD\",\"symbol\":\"֏\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"ANG\":{\"code\":\"ANG\",\"symbol\":\"ƒ\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"AOA\":{\"code\":\"AOA\",\"symbol\":\"Kz\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"ARS\":{\"code\":\"ARS\",\"symbol\":\"$\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"AUD\":{\"code\":\"AUD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"AWG\":{\"code\":\"AWG\",\"symbol\":\"ƒ\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"AZN\":{\"code\":\"AZN\",\"symbol\":\"₼\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"BAM\":{\"code\":\"BAM\",\"symbol\":\"КМ\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"BBD\":{\"code\":\"BBD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"BDT\":{\"code\":\"BDT\",\"symbol\":\"৳\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":0},\"BGN\":{\"code\":\"BGN\",\"symbol\":\"лв.\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"BHD\":{\"code\":\"BHD\",\"symbol\":\"د.ب.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":3},\"BIF\":{\"code\":\"BIF\",\"symbol\":\"FBu\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"BMD\":{\"code\":\"BMD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"BND\":{\"code\":\"BND\",\"symbol\":\"$\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"BOB\":{\"code\":\"BOB\",\"symbol\":\"Bs\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"BRL\":{\"code\":\"BRL\",\"symbol\":\"R$\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"BSD\":{\"code\":\"BSD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"BTC\":{\"code\":\"BTC\",\"symbol\":\"Ƀ\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":8},\"BTN\":{\"code\":\"BTN\",\"symbol\":\"Nu.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":1},\"BWP\":{\"code\":\"BWP\",\"symbol\":\"P\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"BYR\":{\"code\":\"BYR\",\"symbol\":\"р.\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"BZD\":{\"code\":\"BZD\",\"symbol\":\"BZ$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"CAD\":{\"code\":\"CAD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"CDF\":{\"code\":\"CDF\",\"symbol\":\"FC\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"CHF\":{\"code\":\"CHF\",\"symbol\":\"CHF\",\"thousandsSeparator\":\"'\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"CLP\":{\"code\":\"CLP\",\"symbol\":\"$\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"CNY\":{\"code\":\"CNY\",\"symbol\":\"¥\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"COP\":{\"code\":\"COP\",\"symbol\":\"$\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"CRC\":{\"code\":\"CRC\",\"symbol\":\"₡\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"CUC\":{\"code\":\"CUC\",\"symbol\":\"CUC\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"CUP\":{\"code\":\"CUP\",\"symbol\":\"$MN\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"CVE\":{\"code\":\"CVE\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"CZK\":{\"code\":\"CZK\",\"symbol\":\"Kč\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"DJF\":{\"code\":\"DJF\",\"symbol\":\"Fdj\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"DKK\":{\"code\":\"DKK\",\"symbol\":\"kr.\",\"thousandsSeparator\":\"\",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"DOP\":{\"code\":\"DOP\",\"symbol\":\"RD$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"DZD\":{\"code\":\"DZD\",\"symbol\":\"د.ج.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"EGP\":{\"code\":\"EGP\",\"symbol\":\"ج.م.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"ERN\":{\"code\":\"ERN\",\"symbol\":\"Nfk\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"ETB\":{\"code\":\"ETB\",\"symbol\":\"ETB\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"EUR\":{\"code\":\"EUR\",\"symbol\":\"€\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"FJD\":{\"code\":\"FJD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"FKP\":{\"code\":\"FKP\",\"symbol\":\"£\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"GBP\":{\"code\":\"GBP\",\"symbol\":\"£\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"GEL\":{\"code\":\"GEL\",\"symbol\":\"Lari\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"GHS\":{\"code\":\"GHS\",\"symbol\":\"₵\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"GIP\":{\"code\":\"GIP\",\"symbol\":\"£\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"GMD\":{\"code\":\"GMD\",\"symbol\":\"D\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"GNF\":{\"code\":\"GNF\",\"symbol\":\"FG\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"GTQ\":{\"code\":\"GTQ\",\"symbol\":\"Q\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"GYD\":{\"code\":\"GYD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"HKD\":{\"code\":\"HKD\",\"symbol\":\"HK$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"HNL\":{\"code\":\"HNL\",\"symbol\":\"L.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"HRK\":{\"code\":\"HRK\",\"symbol\":\"kn\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"HTG\":{\"code\":\"HTG\",\"symbol\":\"G\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"HUF\":{\"code\":\"HUF\",\"symbol\":\"Ft\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"IDR\":{\"code\":\"IDR\",\"symbol\":\"Rp\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"ILS\":{\"code\":\"ILS\",\"symbol\":\"₪\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"INR\":{\"code\":\"INR\",\"symbol\":\"₹\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"IQD\":{\"code\":\"IQD\",\"symbol\":\"د.ع.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"IRR\":{\"code\":\"IRR\",\"symbol\":\"﷼\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\"/\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"ISK\":{\"code\":\"ISK\",\"symbol\":\"kr.\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":0},\"JMD\":{\"code\":\"JMD\",\"symbol\":\"J$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"JOD\":{\"code\":\"JOD\",\"symbol\":\"د.ا.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":3},\"JPY\":{\"code\":\"JPY\",\"symbol\":\"¥\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"KES\":{\"code\":\"KES\",\"symbol\":\"KSh\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"KGS\":{\"code\":\"KGS\",\"symbol\":\"сом\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\"-\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"KHR\":{\"code\":\"KHR\",\"symbol\":\"៛\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"KMF\":{\"code\":\"KMF\",\"symbol\":\"CF\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"KPW\":{\"code\":\"KPW\",\"symbol\":\"₩\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"KRW\":{\"code\":\"KRW\",\"symbol\":\"₩\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"KWD\":{\"code\":\"KWD\",\"symbol\":\"د.ك.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":3},\"KYD\":{\"code\":\"KYD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"KZT\":{\"code\":\"KZT\",\"symbol\":\"₸\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\"-\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"LAK\":{\"code\":\"LAK\",\"symbol\":\"₭\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"LBP\":{\"code\":\"LBP\",\"symbol\":\"ل.ل.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"LKR\":{\"code\":\"LKR\",\"symbol\":\"₨\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":0},\"LRD\":{\"code\":\"LRD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"LSL\":{\"code\":\"LSL\",\"symbol\":\"M\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"LYD\":{\"code\":\"LYD\",\"symbol\":\"د.ل.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":3},\"MAD\":{\"code\":\"MAD\",\"symbol\":\"د.م.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"MDL\":{\"code\":\"MDL\",\"symbol\":\"lei\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"MGA\":{\"code\":\"MGA\",\"symbol\":\"Ar\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"MKD\":{\"code\":\"MKD\",\"symbol\":\"ден.\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"MMK\":{\"code\":\"MMK\",\"symbol\":\"K\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"MNT\":{\"code\":\"MNT\",\"symbol\":\"₮\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"MOP\":{\"code\":\"MOP\",\"symbol\":\"MOP$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"MRO\":{\"code\":\"MRO\",\"symbol\":\"UM\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"MTL\":{\"code\":\"MTL\",\"symbol\":\"₤\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"MUR\":{\"code\":\"MUR\",\"symbol\":\"₨\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"MVR\":{\"code\":\"MVR\",\"symbol\":\"MVR\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":1},\"MWK\":{\"code\":\"MWK\",\"symbol\":\"MK\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"MXN\":{\"code\":\"MXN\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"MYR\":{\"code\":\"MYR\",\"symbol\":\"RM\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"MZN\":{\"code\":\"MZN\",\"symbol\":\"MT\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"NAD\":{\"code\":\"NAD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"NGN\":{\"code\":\"NGN\",\"symbol\":\"₦\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"NIO\":{\"code\":\"NIO\",\"symbol\":\"C$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"NOK\":{\"code\":\"NOK\",\"symbol\":\"kr\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"NPR\":{\"code\":\"NPR\",\"symbol\":\"₨\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"NZD\":{\"code\":\"NZD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"OMR\":{\"code\":\"OMR\",\"symbol\":\"﷼\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":3},\"PAB\":{\"code\":\"PAB\",\"symbol\":\"B/.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"PEN\":{\"code\":\"PEN\",\"symbol\":\"S/.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"PGK\":{\"code\":\"PGK\",\"symbol\":\"K\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"PHP\":{\"code\":\"PHP\",\"symbol\":\"₱\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"PKR\":{\"code\":\"PKR\",\"symbol\":\"₨\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"PLN\":{\"code\":\"PLN\",\"symbol\":\"zł\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"PYG\":{\"code\":\"PYG\",\"symbol\":\"₲\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"QAR\":{\"code\":\"QAR\",\"symbol\":\"﷼\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"RON\":{\"code\":\"RON\",\"symbol\":\"lei\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"RSD\":{\"code\":\"RSD\",\"symbol\":\"Дин.\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"RUB\":{\"code\":\"RUB\",\"symbol\":\"₽\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"RWF\":{\"code\":\"RWF\",\"symbol\":\"RWF\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"SAR\":{\"code\":\"SAR\",\"symbol\":\"﷼\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"SBD\":{\"code\":\"SBD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"SCR\":{\"code\":\"SCR\",\"symbol\":\"₨\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"SDD\":{\"code\":\"SDD\",\"symbol\":\"LSd\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"SDG\":{\"code\":\"SDG\",\"symbol\":\"£‏\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"SEK\":{\"code\":\"SEK\",\"symbol\":\"kr\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"SGD\":{\"code\":\"SGD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"SHP\":{\"code\":\"SHP\",\"symbol\":\"£\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"SLL\":{\"code\":\"SLL\",\"symbol\":\"Le\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"SOS\":{\"code\":\"SOS\",\"symbol\":\"S\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"SRD\":{\"code\":\"SRD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"STD\":{\"code\":\"STD\",\"symbol\":\"Db\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"SVC\":{\"code\":\"SVC\",\"symbol\":\"₡\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"SYP\":{\"code\":\"SYP\",\"symbol\":\"£\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"SZL\":{\"code\":\"SZL\",\"symbol\":\"E\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"THB\":{\"code\":\"THB\",\"symbol\":\"฿\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"TJS\":{\"code\":\"TJS\",\"symbol\":\"TJS\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\";\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"TMT\":{\"code\":\"TMT\",\"symbol\":\"m\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"TND\":{\"code\":\"TND\",\"symbol\":\"د.ت.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":3},\"TOP\":{\"code\":\"TOP\",\"symbol\":\"T$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"TRY\":{\"code\":\"TRY\",\"symbol\":\"₺\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"TTD\":{\"code\":\"TTD\",\"symbol\":\"TT$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"TVD\":{\"code\":\"TVD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"TWD\":{\"code\":\"TWD\",\"symbol\":\"NT$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"TZS\":{\"code\":\"TZS\",\"symbol\":\"TSh\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"UAH\":{\"code\":\"UAH\",\"symbol\":\"₴\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"UGX\":{\"code\":\"UGX\",\"symbol\":\"USh\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"USD\":{\"code\":\"USD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"UYU\":{\"code\":\"UYU\",\"symbol\":\"$U\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"UZS\":{\"code\":\"UZS\",\"symbol\":\"сўм\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"VEB\":{\"code\":\"VEB\",\"symbol\":\"Bs.\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"VEF\":{\"code\":\"VEF\",\"symbol\":\"Bs. F.\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"VND\":{\"code\":\"VND\",\"symbol\":\"₫\",\"thousandsSeparator\":\".\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":0},\"VUV\":{\"code\":\"VUV\",\"symbol\":\"VT\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":0},\"WST\":{\"code\":\"WST\",\"symbol\":\"WS$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"XAF\":{\"code\":\"XAF\",\"symbol\":\"F\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"XCD\":{\"code\":\"XCD\",\"symbol\":\"$\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"XBT\":{\"code\":\"XBT\",\"symbol\":\"Ƀ\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"XOF\":{\"code\":\"XOF\",\"symbol\":\"F\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"XPF\":{\"code\":\"XPF\",\"symbol\":\"F\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"YER\":{\"code\":\"YER\",\"symbol\":\"﷼\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"ZAR\":{\"code\":\"ZAR\",\"symbol\":\"R\",\"thousandsSeparator\":\" \",\"decimalSeparator\":\",\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"ZMW\":{\"code\":\"ZMW\",\"symbol\":\"ZK\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"WON\":{\"code\":\"WON\",\"symbol\":\"₩\",\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2}}");
/***/ }),
/***/ "./node_modules/currency-formatter/index.js":
/*!**************************************************!*\
!*** ./node_modules/currency-formatter/index.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var accounting = __webpack_require__(/*! accounting */ "./node_modules/accounting/accounting.js");
var assign = __webpack_require__(/*! object-assign */ "./node_modules/object-assign/index.js");
var localeCurrency = __webpack_require__(/*! locale-currency */ "./node_modules/locale-currency/index.js");
var currencies = __webpack_require__(/*! ./currencies.json */ "./node_modules/currency-formatter/currencies.json");
var localeFormats = __webpack_require__(/*! ./localeFormats.json */ "./node_modules/currency-formatter/localeFormats.json");
var defaultCurrency = {
symbol: '',
thousandsSeparator: ',',
decimalSeparator: '.',
symbolOnLeft: true,
spaceBetweenAmountAndSymbol: false,
decimalDigits: 2
};
var defaultLocaleFormat = {};
var formatMapping = [{
symbolOnLeft: true,
spaceBetweenAmountAndSymbol: false,
format: {
pos: '%s%v',
neg: '-%s%v',
zero: '%s%v'
}
}, {
symbolOnLeft: true,
spaceBetweenAmountAndSymbol: true,
format: {
pos: '%s %v',
neg: '-%s %v',
zero: '%s %v'
}
}, {
symbolOnLeft: false,
spaceBetweenAmountAndSymbol: false,
format: {
pos: '%v%s',
neg: '-%v%s',
zero: '%v%s'
}
}, {
symbolOnLeft: false,
spaceBetweenAmountAndSymbol: true,
format: {
pos: '%v %s',
neg: '-%v %s',
zero: '%v %s'
}
}];
function format(value, options) {
var code = options.code || options.locale && localeCurrency.getCurrency(options.locale);
var localeMatch = /^([a-z]+)([_-]([a-z]+))?$/i.exec(options.locale) || [];
var language = localeMatch[1];
var region = localeMatch[3];
var localeFormat = assign({}, defaultLocaleFormat, localeFormats[language] || {}, localeFormats[language + '-' + region] || {});
var currency = assign({}, defaultCurrency, findCurrency(code), localeFormat);
var symbolOnLeft = currency.symbolOnLeft;
var spaceBetweenAmountAndSymbol = currency.spaceBetweenAmountAndSymbol;
var format = formatMapping.filter(function (f) {
return f.symbolOnLeft == symbolOnLeft && f.spaceBetweenAmountAndSymbol == spaceBetweenAmountAndSymbol;
})[0].format;
return accounting.formatMoney(value, {
symbol: isUndefined(options.symbol) ? currency.symbol : options.symbol,
decimal: isUndefined(options.decimal) ? currency.decimalSeparator : options.decimal,
thousand: isUndefined(options.thousand) ? currency.thousandsSeparator : options.thousand,
precision: typeof options.precision === 'number' ? options.precision : currency.decimalDigits,
format: ['string', 'object'].indexOf(typeof options.format) > -1 ? options.format : format
});
}
function findCurrency(currencyCode) {
return currencies[currencyCode];
}
function isUndefined(val) {
return typeof val === 'undefined';
}
function unformat(value, options) {
var code = options.code || options.locale && localeCurrency.getCurrency(options.locale);
var localeFormat = localeFormats[options.locale] || defaultLocaleFormat;
var currency = assign({}, defaultCurrency, findCurrency(code), localeFormat);
var decimal = isUndefined(options.decimal) ? currency.decimalSeparator : options.decimal;
return accounting.unformat(value, decimal);
}
module.exports = {
defaultCurrency: defaultCurrency,
get currencies() {
// In favor of backwards compatibility, the currencies map is converted to an array here
return Object.keys(currencies).map(function (key) {
return currencies[key];
});
},
findCurrency: findCurrency,
format: format,
unformat: unformat
};
/***/ }),
/***/ "./node_modules/currency-formatter/localeFormats.json":
/*!************************************************************!*\
!*** ./node_modules/currency-formatter/localeFormats.json ***!
\************************************************************/
/*! exports provided: de, el, en-US, en-IE, zh-CN, es, it, nl, default */
/***/ (function(module) {
module.exports = JSON.parse("{\"de\":{\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"el\":{\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"decimalDigits\":2},\"en-US\":{\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"en-IE\":{\"symbolOnLeft\":true,\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"zh-CN\":{\"thousandsSeparator\":\",\",\"decimalSeparator\":\".\",\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"decimalDigits\":2},\"es\":{\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"symbolOnLeft\":false,\"spaceBetweenAmountAndSymbol\":true,\"decimalDigits\":2},\"it\":{\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"decimalDigits\":2},\"nl\":{\"symbolOnLeft\":true,\"spaceBetweenAmountAndSymbol\":false,\"thousandsSeparator\":\".\",\"decimalSeparator\":\",\",\"decimalDigits\":2}}");
/***/ }),
/***/ "./node_modules/damerau-levenshtein/index.js":
/*!***************************************************!*\
!*** ./node_modules/damerau-levenshtein/index.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
// TheSpanishInquisition
// Cache the matrix. Note that if you not pass a limit this implementation will use a dynamically calculate one.
module.exports = function (__this, that, limit) {
var thisLength = __this.length,
thatLength = that.length,
matrix = []; // If the limit is not defined it will be calculate from this and that args.
limit = (limit || (thatLength > thisLength ? thatLength : thisLength)) + 1;
for (var i = 0; i < limit; i++) {
matrix[i] = [i];
matrix[i].length = limit;
}
for (i = 0; i < limit; i++) {
matrix[0][i] = i;
}
if (Math.abs(thisLength - thatLength) > (limit || 100)) {
return prepare(limit || 100);
}
if (thisLength === 0) {
return prepare(thatLength);
}
if (thatLength === 0) {
return prepare(thisLength);
} // Calculate matrix.
var j, this_i, that_j, cost, min, t;
for (i = 1; i <= thisLength; ++i) {
this_i = __this[i - 1]; // Step 4
for (j = 1; j <= thatLength; ++j) {
// Check the jagged ld total so far
if (i === j && matrix[i][j] > 4) return prepare(thisLength);
that_j = that[j - 1];
cost = this_i === that_j ? 0 : 1; // Step 5
// Calculate the minimum (much faster than Math.min(...)).
min = matrix[i - 1][j] + 1; // Deletion.
if ((t = matrix[i][j - 1] + 1) < min) min = t; // Insertion.
if ((t = matrix[i - 1][j - 1] + cost) < min) min = t; // Substitution.
// Update matrix.
matrix[i][j] = i > 1 && j > 1 && this_i === that[j - 2] && __this[i - 2] === that_j && (t = matrix[i - 2][j - 2] + cost) < min ? t : min; // Transposition.
}
}
return prepare(matrix[thisLength][thatLength]);
/**
*
*/
function prepare(steps) {
var length = Math.max(thisLength, thatLength);
var relative = length === 0 ? 0 : steps / length;
var similarity = 1 - relative;
return {
steps: steps,
relative: relative,
similarity: similarity
};
}
};
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/addLeadingZeros/index.js":
/*!*****************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/addLeadingZeros/index.js ***!
\*****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return addLeadingZeros; });
function addLeadingZeros(number, targetLength) {
var sign = number < 0 ? '-' : '';
var output = Math.abs(number).toString();
while (output.length < targetLength) {
output = '0' + output;
}
return sign + output;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/assign/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/assign/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return assign; });
function assign(target, dirtyObject) {
if (target == null) {
throw new TypeError('assign requires that input parameter not be null or undefined');
}
dirtyObject = dirtyObject || {};
for (var property in dirtyObject) {
if (dirtyObject.hasOwnProperty(property)) {
target[property] = dirtyObject[property];
}
}
return target;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/cloneObject/index.js":
/*!*************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/cloneObject/index.js ***!
\*************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return cloneObject; });
/* harmony import */ var _assign_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../assign/index.js */ "./node_modules/date-fns/esm/_lib/assign/index.js");
function cloneObject(dirtyObject) {
return Object(_assign_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])({}, dirtyObject);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/format/formatters/index.js":
/*!*******************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/format/formatters/index.js ***!
\*******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lightFormatters_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../lightFormatters/index.js */ "./node_modules/date-fns/esm/_lib/format/lightFormatters/index.js");
/* harmony import */ var _lib_getUTCDayOfYear_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../_lib/getUTCDayOfYear/index.js */ "./node_modules/date-fns/esm/_lib/getUTCDayOfYear/index.js");
/* harmony import */ var _lib_getUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../_lib/getUTCISOWeek/index.js */ "./node_modules/date-fns/esm/_lib/getUTCISOWeek/index.js");
/* harmony import */ var _lib_getUTCISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../_lib/getUTCISOWeekYear/index.js */ "./node_modules/date-fns/esm/_lib/getUTCISOWeekYear/index.js");
/* harmony import */ var _lib_getUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../_lib/getUTCWeek/index.js */ "./node_modules/date-fns/esm/_lib/getUTCWeek/index.js");
/* harmony import */ var _lib_getUTCWeekYear_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../_lib/getUTCWeekYear/index.js */ "./node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js");
/* harmony import */ var _addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../addLeadingZeros/index.js */ "./node_modules/date-fns/esm/_lib/addLeadingZeros/index.js");
var dayPeriodEnum = {
am: 'am',
pm: 'pm',
midnight: 'midnight',
noon: 'noon',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
};
/*
* | | Unit | | Unit |
* |-----|--------------------------------|-----|--------------------------------|
* | a | AM, PM | A* | Milliseconds in day |
* | b | AM, PM, noon, midnight | B | Flexible day period |
* | c | Stand-alone local day of week | C* | Localized hour w/ day period |
* | d | Day of month | D | Day of year |
* | e | Local day of week | E | Day of week |
* | f | | F* | Day of week in month |
* | g* | Modified Julian day | G | Era |
* | h | Hour [1-12] | H | Hour [0-23] |
* | i! | ISO day of week | I! | ISO week of year |
* | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
* | k | Hour [1-24] | K | Hour [0-11] |
* | l* | (deprecated) | L | Stand-alone month |
* | m | Minute | M | Month |
* | n | | N | |
* | o! | Ordinal number modifier | O | Timezone (GMT) |
* | p! | Long localized time | P! | Long localized date |
* | q | Stand-alone quarter | Q | Quarter |
* | r* | Related Gregorian year | R! | ISO week-numbering year |
* | s | Second | S | Fraction of second |
* | t! | Seconds timestamp | T! | Milliseconds timestamp |
* | u | Extended year | U* | Cyclic year |
* | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
* | w | Local week of year | W* | Week of month |
* | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
* | y | Year (abs) | Y | Local week-numbering year |
* | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
*
* Letters marked by * are not implemented but reserved by Unicode standard.
*
* Letters marked by ! are non-standard, but implemented by date-fns:
* - `o` modifies the previous token to turn it into an ordinal (see `format` docs)
* - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
* i.e. 7 for Sunday, 1 for Monday, etc.
* - `I` is ISO week of year, as opposed to `w` which is local week of year.
* - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
* `R` is supposed to be used in conjunction with `I` and `i`
* for universal ISO week-numbering date, whereas
* `Y` is supposed to be used in conjunction with `w` and `e`
* for week-numbering date specific to the locale.
* - `P` is long localized date format
* - `p` is long localized time format
*/
var formatters = {
// Era
G: function (date, token, localize) {
var era = date.getUTCFullYear() > 0 ? 1 : 0;
switch (token) {
// AD, BC
case 'G':
case 'GG':
case 'GGG':
return localize.era(era, {
width: 'abbreviated'
});
// A, B
case 'GGGGG':
return localize.era(era, {
width: 'narrow'
});
// Anno Domini, Before Christ
case 'GGGG':
default:
return localize.era(era, {
width: 'wide'
});
}
},
// Year
y: function (date, token, localize) {
// Ordinal number
if (token === 'yo') {
var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript)
var year = signedYear > 0 ? signedYear : 1 - signedYear;
return localize.ordinalNumber(year, {
unit: 'year'
});
}
return _lightFormatters_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].y(date, token);
},
// Local week-numbering year
Y: function (date, token, localize, options) {
var signedWeekYear = Object(_lib_getUTCWeekYear_index_js__WEBPACK_IMPORTED_MODULE_5__["default"])(date, options); // Returns 1 for 1 BC (which is year 0 in JavaScript)
var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; // Two digit year
if (token === 'YY') {
var twoDigitYear = weekYear % 100;
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(twoDigitYear, 2);
} // Ordinal number
if (token === 'Yo') {
return localize.ordinalNumber(weekYear, {
unit: 'year'
});
} // Padding
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(weekYear, token.length);
},
// ISO week-numbering year
R: function (date, token) {
var isoWeekYear = Object(_lib_getUTCISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(date); // Padding
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(isoWeekYear, token.length);
},
// Extended year. This is a single number designating the year of this calendar system.
// The main difference between `y` and `u` localizers are B.C. years:
// | Year | `y` | `u` |
// |------|-----|-----|
// | AC 1 | 1 | 1 |
// | BC 1 | 1 | 0 |
// | BC 2 | 2 | -1 |
// Also `yy` always returns the last two digits of a year,
// while `uu` pads single digit years to 2 characters and returns other years unchanged.
u: function (date, token) {
var year = date.getUTCFullYear();
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(year, token.length);
},
// Quarter
Q: function (date, token, localize) {
var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
switch (token) {
// 1, 2, 3, 4
case 'Q':
return String(quarter);
// 01, 02, 03, 04
case 'QQ':
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(quarter, 2);
// 1st, 2nd, 3rd, 4th
case 'Qo':
return localize.ordinalNumber(quarter, {
unit: 'quarter'
});
// Q1, Q2, Q3, Q4
case 'QQQ':
return localize.quarter(quarter, {
width: 'abbreviated',
context: 'formatting'
});
// 1, 2, 3, 4 (narrow quarter; could be not numerical)
case 'QQQQQ':
return localize.quarter(quarter, {
width: 'narrow',
context: 'formatting'
});
// 1st quarter, 2nd quarter, ...
case 'QQQQ':
default:
return localize.quarter(quarter, {
width: 'wide',
context: 'formatting'
});
}
},
// Stand-alone quarter
q: function (date, token, localize) {
var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
switch (token) {
// 1, 2, 3, 4
case 'q':
return String(quarter);
// 01, 02, 03, 04
case 'qq':
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(quarter, 2);
// 1st, 2nd, 3rd, 4th
case 'qo':
return localize.ordinalNumber(quarter, {
unit: 'quarter'
});
// Q1, Q2, Q3, Q4
case 'qqq':
return localize.quarter(quarter, {
width: 'abbreviated',
context: 'standalone'
});
// 1, 2, 3, 4 (narrow quarter; could be not numerical)
case 'qqqqq':
return localize.quarter(quarter, {
width: 'narrow',
context: 'standalone'
});
// 1st quarter, 2nd quarter, ...
case 'qqqq':
default:
return localize.quarter(quarter, {
width: 'wide',
context: 'standalone'
});
}
},
// Month
M: function (date, token, localize) {
var month = date.getUTCMonth();
switch (token) {
case 'M':
case 'MM':
return _lightFormatters_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].M(date, token);
// 1st, 2nd, ..., 12th
case 'Mo':
return localize.ordinalNumber(month + 1, {
unit: 'month'
});
// Jan, Feb, ..., Dec
case 'MMM':
return localize.month(month, {
width: 'abbreviated',
context: 'formatting'
});
// J, F, ..., D
case 'MMMMM':
return localize.month(month, {
width: 'narrow',
context: 'formatting'
});
// January, February, ..., December
case 'MMMM':
default:
return localize.month(month, {
width: 'wide',
context: 'formatting'
});
}
},
// Stand-alone month
L: function (date, token, localize) {
var month = date.getUTCMonth();
switch (token) {
// 1, 2, ..., 12
case 'L':
return String(month + 1);
// 01, 02, ..., 12
case 'LL':
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(month + 1, 2);
// 1st, 2nd, ..., 12th
case 'Lo':
return localize.ordinalNumber(month + 1, {
unit: 'month'
});
// Jan, Feb, ..., Dec
case 'LLL':
return localize.month(month, {
width: 'abbreviated',
context: 'standalone'
});
// J, F, ..., D
case 'LLLLL':
return localize.month(month, {
width: 'narrow',
context: 'standalone'
});
// January, February, ..., December
case 'LLLL':
default:
return localize.month(month, {
width: 'wide',
context: 'standalone'
});
}
},
// Local week of year
w: function (date, token, localize, options) {
var week = Object(_lib_getUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_4__["default"])(date, options);
if (token === 'wo') {
return localize.ordinalNumber(week, {
unit: 'week'
});
}
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(week, token.length);
},
// ISO week of year
I: function (date, token, localize) {
var isoWeek = Object(_lib_getUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date);
if (token === 'Io') {
return localize.ordinalNumber(isoWeek, {
unit: 'week'
});
}
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(isoWeek, token.length);
},
// Day of the month
d: function (date, token, localize) {
if (token === 'do') {
return localize.ordinalNumber(date.getUTCDate(), {
unit: 'date'
});
}
return _lightFormatters_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].d(date, token);
},
// Day of year
D: function (date, token, localize) {
var dayOfYear = Object(_lib_getUTCDayOfYear_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date);
if (token === 'Do') {
return localize.ordinalNumber(dayOfYear, {
unit: 'dayOfYear'
});
}
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(dayOfYear, token.length);
},
// Day of week
E: function (date, token, localize) {
var dayOfWeek = date.getUTCDay();
switch (token) {
// Tue
case 'E':
case 'EE':
case 'EEE':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'formatting'
});
// T
case 'EEEEE':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'EEEEEE':
return localize.day(dayOfWeek, {
width: 'short',
context: 'formatting'
});
// Tuesday
case 'EEEE':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'formatting'
});
}
},
// Local day of week
e: function (date, token, localize, options) {
var dayOfWeek = date.getUTCDay();
var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
// Numerical value (Nth day of week with current locale or weekStartsOn)
case 'e':
return String(localDayOfWeek);
// Padded numerical value
case 'ee':
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(localDayOfWeek, 2);
// 1st, 2nd, ..., 7th
case 'eo':
return localize.ordinalNumber(localDayOfWeek, {
unit: 'day'
});
case 'eee':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'formatting'
});
// T
case 'eeeee':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'eeeeee':
return localize.day(dayOfWeek, {
width: 'short',
context: 'formatting'
});
// Tuesday
case 'eeee':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'formatting'
});
}
},
// Stand-alone local day of week
c: function (date, token, localize, options) {
var dayOfWeek = date.getUTCDay();
var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
// Numerical value (same as in `e`)
case 'c':
return String(localDayOfWeek);
// Padded numerical value
case 'cc':
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(localDayOfWeek, token.length);
// 1st, 2nd, ..., 7th
case 'co':
return localize.ordinalNumber(localDayOfWeek, {
unit: 'day'
});
case 'ccc':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'standalone'
});
// T
case 'ccccc':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'standalone'
});
// Tu
case 'cccccc':
return localize.day(dayOfWeek, {
width: 'short',
context: 'standalone'
});
// Tuesday
case 'cccc':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'standalone'
});
}
},
// ISO day of week
i: function (date, token, localize) {
var dayOfWeek = date.getUTCDay();
var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
switch (token) {
// 2
case 'i':
return String(isoDayOfWeek);
// 02
case 'ii':
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(isoDayOfWeek, token.length);
// 2nd
case 'io':
return localize.ordinalNumber(isoDayOfWeek, {
unit: 'day'
});
// Tue
case 'iii':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'formatting'
});
// T
case 'iiiii':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'iiiiii':
return localize.day(dayOfWeek, {
width: 'short',
context: 'formatting'
});
// Tuesday
case 'iiii':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'formatting'
});
}
},
// AM or PM
a: function (date, token, localize) {
var hours = date.getUTCHours();
var dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
switch (token) {
case 'a':
case 'aa':
case 'aaa':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
});
case 'aaaaa':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'narrow',
context: 'formatting'
});
case 'aaaa':
default:
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'wide',
context: 'formatting'
});
}
},
// AM, PM, midnight, noon
b: function (date, token, localize) {
var hours = date.getUTCHours();
var dayPeriodEnumValue;
if (hours === 12) {
dayPeriodEnumValue = dayPeriodEnum.noon;
} else if (hours === 0) {
dayPeriodEnumValue = dayPeriodEnum.midnight;
} else {
dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
}
switch (token) {
case 'b':
case 'bb':
case 'bbb':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
});
case 'bbbbb':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'narrow',
context: 'formatting'
});
case 'bbbb':
default:
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'wide',
context: 'formatting'
});
}
},
// in the morning, in the afternoon, in the evening, at night
B: function (date, token, localize) {
var hours = date.getUTCHours();
var dayPeriodEnumValue;
if (hours >= 17) {
dayPeriodEnumValue = dayPeriodEnum.evening;
} else if (hours >= 12) {
dayPeriodEnumValue = dayPeriodEnum.afternoon;
} else if (hours >= 4) {
dayPeriodEnumValue = dayPeriodEnum.morning;
} else {
dayPeriodEnumValue = dayPeriodEnum.night;
}
switch (token) {
case 'B':
case 'BB':
case 'BBB':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
});
case 'BBBBB':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'narrow',
context: 'formatting'
});
case 'BBBB':
default:
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'wide',
context: 'formatting'
});
}
},
// Hour [1-12]
h: function (date, token, localize) {
if (token === 'ho') {
var hours = date.getUTCHours() % 12;
if (hours === 0) hours = 12;
return localize.ordinalNumber(hours, {
unit: 'hour'
});
}
return _lightFormatters_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].h(date, token);
},
// Hour [0-23]
H: function (date, token, localize) {
if (token === 'Ho') {
return localize.ordinalNumber(date.getUTCHours(), {
unit: 'hour'
});
}
return _lightFormatters_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].H(date, token);
},
// Hour [0-11]
K: function (date, token, localize) {
var hours = date.getUTCHours() % 12;
if (token === 'Ko') {
return localize.ordinalNumber(hours, {
unit: 'hour'
});
}
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(hours, token.length);
},
// Hour [1-24]
k: function (date, token, localize) {
var hours = date.getUTCHours();
if (hours === 0) hours = 24;
if (token === 'ko') {
return localize.ordinalNumber(hours, {
unit: 'hour'
});
}
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(hours, token.length);
},
// Minute
m: function (date, token, localize) {
if (token === 'mo') {
return localize.ordinalNumber(date.getUTCMinutes(), {
unit: 'minute'
});
}
return _lightFormatters_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].m(date, token);
},
// Second
s: function (date, token, localize) {
if (token === 'so') {
return localize.ordinalNumber(date.getUTCSeconds(), {
unit: 'second'
});
}
return _lightFormatters_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].s(date, token);
},
// Fraction of second
S: function (date, token) {
var numberOfDigits = token.length;
var milliseconds = date.getUTCMilliseconds();
var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(fractionalSeconds, numberOfDigits);
},
// Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
X: function (date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
if (timezoneOffset === 0) {
return 'Z';
}
switch (token) {
// Hours and optional minutes
case 'X':
return formatTimezoneWithOptionalMinutes(timezoneOffset);
// Hours, minutes and optional seconds without `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `XX`
case 'XXXX':
case 'XX':
// Hours and minutes without `:` delimiter
return formatTimezone(timezoneOffset);
// Hours, minutes and optional seconds with `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `XXX`
case 'XXXXX':
case 'XXX': // Hours and minutes with `:` delimiter
default:
return formatTimezone(timezoneOffset, ':');
}
},
// Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
x: function (date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
// Hours and optional minutes
case 'x':
return formatTimezoneWithOptionalMinutes(timezoneOffset);
// Hours, minutes and optional seconds without `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `xx`
case 'xxxx':
case 'xx':
// Hours and minutes without `:` delimiter
return formatTimezone(timezoneOffset);
// Hours, minutes and optional seconds with `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `xxx`
case 'xxxxx':
case 'xxx': // Hours and minutes with `:` delimiter
default:
return formatTimezone(timezoneOffset, ':');
}
},
// Timezone (GMT)
O: function (date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
// Short
case 'O':
case 'OO':
case 'OOO':
return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
// Long
case 'OOOO':
default:
return 'GMT' + formatTimezone(timezoneOffset, ':');
}
},
// Timezone (specific non-location)
z: function (date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
// Short
case 'z':
case 'zz':
case 'zzz':
return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
// Long
case 'zzzz':
default:
return 'GMT' + formatTimezone(timezoneOffset, ':');
}
},
// Seconds timestamp
t: function (date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timestamp = Math.floor(originalDate.getTime() / 1000);
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(timestamp, token.length);
},
// Milliseconds timestamp
T: function (date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timestamp = originalDate.getTime();
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(timestamp, token.length);
}
};
function formatTimezoneShort(offset, dirtyDelimiter) {
var sign = offset > 0 ? '-' : '+';
var absOffset = Math.abs(offset);
var hours = Math.floor(absOffset / 60);
var minutes = absOffset % 60;
if (minutes === 0) {
return sign + String(hours);
}
var delimiter = dirtyDelimiter || '';
return sign + String(hours) + delimiter + Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(minutes, 2);
}
function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) {
if (offset % 60 === 0) {
var sign = offset > 0 ? '-' : '+';
return sign + Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(Math.abs(offset) / 60, 2);
}
return formatTimezone(offset, dirtyDelimiter);
}
function formatTimezone(offset, dirtyDelimiter) {
var delimiter = dirtyDelimiter || '';
var sign = offset > 0 ? '-' : '+';
var absOffset = Math.abs(offset);
var hours = Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(Math.floor(absOffset / 60), 2);
var minutes = Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(absOffset % 60, 2);
return sign + hours + delimiter + minutes;
}
/* harmony default export */ __webpack_exports__["default"] = (formatters);
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/format/lightFormatters/index.js":
/*!************************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/format/lightFormatters/index.js ***!
\************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../addLeadingZeros/index.js */ "./node_modules/date-fns/esm/_lib/addLeadingZeros/index.js");
/*
* | | Unit | | Unit |
* |-----|--------------------------------|-----|--------------------------------|
* | a | AM, PM | A* | Milliseconds in day |
* | c | Stand-alone local day of week | C* | Localized hour w/ day period |
* | d | Day of month | D | Day of year |
* | e | Local day of week | E | Day of week |
* | f | | F* | Day of week in month |
* | g* | Modified Julian day | G | Era |
* | h | Hour [1-12] | H | Hour [0-23] |
* | i! | ISO day of week | I! | ISO week of year |
* | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
* | k | Hour [1-24] | K | Hour [0-11] |
* | l* | (deprecated) | L | Stand-alone month |
* | m | Minute | M | Month |
* | n | | N | |
* | o! | Ordinal number modifier | O | Timezone (GMT) |
* | p! | Long localized time | P! | Long localized date |
* | q | Stand-alone quarter | Q | Quarter |
* | r* | Related Gregorian year | R! | ISO week-numbering year |
* | s | Second | S | Fraction of second |
* | t! | Seconds timestamp | T! | Milliseconds timestamp |
* | u | Extended year | U* | Cyclic year |
* | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
* | w | Local week of year | W* | Week of month |
* | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
* | y | Year (abs) | Y | Local week-numbering year |
* | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
*
* Letters marked by * are not implemented but reserved by Unicode standard.
*
* Letters marked by ! are non-standard, but implemented by date-fns:
* - `o` modifies the previous token to turn it into an ordinal (see `format` docs)
* - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
* i.e. 7 for Sunday, 1 for Monday, etc.
* - `I` is ISO week of year, as opposed to `w` which is local week of year.
* - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
* `R` is supposed to be used in conjunction with `I` and `i`
* for universal ISO week-numbering date, whereas
* `Y` is supposed to be used in conjunction with `w` and `e`
* for week-numbering date specific to the locale.
* - `P` is long localized date format
* - `p` is long localized time format
*/
var formatters = {
// Year
y: function (date, token) {
// From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens
// | Year | y | yy | yyy | yyyy | yyyyy |
// |----------|-------|----|-------|-------|-------|
// | AD 1 | 1 | 01 | 001 | 0001 | 00001 |
// | AD 12 | 12 | 12 | 012 | 0012 | 00012 |
// | AD 123 | 123 | 23 | 123 | 0123 | 00123 |
// | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |
// | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript)
var year = signedYear > 0 ? signedYear : 1 - signedYear;
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(token === 'yy' ? year % 100 : year, token.length);
},
// Month
M: function (date, token) {
var month = date.getUTCMonth();
return token === 'M' ? String(month + 1) : Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(month + 1, 2);
},
// Day of the month
d: function (date, token) {
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(date.getUTCDate(), token.length);
},
// AM or PM
a: function (date, token) {
var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? 'pm' : 'am';
switch (token) {
case 'a':
case 'aa':
case 'aaa':
return dayPeriodEnumValue.toUpperCase();
case 'aaaaa':
return dayPeriodEnumValue[0];
case 'aaaa':
default:
return dayPeriodEnumValue === 'am' ? 'a.m.' : 'p.m.';
}
},
// Hour [1-12]
h: function (date, token) {
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(date.getUTCHours() % 12 || 12, token.length);
},
// Hour [0-23]
H: function (date, token) {
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(date.getUTCHours(), token.length);
},
// Minute
m: function (date, token) {
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(date.getUTCMinutes(), token.length);
},
// Second
s: function (date, token) {
return Object(_addLeadingZeros_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(date.getUTCSeconds(), token.length);
}
};
/* harmony default export */ __webpack_exports__["default"] = (formatters);
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/format/longFormatters/index.js":
/*!***********************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/format/longFormatters/index.js ***!
\***********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
function dateLongFormatter(pattern, formatLong) {
switch (pattern) {
case 'P':
return formatLong.date({
width: 'short'
});
case 'PP':
return formatLong.date({
width: 'medium'
});
case 'PPP':
return formatLong.date({
width: 'long'
});
case 'PPPP':
default:
return formatLong.date({
width: 'full'
});
}
}
function timeLongFormatter(pattern, formatLong) {
switch (pattern) {
case 'p':
return formatLong.time({
width: 'short'
});
case 'pp':
return formatLong.time({
width: 'medium'
});
case 'ppp':
return formatLong.time({
width: 'long'
});
case 'pppp':
default:
return formatLong.time({
width: 'full'
});
}
}
function dateTimeLongFormatter(pattern, formatLong) {
var matchResult = pattern.match(/(P+)(p+)?/);
var datePattern = matchResult[1];
var timePattern = matchResult[2];
if (!timePattern) {
return dateLongFormatter(pattern, formatLong);
}
var dateTimeFormat;
switch (datePattern) {
case 'P':
dateTimeFormat = formatLong.dateTime({
width: 'short'
});
break;
case 'PP':
dateTimeFormat = formatLong.dateTime({
width: 'medium'
});
break;
case 'PPP':
dateTimeFormat = formatLong.dateTime({
width: 'long'
});
break;
case 'PPPP':
default:
dateTimeFormat = formatLong.dateTime({
width: 'full'
});
break;
}
return dateTimeFormat.replace('{{date}}', dateLongFormatter(datePattern, formatLong)).replace('{{time}}', timeLongFormatter(timePattern, formatLong));
}
var longFormatters = {
p: timeLongFormatter,
P: dateTimeLongFormatter
};
/* harmony default export */ __webpack_exports__["default"] = (longFormatters);
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js":
/*!*********************************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js ***!
\*********************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getTimezoneOffsetInMilliseconds; });
var MILLISECONDS_IN_MINUTE = 60000;
/**
* Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.
* They usually appear for dates that denote time before the timezones were introduced
* (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891
* and GMT+01:00:00 after that date)
*
* Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
* which would lead to incorrect calculations.
*
* This function returns the timezone offset in milliseconds that takes seconds in account.
*/
function getTimezoneOffsetInMilliseconds(dirtyDate) {
var date = new Date(dirtyDate.getTime());
var baseTimezoneOffset = date.getTimezoneOffset();
date.setSeconds(0, 0);
var millisecondsPartOfTimezoneOffset = date.getTime() % MILLISECONDS_IN_MINUTE;
return baseTimezoneOffset * MILLISECONDS_IN_MINUTE + millisecondsPartOfTimezoneOffset;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/getUTCDayOfYear/index.js":
/*!*****************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/getUTCDayOfYear/index.js ***!
\*****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getUTCDayOfYear; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
var MILLISECONDS_IN_DAY = 86400000; // This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
function getUTCDayOfYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var timestamp = date.getTime();
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
var startOfYearTimestamp = date.getTime();
var difference = timestamp - startOfYearTimestamp;
return Math.floor(difference / MILLISECONDS_IN_DAY) + 1;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/getUTCISOWeek/index.js":
/*!***************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/getUTCISOWeek/index.js ***!
\***************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getUTCISOWeek; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _startOfUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfUTCISOWeek/index.js */ "./node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js");
/* harmony import */ var _startOfUTCISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../startOfUTCISOWeekYear/index.js */ "./node_modules/date-fns/esm/_lib/startOfUTCISOWeekYear/index.js");
var MILLISECONDS_IN_WEEK = 604800000; // This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
function getUTCISOWeek(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var diff = Object(_startOfUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date).getTime() - Object(_startOfUTCISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date).getTime(); // Round the number of days to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/getUTCISOWeekYear/index.js":
/*!*******************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/getUTCISOWeekYear/index.js ***!
\*******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getUTCISOWeekYear; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _startOfUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfUTCISOWeek/index.js */ "./node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js");
// This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
function getUTCISOWeekYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var year = date.getUTCFullYear();
var fourthOfJanuaryOfNextYear = new Date(0);
fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
var startOfNextYear = Object(_startOfUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(fourthOfJanuaryOfNextYear);
var fourthOfJanuaryOfThisYear = new Date(0);
fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
var startOfThisYear = Object(_startOfUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(fourthOfJanuaryOfThisYear);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/getUTCWeek/index.js":
/*!************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/getUTCWeek/index.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getUTCWeek; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _startOfUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfUTCWeek/index.js */ "./node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js");
/* harmony import */ var _startOfUTCWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../startOfUTCWeekYear/index.js */ "./node_modules/date-fns/esm/_lib/startOfUTCWeekYear/index.js");
var MILLISECONDS_IN_WEEK = 604800000; // This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
function getUTCWeek(dirtyDate, options) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var diff = Object(_startOfUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date, options).getTime() - Object(_startOfUTCWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date, options).getTime(); // Round the number of days to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js":
/*!****************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js ***!
\****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getUTCWeekYear; });
/* harmony import */ var _toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _startOfUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../startOfUTCWeek/index.js */ "./node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js");
// This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
function getUTCWeekYear(dirtyDate, dirtyOptions) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, dirtyOptions);
var year = date.getUTCFullYear();
var options = dirtyOptions || {};
var locale = options.locale;
var localeFirstWeekContainsDate = locale && locale.options && locale.options.firstWeekContainsDate;
var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : Object(_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeFirstWeekContainsDate);
var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : Object(_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.firstWeekContainsDate); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
}
var firstWeekOfNextYear = new Date(0);
firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
var startOfNextYear = Object(_startOfUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(firstWeekOfNextYear, dirtyOptions);
var firstWeekOfThisYear = new Date(0);
firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
var startOfThisYear = Object(_startOfUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(firstWeekOfThisYear, dirtyOptions);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/protectedTokens/index.js":
/*!*****************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/protectedTokens/index.js ***!
\*****************************************************************/
/*! exports provided: protectedTokens, isProtectedToken, throwProtectedError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "protectedTokens", function() { return protectedTokens; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isProtectedToken", function() { return isProtectedToken; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throwProtectedError", function() { return throwProtectedError; });
var protectedTokens = ['D', 'DD', 'YY', 'YYYY'];
function isProtectedToken(token) {
return protectedTokens.indexOf(token) !== -1;
}
function throwProtectedError(token) {
throw new RangeError('`options.awareOfUnicodeTokens` must be set to `true` to use `' + token + '` token; see: https://git.io/fxCyr');
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/setUTCDay/index.js":
/*!***********************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/setUTCDay/index.js ***!
\***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setUTCDay; });
/* harmony import */ var _toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
// This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
function setUTCDay(dirtyDate, dirtyDay, dirtyOptions) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var options = dirtyOptions || {};
var locale = options.locale;
var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : Object(_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeWeekStartsOn);
var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : Object(_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var day = Object(_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDay);
var currentDay = date.getUTCDay();
var remainder = day % 7;
var dayIndex = (remainder + 7) % 7;
var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay;
date.setUTCDate(date.getUTCDate() + diff);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/setUTCISODay/index.js":
/*!**************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/setUTCISODay/index.js ***!
\**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setUTCISODay; });
/* harmony import */ var _toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
// This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
function setUTCISODay(dirtyDate, dirtyDay) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var day = Object(_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDay);
if (day % 7 === 0) {
day = day - 7;
}
var weekStartsOn = 1;
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var currentDay = date.getUTCDay();
var remainder = day % 7;
var dayIndex = (remainder + 7) % 7;
var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay;
date.setUTCDate(date.getUTCDate() + diff);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/setUTCISOWeek/index.js":
/*!***************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/setUTCISOWeek/index.js ***!
\***************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setUTCISOWeek; });
/* harmony import */ var _toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _getUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../getUTCISOWeek/index.js */ "./node_modules/date-fns/esm/_lib/getUTCISOWeek/index.js");
// This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
function setUTCISOWeek(dirtyDate, dirtyISOWeek) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var isoWeek = Object(_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyISOWeek);
var diff = Object(_getUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date) - isoWeek;
date.setUTCDate(date.getUTCDate() - diff * 7);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/setUTCWeek/index.js":
/*!************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/setUTCWeek/index.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setUTCWeek; });
/* harmony import */ var _toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _getUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../getUTCWeek/index.js */ "./node_modules/date-fns/esm/_lib/getUTCWeek/index.js");
// This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
function setUTCWeek(dirtyDate, dirtyWeek, options) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var week = Object(_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyWeek);
var diff = Object(_getUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date, options) - week;
date.setUTCDate(date.getUTCDate() - diff * 7);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js":
/*!*******************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js ***!
\*******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfUTCISOWeek; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
// This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
function startOfUTCISOWeek(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var weekStartsOn = 1;
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var day = date.getUTCDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setUTCDate(date.getUTCDate() - diff);
date.setUTCHours(0, 0, 0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/startOfUTCISOWeekYear/index.js":
/*!***********************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/startOfUTCISOWeekYear/index.js ***!
\***********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfUTCISOWeekYear; });
/* harmony import */ var _getUTCISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../getUTCISOWeekYear/index.js */ "./node_modules/date-fns/esm/_lib/getUTCISOWeekYear/index.js");
/* harmony import */ var _startOfUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfUTCISOWeek/index.js */ "./node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js");
// This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
function startOfUTCISOWeekYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var year = Object(_getUTCISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var fourthOfJanuary = new Date(0);
fourthOfJanuary.setUTCFullYear(year, 0, 4);
fourthOfJanuary.setUTCHours(0, 0, 0, 0);
var date = Object(_startOfUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(fourthOfJanuary);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js":
/*!****************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js ***!
\****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfUTCWeek; });
/* harmony import */ var _toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
// This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
function startOfUTCWeek(dirtyDate, dirtyOptions) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var options = dirtyOptions || {};
var locale = options.locale;
var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : Object(_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeWeekStartsOn);
var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : Object(_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var day = date.getUTCDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setUTCDate(date.getUTCDate() - diff);
date.setUTCHours(0, 0, 0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/startOfUTCWeekYear/index.js":
/*!********************************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/startOfUTCWeekYear/index.js ***!
\********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfUTCWeekYear; });
/* harmony import */ var _toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _getUTCWeekYear_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../getUTCWeekYear/index.js */ "./node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js");
/* harmony import */ var _startOfUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../startOfUTCWeek/index.js */ "./node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js");
// This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
function startOfUTCWeekYear(dirtyDate, dirtyOptions) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var options = dirtyOptions || {};
var locale = options.locale;
var localeFirstWeekContainsDate = locale && locale.options && locale.options.firstWeekContainsDate;
var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : Object(_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeFirstWeekContainsDate);
var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : Object(_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.firstWeekContainsDate);
var year = Object(_getUTCWeekYear_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, dirtyOptions);
var firstWeek = new Date(0);
firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
firstWeek.setUTCHours(0, 0, 0, 0);
var date = Object(_startOfUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(firstWeek, dirtyOptions);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/_lib/toInteger/index.js":
/*!***********************************************************!*\
!*** ./node_modules/date-fns/esm/_lib/toInteger/index.js ***!
\***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return toInteger; });
function toInteger(dirtyNumber) {
if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
return NaN;
}
var number = Number(dirtyNumber);
if (isNaN(number)) {
return number;
}
return number < 0 ? Math.ceil(number) : Math.floor(number);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/addDays/index.js":
/*!****************************************************!*\
!*** ./node_modules/date-fns/esm/addDays/index.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return addDays; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name addDays
* @category Day Helpers
* @summary Add the specified number of days to the given date.
*
* @description
* Add the specified number of days to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of days to be added
* @returns {Date} the new date with the days added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 10 days to 1 September 2014:
* var result = addDays(new Date(2014, 8, 1), 10)
* //=> Thu Sep 11 2014 00:00:00
*/
function addDays(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
date.setDate(date.getDate() + amount);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/addHours/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/addHours/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return addHours; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addMilliseconds/index.js */ "./node_modules/date-fns/esm/addMilliseconds/index.js");
var MILLISECONDS_IN_HOUR = 3600000;
/**
* @name addHours
* @category Hour Helpers
* @summary Add the specified number of hours to the given date.
*
* @description
* Add the specified number of hours to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of hours to be added
* @returns {Date} the new date with the hours added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 2 hours to 10 July 2014 23:00:00:
* var result = addHours(new Date(2014, 6, 10, 23, 0), 2)
* //=> Fri Jul 11 2014 01:00:00
*/
function addHours(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, amount * MILLISECONDS_IN_HOUR);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/addISOWeekYears/index.js":
/*!************************************************************!*\
!*** ./node_modules/date-fns/esm/addISOWeekYears/index.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return addISOWeekYears; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _getISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../getISOWeekYear/index.js */ "./node_modules/date-fns/esm/getISOWeekYear/index.js");
/* harmony import */ var _setISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../setISOWeekYear/index.js */ "./node_modules/date-fns/esm/setISOWeekYear/index.js");
/**
* @name addISOWeekYears
* @category ISO Week-Numbering Year Helpers
* @summary Add the specified number of ISO week-numbering years to the given date.
*
* @description
* Add the specified number of ISO week-numbering years to the given date.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `addISOYears` to `addISOWeekYears`.
* "ISO week year" is short for [ISO week-numbering year](https://en.wikipedia.org/wiki/ISO_week_date).
* This change makes the name consistent with
* locale-dependent week-numbering year helpers, e.g., `addWeekYears`.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of ISO week-numbering years to be added
* @returns {Date} the new date with the ISO week-numbering years added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 5 ISO week-numbering years to 2 July 2010:
* var result = addISOWeekYears(new Date(2010, 6, 2), 5)
* //=> Fri Jun 26 2015 00:00:00
*/
function addISOWeekYears(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_setISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dirtyDate, Object(_getISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate) + amount);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/addMilliseconds/index.js":
/*!************************************************************!*\
!*** ./node_modules/date-fns/esm/addMilliseconds/index.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return addMilliseconds; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name addMilliseconds
* @category Millisecond Helpers
* @summary Add the specified number of milliseconds to the given date.
*
* @description
* Add the specified number of milliseconds to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of milliseconds to be added
* @returns {Date} the new date with the milliseconds added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 750 milliseconds to 10 July 2014 12:45:30.000:
* var result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
* //=> Thu Jul 10 2014 12:45:30.750
*/
function addMilliseconds(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var timestamp = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate).getTime();
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return new Date(timestamp + amount);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/addMinutes/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/addMinutes/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return addMinutes; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addMilliseconds/index.js */ "./node_modules/date-fns/esm/addMilliseconds/index.js");
var MILLISECONDS_IN_MINUTE = 60000;
/**
* @name addMinutes
* @category Minute Helpers
* @summary Add the specified number of minutes to the given date.
*
* @description
* Add the specified number of minutes to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of minutes to be added
* @returns {Date} the new date with the minutes added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 30 minutes to 10 July 2014 12:00:00:
* var result = addMinutes(new Date(2014, 6, 10, 12, 0), 30)
* //=> Thu Jul 10 2014 12:30:00
*/
function addMinutes(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, amount * MILLISECONDS_IN_MINUTE);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/addMonths/index.js":
/*!******************************************************!*\
!*** ./node_modules/date-fns/esm/addMonths/index.js ***!
\******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return addMonths; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _getDaysInMonth_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../getDaysInMonth/index.js */ "./node_modules/date-fns/esm/getDaysInMonth/index.js");
/**
* @name addMonths
* @category Month Helpers
* @summary Add the specified number of months to the given date.
*
* @description
* Add the specified number of months to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of months to be added
* @returns {Date} the new date with the months added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 5 months to 1 September 2014:
* var result = addMonths(new Date(2014, 8, 1), 5)
* //=> Sun Feb 01 2015 00:00:00
*/
function addMonths(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
var desiredMonth = date.getMonth() + amount;
var dateWithDesiredMonth = new Date(0);
dateWithDesiredMonth.setFullYear(date.getFullYear(), desiredMonth, 1);
dateWithDesiredMonth.setHours(0, 0, 0, 0);
var daysInMonth = Object(_getDaysInMonth_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dateWithDesiredMonth); // Set the last day of the new month
// if the original date was the last day of the longer month
date.setMonth(desiredMonth, Math.min(daysInMonth, date.getDate()));
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/addQuarters/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/addQuarters/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return addQuarters; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addMonths_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addMonths/index.js */ "./node_modules/date-fns/esm/addMonths/index.js");
/**
* @name addQuarters
* @category Quarter Helpers
* @summary Add the specified number of year quarters to the given date.
*
* @description
* Add the specified number of year quarters to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of quarters to be added
* @returns {Date} the new date with the quarters added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 1 quarter to 1 September 2014:
* var result = addQuarters(new Date(2014, 8, 1), 1)
* //=> Mon Dec 01 2014 00:00:00
*/
function addQuarters(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
var months = amount * 3;
return Object(_addMonths_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, months);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/addSeconds/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/addSeconds/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return addSeconds; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addMilliseconds/index.js */ "./node_modules/date-fns/esm/addMilliseconds/index.js");
/**
* @name addSeconds
* @category Second Helpers
* @summary Add the specified number of seconds to the given date.
*
* @description
* Add the specified number of seconds to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of seconds to be added
* @returns {Date} the new date with the seconds added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 30 seconds to 10 July 2014 12:45:00:
* var result = addSeconds(new Date(2014, 6, 10, 12, 45, 0), 30)
* //=> Thu Jul 10 2014 12:45:30
*/
function addSeconds(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, amount * 1000);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/addWeeks/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/addWeeks/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return addWeeks; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addDays_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addDays/index.js */ "./node_modules/date-fns/esm/addDays/index.js");
/**
* @name addWeeks
* @category Week Helpers
* @summary Add the specified number of weeks to the given date.
*
* @description
* Add the specified number of week to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of weeks to be added
* @returns {Date} the new date with the weeks added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 4 weeks to 1 September 2014:
* var result = addWeeks(new Date(2014, 8, 1), 4)
* //=> Mon Sep 29 2014 00:00:00
*/
function addWeeks(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
var days = amount * 7;
return Object(_addDays_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, days);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/addYears/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/addYears/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return addYears; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addMonths_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addMonths/index.js */ "./node_modules/date-fns/esm/addMonths/index.js");
/**
* @name addYears
* @category Year Helpers
* @summary Add the specified number of years to the given date.
*
* @description
* Add the specified number of years to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of years to be added
* @returns {Date} the new date with the years added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 5 years to 1 September 2014:
* var result = addYears(new Date(2014, 8, 1), 5)
* //=> Sun Sep 01 2019 00:00:00
*/
function addYears(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addMonths_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, amount * 12);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/areIntervalsOverlapping/index.js":
/*!********************************************************************!*\
!*** ./node_modules/date-fns/esm/areIntervalsOverlapping/index.js ***!
\********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return areIntervalsOverlapping; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name areIntervalsOverlapping
* @category Interval Helpers
* @summary Is the given time interval overlapping with another time interval?
*
* @description
* Is the given time interval overlapping with another time interval?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `areRangesOverlapping` to `areIntervalsOverlapping`.
* This change was made to mirror the use of the word "interval" in standard ISO 8601:2004 terminology:
*
* ```
* 2.1.3
* time interval
* part of the time axis limited by two instants
* ```
*
* Also, this function now accepts an object with `start` and `end` properties
* instead of two arguments as an interval.
* This function now throws `RangeError` if the start of the interval is after its end
* or if any date in the interval is `Invalid Date`.
*
* ```javascript
* // Before v2.0.0
*
* areRangesOverlapping(
* new Date(2014, 0, 10), new Date(2014, 0, 20),
* new Date(2014, 0, 17), new Date(2014, 0, 21)
* )
*
* // v2.0.0 onward
*
* areIntervalsOverlapping(
* { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
* { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }
* )
* ```
*
* @param {Interval} intervalLeft - the first interval to compare. See [Interval]{@link docs/types/Interval}
* @param {Interval} intervalRight - the second interval to compare. See [Interval]{@link docs/types/Interval}
* @returns {Boolean} whether the time intervals are overlapping
* @throws {TypeError} 2 arguments required
* @throws {RangeError} The start of an interval cannot be after its end
* @throws {RangeError} Date in interval cannot be `Invalid Date`
*
* @example
* // For overlapping time intervals:
* areIntervalsOverlapping(
* { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
* { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }
* )
* //=> true
*
* @example
* // For non-overlapping time intervals:
* areIntervalsOverlapping(
* { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
* { start: new Date(2014, 0, 21), end: new Date(2014, 0, 22) }
* )
* //=> false
*/
function areIntervalsOverlapping(dirtyIntervalLeft, dirtyIntervalRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var intervalLeft = dirtyIntervalLeft || {};
var intervalRight = dirtyIntervalRight || {};
var leftStartTime = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(intervalLeft.start).getTime();
var leftEndTime = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(intervalLeft.end).getTime();
var rightStartTime = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(intervalRight.start).getTime();
var rightEndTime = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(intervalRight.end).getTime(); // Throw an exception if start date is after end date or if any date is `Invalid Date`
if (!(leftStartTime <= leftEndTime && rightStartTime <= rightEndTime)) {
throw new RangeError('Invalid interval');
}
return leftStartTime < rightEndTime && rightStartTime < leftEndTime;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/closestIndexTo/index.js":
/*!***********************************************************!*\
!*** ./node_modules/date-fns/esm/closestIndexTo/index.js ***!
\***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return closestIndexTo; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name closestIndexTo
* @category Common Helpers
* @summary Return an index of the closest date from the array comparing to the given date.
*
* @description
* Return an index of the closest date from the array comparing to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - Now, `closestIndexTo` doesn't throw an exception
* when the second argument is not an array, and returns Invalid Date instead.
*
* @param {Date|Number} dateToCompare - the date to compare with
* @param {Date[]|Number[]} datesArray - the array to search
* @returns {Number} an index of the date closest to the given date
* @throws {TypeError} 2 arguments required
*
* @example
* // Which date is closer to 6 September 2015?
* var dateToCompare = new Date(2015, 8, 6)
* var datesArray = [
* new Date(2015, 0, 1),
* new Date(2016, 0, 1),
* new Date(2017, 0, 1)
* ]
* var result = closestIndexTo(dateToCompare, datesArray)
* //=> 1
*/
function closestIndexTo(dirtyDateToCompare, dirtyDatesArray) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateToCompare = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateToCompare);
if (isNaN(dateToCompare)) {
return NaN;
}
var timeToCompare = dateToCompare.getTime();
var datesArray; // `dirtyDatesArray` is undefined or null
if (dirtyDatesArray == null) {
datesArray = []; // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method
} else if (typeof dirtyDatesArray.forEach === 'function') {
datesArray = dirtyDatesArray; // If `dirtyDatesArray` is Array-like Object, convert to Array. Otherwise, make it empty Array
} else {
datesArray = Array.prototype.slice.call(dirtyDatesArray);
}
var result;
var minDistance;
datesArray.forEach(function (dirtyDate, index) {
var currentDate = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
if (isNaN(currentDate)) {
result = NaN;
minDistance = NaN;
return;
}
var distance = Math.abs(timeToCompare - currentDate.getTime());
if (result == null || distance < minDistance) {
result = index;
minDistance = distance;
}
});
return result;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/closestTo/index.js":
/*!******************************************************!*\
!*** ./node_modules/date-fns/esm/closestTo/index.js ***!
\******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return closestTo; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name closestTo
* @category Common Helpers
* @summary Return a date from the array closest to the given date.
*
* @description
* Return a date from the array closest to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - Now, `closestTo` doesn't throw an exception
* when the second argument is not an array, and returns Invalid Date instead.
*
* @param {Date|Number} dateToCompare - the date to compare with
* @param {Date[]|Number[]} datesArray - the array to search
* @returns {Date} the date from the array closest to the given date
* @throws {TypeError} 2 arguments required
*
* @example
* // Which date is closer to 6 September 2015: 1 January 2000 or 1 January 2030?
* var dateToCompare = new Date(2015, 8, 6)
* var result = closestTo(dateToCompare, [
* new Date(2000, 0, 1),
* new Date(2030, 0, 1)
* ])
* //=> Tue Jan 01 2030 00:00:00
*/
function closestTo(dirtyDateToCompare, dirtyDatesArray) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateToCompare = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateToCompare);
if (isNaN(dateToCompare)) {
return new Date(NaN);
}
var timeToCompare = dateToCompare.getTime();
var datesArray; // `dirtyDatesArray` is undefined or null
if (dirtyDatesArray == null) {
datesArray = []; // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method
} else if (typeof dirtyDatesArray.forEach === 'function') {
datesArray = dirtyDatesArray; // If `dirtyDatesArray` is Array-like Object, convert to Array. Otherwise, make it empty Array
} else {
datesArray = Array.prototype.slice.call(dirtyDatesArray);
}
var result;
var minDistance;
datesArray.forEach(function (dirtyDate) {
var currentDate = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
if (isNaN(currentDate)) {
result = new Date(NaN);
minDistance = NaN;
return;
}
var distance = Math.abs(timeToCompare - currentDate.getTime());
if (result == null || distance < minDistance) {
result = currentDate;
minDistance = distance;
}
});
return result;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/compareAsc/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/compareAsc/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return compareAsc; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name compareAsc
* @category Common Helpers
* @summary Compare the two dates and return -1, 0 or 1.
*
* @description
* Compare the two dates and return 1 if the first date is after the second,
* -1 if the first date is before the second or 0 if dates are equal.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to compare
* @param {Date|Number} dateRight - the second date to compare
* @returns {Number} the result of the comparison
* @throws {TypeError} 2 arguments required
*
* @example
* // Compare 11 February 1987 and 10 July 1989:
* var result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10))
* //=> -1
*
* @example
* // Sort the array of dates:
* var result = [
* new Date(1995, 6, 2),
* new Date(1987, 1, 11),
* new Date(1989, 6, 10)
* ].sort(compareAsc)
* //=> [
* // Wed Feb 11 1987 00:00:00,
* // Mon Jul 10 1989 00:00:00,
* // Sun Jul 02 1995 00:00:00
* // ]
*/
function compareAsc(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
var diff = dateLeft.getTime() - dateRight.getTime();
if (diff < 0) {
return -1;
} else if (diff > 0) {
return 1; // Return 0 if diff is 0; return NaN if diff is NaN
} else {
return diff;
}
}
/***/ }),
/***/ "./node_modules/date-fns/esm/compareDesc/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/compareDesc/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return compareDesc; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name compareDesc
* @category Common Helpers
* @summary Compare the two dates reverse chronologically and return -1, 0 or 1.
*
* @description
* Compare the two dates and return -1 if the first date is after the second,
* 1 if the first date is before the second or 0 if dates are equal.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to compare
* @param {Date|Number} dateRight - the second date to compare
* @returns {Number} the result of the comparison
* @throws {TypeError} 2 arguments required
*
* @example
* // Compare 11 February 1987 and 10 July 1989 reverse chronologically:
* var result = compareDesc(new Date(1987, 1, 11), new Date(1989, 6, 10))
* //=> 1
*
* @example
* // Sort the array of dates in reverse chronological order:
* var result = [
* new Date(1995, 6, 2),
* new Date(1987, 1, 11),
* new Date(1989, 6, 10)
* ].sort(compareDesc)
* //=> [
* // Sun Jul 02 1995 00:00:00,
* // Mon Jul 10 1989 00:00:00,
* // Wed Feb 11 1987 00:00:00
* // ]
*/
function compareDesc(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
var diff = dateLeft.getTime() - dateRight.getTime();
if (diff > 0) {
return -1;
} else if (diff < 0) {
return 1; // Return 0 if diff is 0; return NaN if diff is NaN
} else {
return diff;
}
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInCalendarDays/index.js":
/*!*********************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInCalendarDays/index.js ***!
\*********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInCalendarDays; });
/* harmony import */ var _lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/getTimezoneOffsetInMilliseconds/index.js */ "./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js");
/* harmony import */ var _startOfDay_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfDay/index.js */ "./node_modules/date-fns/esm/startOfDay/index.js");
var MILLISECONDS_IN_DAY = 86400000;
/**
* @name differenceInCalendarDays
* @category Day Helpers
* @summary Get the number of calendar days between the given dates.
*
* @description
* Get the number of calendar days between the given dates. This means that the times are removed
* from the dates and then the difference in days is calculated.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of calendar days
* @throws {TypeError} 2 arguments required
*
* @example
* // How many calendar days are between
* // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
* var result = differenceInCalendarDays(
* new Date(2012, 6, 2, 0, 0),
* new Date(2011, 6, 2, 23, 0)
* )
* //=> 366
* // How many calendar days are between
* // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
* var result = differenceInCalendarDays(
* new Date(2011, 6, 2, 0, 1),
* new Date(2011, 6, 2, 23, 59)
* )
* //=> 1
*/
function differenceInCalendarDays(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var startOfDayLeft = Object(_startOfDay_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDateLeft);
var startOfDayRight = Object(_startOfDay_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDateRight);
var timestampLeft = startOfDayLeft.getTime() - Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(startOfDayLeft);
var timestampRight = startOfDayRight.getTime() - Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(startOfDayRight); // Round the number of days to the nearest integer
// because the number of milliseconds in a day is not constant
// (e.g. it's different in the day of the daylight saving time clock shift)
return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInCalendarISOWeekYears/index.js":
/*!*****************************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInCalendarISOWeekYears/index.js ***!
\*****************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInCalendarISOWeekYears; });
/* harmony import */ var _getISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../getISOWeekYear/index.js */ "./node_modules/date-fns/esm/getISOWeekYear/index.js");
/**
* @name differenceInCalendarISOWeekYears
* @category ISO Week-Numbering Year Helpers
* @summary Get the number of calendar ISO week-numbering years between the given dates.
*
* @description
* Get the number of calendar ISO week-numbering years between the given dates.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `differenceInCalendarISOYears` to `differenceInCalendarISOWeekYears`.
* "ISO week year" is short for [ISO week-numbering year](https://en.wikipedia.org/wiki/ISO_week_date).
* This change makes the name consistent with
* locale-dependent week-numbering year helpers, e.g., `addWeekYears`.
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of calendar ISO week-numbering years
* @throws {TypeError} 2 arguments required
*
* @example
* // How many calendar ISO week-numbering years are 1 January 2010 and 1 January 2012?
* var result = differenceInCalendarISOWeekYears(
* new Date(2012, 0, 1),
* new Date(2010, 0, 1)
* )
* //=> 2
*/
function differenceInCalendarISOWeekYears(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
return Object(_getISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft) - Object(_getISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInCalendarISOWeeks/index.js":
/*!*************************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInCalendarISOWeeks/index.js ***!
\*************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInCalendarISOWeeks; });
/* harmony import */ var _lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/getTimezoneOffsetInMilliseconds/index.js */ "./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js");
/* harmony import */ var _startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfISOWeek/index.js */ "./node_modules/date-fns/esm/startOfISOWeek/index.js");
var MILLISECONDS_IN_WEEK = 604800000;
/**
* @name differenceInCalendarISOWeeks
* @category ISO Week Helpers
* @summary Get the number of calendar ISO weeks between the given dates.
*
* @description
* Get the number of calendar ISO weeks between the given dates.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of calendar ISO weeks
* @throws {TypeError} 2 arguments required
*
* @example
* // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014?
* var result = differenceInCalendarISOWeeks(
* new Date(2014, 6, 21),
* new Date(2014, 6, 6)
* )
* //=> 3
*/
function differenceInCalendarISOWeeks(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var startOfISOWeekLeft = Object(_startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDateLeft);
var startOfISOWeekRight = Object(_startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDateRight);
var timestampLeft = startOfISOWeekLeft.getTime() - Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(startOfISOWeekLeft);
var timestampRight = startOfISOWeekRight.getTime() - Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(startOfISOWeekRight); // Round the number of days to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInCalendarMonths/index.js":
/*!***********************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInCalendarMonths/index.js ***!
\***********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInCalendarMonths; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name differenceInCalendarMonths
* @category Month Helpers
* @summary Get the number of calendar months between the given dates.
*
* @description
* Get the number of calendar months between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of calendar months
* @throws {TypeError} 2 arguments required
*
* @example
* // How many calendar months are between 31 January 2014 and 1 September 2014?
* var result = differenceInCalendarMonths(
* new Date(2014, 8, 1),
* new Date(2014, 0, 31)
* )
* //=> 8
*/
function differenceInCalendarMonths(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear();
var monthDiff = dateLeft.getMonth() - dateRight.getMonth();
return yearDiff * 12 + monthDiff;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInCalendarQuarters/index.js":
/*!*************************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInCalendarQuarters/index.js ***!
\*************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInCalendarQuarters; });
/* harmony import */ var _getQuarter_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../getQuarter/index.js */ "./node_modules/date-fns/esm/getQuarter/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name differenceInCalendarQuarters
* @category Quarter Helpers
* @summary Get the number of calendar quarters between the given dates.
*
* @description
* Get the number of calendar quarters between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of calendar quarters
* @throws {TypeError} 2 arguments required
*
* @example
* // How many calendar quarters are between 31 December 2013 and 2 July 2014?
* var result = differenceInCalendarQuarters(
* new Date(2014, 6, 2),
* new Date(2013, 11, 31)
* )
* //=> 3
*/
function differenceInCalendarQuarters(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDateLeft);
var dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDateRight);
var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear();
var quarterDiff = Object(_getQuarter_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dateLeft) - Object(_getQuarter_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dateRight);
return yearDiff * 4 + quarterDiff;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInCalendarWeeks/index.js":
/*!**********************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInCalendarWeeks/index.js ***!
\**********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInCalendarWeeks; });
/* harmony import */ var _lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/getTimezoneOffsetInMilliseconds/index.js */ "./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js");
/* harmony import */ var _startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfWeek/index.js */ "./node_modules/date-fns/esm/startOfWeek/index.js");
var MILLISECONDS_IN_WEEK = 604800000;
/**
* @name differenceInCalendarWeeks
* @category Week Helpers
* @summary Get the number of calendar weeks between the given dates.
*
* @description
* Get the number of calendar weeks between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {Number} the number of calendar weeks
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // How many calendar weeks are between 5 July 2014 and 20 July 2014?
* var result = differenceInCalendarWeeks(
* new Date(2014, 6, 20),
* new Date(2014, 6, 5)
* )
* //=> 3
*
* @example
* // If the week starts on Monday,
* // how many calendar weeks are between 5 July 2014 and 20 July 2014?
* var result = differenceInCalendarWeeks(
* new Date(2014, 6, 20),
* new Date(2014, 6, 5),
* { weekStartsOn: 1 }
* )
* //=> 2
*/
function differenceInCalendarWeeks(dirtyDateLeft, dirtyDateRight, dirtyOptions) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var startOfWeekLeft = Object(_startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDateLeft, dirtyOptions);
var startOfWeekRight = Object(_startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDateRight, dirtyOptions);
var timestampLeft = startOfWeekLeft.getTime() - Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(startOfWeekLeft);
var timestampRight = startOfWeekRight.getTime() - Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(startOfWeekRight); // Round the number of days to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInCalendarYears/index.js":
/*!**********************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInCalendarYears/index.js ***!
\**********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInCalendarYears; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name differenceInCalendarYears
* @category Year Helpers
* @summary Get the number of calendar years between the given dates.
*
* @description
* Get the number of calendar years between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of calendar years
* @throws {TypeError} 2 arguments required
*
* @example
* // How many calendar years are between 31 December 2013 and 11 February 2015?
* var result = differenceInCalendarYears(
* new Date(2015, 1, 11),
* new Date(2013, 11, 31)
* )
* //=> 2
*/
function differenceInCalendarYears(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
return dateLeft.getFullYear() - dateRight.getFullYear();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInDays/index.js":
/*!*************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInDays/index.js ***!
\*************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInDays; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _differenceInCalendarDays_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../differenceInCalendarDays/index.js */ "./node_modules/date-fns/esm/differenceInCalendarDays/index.js");
/* harmony import */ var _compareAsc_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../compareAsc/index.js */ "./node_modules/date-fns/esm/compareAsc/index.js");
/**
* @name differenceInDays
* @category Day Helpers
* @summary Get the number of full days between the given dates.
*
* @description
* Get the number of full day periods between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of full days
* @throws {TypeError} 2 arguments required
*
* @example
* // How many full days are between
* // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
* var result = differenceInDays(
* new Date(2012, 6, 2, 0, 0),
* new Date(2011, 6, 2, 23, 0)
* )
* //=> 365
* // How many days are between
* // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
* var result = differenceInDays(
* new Date(2011, 6, 2, 0, 1),
* new Date(2011, 6, 2, 23, 59)
* )
* //=> 0
*/
function differenceInDays(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
var sign = Object(_compareAsc_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dateLeft, dateRight);
var difference = Math.abs(Object(_differenceInCalendarDays_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dateLeft, dateRight));
dateLeft.setDate(dateLeft.getDate() - sign * difference); // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full
// If so, result must be decreased by 1 in absolute value
var isLastDayNotFull = Object(_compareAsc_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dateLeft, dateRight) === -sign;
var result = sign * (difference - isLastDayNotFull); // Prevent negative zero
return result === 0 ? 0 : result;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInHours/index.js":
/*!**************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInHours/index.js ***!
\**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInHours; });
/* harmony import */ var _differenceInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../differenceInMilliseconds/index.js */ "./node_modules/date-fns/esm/differenceInMilliseconds/index.js");
var MILLISECONDS_IN_HOUR = 3600000;
/**
* @name differenceInHours
* @category Hour Helpers
* @summary Get the number of hours between the given dates.
*
* @description
* Get the number of hours between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of hours
* @throws {TypeError} 2 arguments required
*
* @example
* // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00?
* var result = differenceInHours(
* new Date(2014, 6, 2, 19, 0),
* new Date(2014, 6, 2, 6, 50)
* )
* //=> 12
*/
function differenceInHours(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var diff = Object(_differenceInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_HOUR;
return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInISOWeekYears/index.js":
/*!*********************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInISOWeekYears/index.js ***!
\*********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInISOWeekYears; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _differenceInCalendarISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../differenceInCalendarISOWeekYears/index.js */ "./node_modules/date-fns/esm/differenceInCalendarISOWeekYears/index.js");
/* harmony import */ var _compareAsc_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../compareAsc/index.js */ "./node_modules/date-fns/esm/compareAsc/index.js");
/* harmony import */ var _subISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../subISOWeekYears/index.js */ "./node_modules/date-fns/esm/subISOWeekYears/index.js");
/**
* @name differenceInISOWeekYears
* @category ISO Week-Numbering Year Helpers
* @summary Get the number of full ISO week-numbering years between the given dates.
*
* @description
* Get the number of full ISO week-numbering years between the given dates.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `differenceInISOYears` to `differenceInISOWeekYears`.
* "ISO week year" is short for [ISO week-numbering year](https://en.wikipedia.org/wiki/ISO_week_date).
* This change makes the name consistent with
* locale-dependent week-numbering year helpers, e.g., `addWeekYears`.
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of full ISO week-numbering years
* @throws {TypeError} 2 arguments required
*
* @example
* // How many full ISO week-numbering years are between 1 January 2010 and 1 January 2012?
* var result = differenceInISOWeekYears(
* new Date(2012, 0, 1),
* new Date(2010, 0, 1)
* )
* //=> 1
*/
function differenceInISOWeekYears(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
var sign = Object(_compareAsc_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dateLeft, dateRight);
var difference = Math.abs(Object(_differenceInCalendarISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dateLeft, dateRight));
dateLeft = Object(_subISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(dateLeft, sign * difference); // Math.abs(diff in full ISO years - diff in calendar ISO years) === 1
// if last calendar ISO year is not full
// If so, result must be decreased by 1 in absolute value
var isLastISOWeekYearNotFull = Object(_compareAsc_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dateLeft, dateRight) === -sign;
var result = sign * (difference - isLastISOWeekYearNotFull); // Prevent negative zero
return result === 0 ? 0 : result;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInMilliseconds/index.js":
/*!*********************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInMilliseconds/index.js ***!
\*********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInMilliseconds; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name differenceInMilliseconds
* @category Millisecond Helpers
* @summary Get the number of milliseconds between the given dates.
*
* @description
* Get the number of milliseconds between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of milliseconds
* @throws {TypeError} 2 arguments required
*
* @example
* // How many milliseconds are between
* // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700?
* var result = differenceInMilliseconds(
* new Date(2014, 6, 2, 12, 30, 21, 700),
* new Date(2014, 6, 2, 12, 30, 20, 600)
* )
* //=> 1100
*/
function differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
return dateLeft.getTime() - dateRight.getTime();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInMinutes/index.js":
/*!****************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInMinutes/index.js ***!
\****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInMinutes; });
/* harmony import */ var _differenceInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../differenceInMilliseconds/index.js */ "./node_modules/date-fns/esm/differenceInMilliseconds/index.js");
var MILLISECONDS_IN_MINUTE = 60000;
/**
* @name differenceInMinutes
* @category Minute Helpers
* @summary Get the number of minutes between the given dates.
*
* @description
* Get the number of minutes between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of minutes
* @throws {TypeError} 2 arguments required
*
* @example
* // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?
* var result = differenceInMinutes(
* new Date(2014, 6, 2, 12, 20, 0),
* new Date(2014, 6, 2, 12, 7, 59)
* )
* //=> 12
*/
function differenceInMinutes(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var diff = Object(_differenceInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_MINUTE;
return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInMonths/index.js":
/*!***************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInMonths/index.js ***!
\***************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInMonths; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _differenceInCalendarMonths_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../differenceInCalendarMonths/index.js */ "./node_modules/date-fns/esm/differenceInCalendarMonths/index.js");
/* harmony import */ var _compareAsc_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../compareAsc/index.js */ "./node_modules/date-fns/esm/compareAsc/index.js");
/**
* @name differenceInMonths
* @category Month Helpers
* @summary Get the number of full months between the given dates.
*
* @description
* Get the number of full months between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of full months
* @throws {TypeError} 2 arguments required
*
* @example
* // How many full months are between 31 January 2014 and 1 September 2014?
* var result = differenceInMonths(new Date(2014, 8, 1), new Date(2014, 0, 31))
* //=> 7
*/
function differenceInMonths(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
var sign = Object(_compareAsc_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dateLeft, dateRight);
var difference = Math.abs(Object(_differenceInCalendarMonths_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dateLeft, dateRight));
dateLeft.setMonth(dateLeft.getMonth() - sign * difference); // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full
// If so, result must be decreased by 1 in absolute value
var isLastMonthNotFull = Object(_compareAsc_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dateLeft, dateRight) === -sign;
var result = sign * (difference - isLastMonthNotFull); // Prevent negative zero
return result === 0 ? 0 : result;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInQuarters/index.js":
/*!*****************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInQuarters/index.js ***!
\*****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInQuarters; });
/* harmony import */ var _differenceInMonths_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../differenceInMonths/index.js */ "./node_modules/date-fns/esm/differenceInMonths/index.js");
/**
* @name differenceInQuarters
* @category Quarter Helpers
* @summary Get the number of full quarters between the given dates.
*
* @description
* Get the number of full quarters between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of full quarters
* @throws {TypeError} 2 arguments required
*
* @example
* // How many full quarters are between 31 December 2013 and 2 July 2014?
* var result = differenceInQuarters(new Date(2014, 6, 2), new Date(2013, 11, 31))
* //=> 2
*/
function differenceInQuarters(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var diff = Object(_differenceInMonths_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft, dirtyDateRight) / 3;
return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInSeconds/index.js":
/*!****************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInSeconds/index.js ***!
\****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInSeconds; });
/* harmony import */ var _differenceInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../differenceInMilliseconds/index.js */ "./node_modules/date-fns/esm/differenceInMilliseconds/index.js");
/**
* @name differenceInSeconds
* @category Second Helpers
* @summary Get the number of seconds between the given dates.
*
* @description
* Get the number of seconds between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of seconds
* @throws {TypeError} 2 arguments required
*
* @example
* // How many seconds are between
* // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000?
* var result = differenceInSeconds(
* new Date(2014, 6, 2, 12, 30, 20, 0),
* new Date(2014, 6, 2, 12, 30, 7, 999)
* )
* //=> 12
*/
function differenceInSeconds(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var diff = Object(_differenceInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft, dirtyDateRight) / 1000;
return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInWeeks/index.js":
/*!**************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInWeeks/index.js ***!
\**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInWeeks; });
/* harmony import */ var _differenceInDays_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../differenceInDays/index.js */ "./node_modules/date-fns/esm/differenceInDays/index.js");
/**
* @name differenceInWeeks
* @category Week Helpers
* @summary Get the number of full weeks between the given dates.
*
* @description
* Get the number of full weeks between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of full weeks
* @throws {TypeError} 2 arguments required
*
* @example
* // How many full weeks are between 5 July 2014 and 20 July 2014?
* var result = differenceInWeeks(new Date(2014, 6, 20), new Date(2014, 6, 5))
* //=> 2
*/
function differenceInWeeks(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var diff = Object(_differenceInDays_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft, dirtyDateRight) / 7;
return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/differenceInYears/index.js":
/*!**************************************************************!*\
!*** ./node_modules/date-fns/esm/differenceInYears/index.js ***!
\**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return differenceInYears; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _differenceInCalendarYears_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../differenceInCalendarYears/index.js */ "./node_modules/date-fns/esm/differenceInCalendarYears/index.js");
/* harmony import */ var _compareAsc_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../compareAsc/index.js */ "./node_modules/date-fns/esm/compareAsc/index.js");
/**
* @name differenceInYears
* @category Year Helpers
* @summary Get the number of full years between the given dates.
*
* @description
* Get the number of full years between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of full years
* @throws {TypeError} 2 arguments required
*
* @example
* // How many full years are between 31 December 2013 and 11 February 2015?
* var result = differenceInYears(new Date(2015, 1, 11), new Date(2013, 11, 31))
* //=> 1
*/
function differenceInYears(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
var sign = Object(_compareAsc_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dateLeft, dateRight);
var difference = Math.abs(Object(_differenceInCalendarYears_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dateLeft, dateRight));
dateLeft.setFullYear(dateLeft.getFullYear() - sign * difference); // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full
// If so, result must be decreased by 1 in absolute value
var isLastYearNotFull = Object(_compareAsc_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dateLeft, dateRight) === -sign;
var result = sign * (difference - isLastYearNotFull); // Prevent negative zero
return result === 0 ? 0 : result;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/eachDayOfInterval/index.js":
/*!**************************************************************!*\
!*** ./node_modules/date-fns/esm/eachDayOfInterval/index.js ***!
\**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return eachDayOfInterval; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name eachDayOfInterval
* @category Interval Helpers
* @summary Return the array of dates within the specified time interval.
*
* @description
* Return the array of dates within the specified time interval.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `eachDay` to `eachDayOfInterval`.
* This change was made to mirror the use of the word "interval" in standard ISO 8601:2004 terminology:
*
* ```
* 2.1.3
* time interval
* part of the time axis limited by two instants
* ```
*
* Also, this function now accepts an object with `start` and `end` properties
* instead of two arguments as an interval.
* This function now throws `RangeError` if the start of the interval is after its end
* or if any date in the interval is `Invalid Date`.
*
* ```javascript
* // Before v2.0.0
*
* eachDay(new Date(2014, 0, 10), new Date(2014, 0, 20))
*
* // v2.0.0 onward
*
* eachDayOfInterval(
* { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) }
* )
* ```
*
* @param {Interval} interval - the interval. See [Interval]{@link docs/types/Interval}
* @param {Object} [options] - an object with options.
* @param {Number} [options.step=1] - the step to increment by. The value should be more than 1.
* @returns {Date[]} the array with starts of days from the day of the interval start to the day of the interval end
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.step` must be a number greater than 1
* @throws {RangeError} The start of an interval cannot be after its end
* @throws {RangeError} Date in interval cannot be `Invalid Date`
*
* @example
* // Each day between 6 October 2014 and 10 October 2014:
* var result = eachDayOfInterval({
* start: new Date(2014, 9, 6),
* end: new Date(2014, 9, 10)
* })
* //=> [
* // Mon Oct 06 2014 00:00:00,
* // Tue Oct 07 2014 00:00:00,
* // Wed Oct 08 2014 00:00:00,
* // Thu Oct 09 2014 00:00:00,
* // Fri Oct 10 2014 00:00:00
* // ]
*/
function eachDayOfInterval(dirtyInterval, options) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var interval = dirtyInterval || {};
var startDate = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(interval.start);
var endDate = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(interval.end);
var endTime = endDate.getTime(); // Throw an exception if start date is after end date or if any date is `Invalid Date`
if (!(startDate.getTime() <= endTime)) {
throw new RangeError('Invalid interval');
}
var dates = [];
var currentDate = startDate;
currentDate.setHours(0, 0, 0, 0);
var step = options && 'step' in options ? Number(options.step) : 1;
if (step < 1 || isNaN(step)) throw new RangeError('`options.step` must be a number greater than 1');
while (currentDate.getTime() <= endTime) {
dates.push(Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(currentDate));
currentDate.setDate(currentDate.getDate() + step);
currentDate.setHours(0, 0, 0, 0);
}
return dates;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/eachWeekOfInterval/index.js":
/*!***************************************************************!*\
!*** ./node_modules/date-fns/esm/eachWeekOfInterval/index.js ***!
\***************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return eachWeekOfInterval; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfWeek/index.js */ "./node_modules/date-fns/esm/startOfWeek/index.js");
/* harmony import */ var _addWeeks_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../addWeeks/index.js */ "./node_modules/date-fns/esm/addWeeks/index.js");
/**
* @name eachWeekOfInterval
* @category Interval Helpers
* @summary Return the array of weeks within the specified time interval.
*
* @description
* Return the array of weeks within the specified time interval.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Interval} interval - the interval. See [Interval]{@link docs/types/Interval}
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @returns {Date[]} the array with starts of weeks from the week of the interval start to the week of the interval end
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be 0, 1, ..., 6
* @throws {RangeError} The start of an interval cannot be after its end
* @throws {RangeError} Date in interval cannot be `Invalid Date`
*
* @example
* // Each week within interval 6 October 2014 - 23 November 2014:
* var result = eachWeekOfInterval({
* start: new Date(2014, 9, 6),
* end: new Date(2014, 10, 23)
* })
* //=> [
* // Sun Oct 05 2014 00:00:00,
* // Sun Oct 12 2014 00:00:00,
* // Sun Oct 19 2014 00:00:00,
* // Sun Oct 26 2014 00:00:00,
* // Sun Nov 02 2014 00:00:00,
* // Sun Nov 09 2014 00:00:00,
* // Sun Nov 16 2014 00:00:00,
* // Sun Nov 23 2014 00:00:00
* // ]
*/
function eachWeekOfInterval(dirtyInterval, options) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var interval = dirtyInterval || {};
var startDate = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(interval.start);
var endDate = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(interval.end);
var endTime = endDate.getTime(); // Throw an exception if start date is after end date or if any date is `Invalid Date`
if (!(startDate.getTime() <= endTime)) {
throw new RangeError('Invalid interval');
}
var startDateWeek = Object(_startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(startDate, options);
var endDateWeek = Object(_startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(endDate, options); // Some timezones switch DST at midnight, making start of day unreliable in these timezones, 3pm is a safe bet
startDateWeek.setHours(15);
endDateWeek.setHours(15);
endTime = endDateWeek.getTime();
var weeks = [];
var currentWeek = startDateWeek;
while (currentWeek.getTime() <= endTime) {
currentWeek.setHours(0);
weeks.push(Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(currentWeek));
currentWeek = Object(_addWeeks_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(currentWeek, 1);
currentWeek.setHours(15);
}
return weeks;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/eachWeekendOfInterval/index.js":
/*!******************************************************************!*\
!*** ./node_modules/date-fns/esm/eachWeekendOfInterval/index.js ***!
\******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return eachWeekendOfInterval; });
/* harmony import */ var _eachDayOfInterval_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../eachDayOfInterval/index.js */ "./node_modules/date-fns/esm/eachDayOfInterval/index.js");
/* harmony import */ var _isSunday_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../isSunday/index.js */ "./node_modules/date-fns/esm/isSunday/index.js");
/* harmony import */ var _isWeekend_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../isWeekend/index.js */ "./node_modules/date-fns/esm/isWeekend/index.js");
/**
* @name eachWeekendOfInterval
* @category Interval Helpers
* @summary List all the Saturdays and Sundays in the given date interval.
*
* @description
* Get all the Saturdays and Sundays in the given date interval.
*
* @param {Interval} interval - the given interval. See [Interval]{@link docs/types/Interval}
* @returns {Date[]} an array containing all the Saturdays and Sundays
* @throws {TypeError} 1 argument required
* @throws {RangeError} The start of an interval cannot be after its end
* @throws {RangeError} Date in interval cannot be `Invalid Date`
*
* @example
* // Lists all Saturdays and Sundays in the given date interval
* var result = eachWeekendOfInterval({
* start: new Date(2018, 8, 17),
* end: new Date(2018, 8, 30)
* })
* //=> [
* // Sat Sep 22 2018 00:00:00,
* // Sun Sep 23 2018 00:00:00,
* // Sat Sep 29 2018 00:00:00,
* // Sun Sep 30 2018 00:00:00
* // ]
*/
function eachWeekendOfInterval(interval) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var dateInterval = Object(_eachDayOfInterval_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(interval);
var weekends = [];
var index = 0;
while (index++ < dateInterval.length) {
var date = dateInterval[index];
if (Object(_isWeekend_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date)) {
weekends.push(date);
if (Object(_isSunday_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date)) index = index + 5;
}
}
return weekends;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/eachWeekendOfMonth/index.js":
/*!***************************************************************!*\
!*** ./node_modules/date-fns/esm/eachWeekendOfMonth/index.js ***!
\***************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return eachWeekendOfMonth; });
/* harmony import */ var _eachWeekendOfInterval_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../eachWeekendOfInterval/index.js */ "./node_modules/date-fns/esm/eachWeekendOfInterval/index.js");
/* harmony import */ var _startOfMonth_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfMonth/index.js */ "./node_modules/date-fns/esm/startOfMonth/index.js");
/* harmony import */ var _endOfMonth_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../endOfMonth/index.js */ "./node_modules/date-fns/esm/endOfMonth/index.js");
/**
* @name eachWeekendOfMonth
* @category Month Helpers
* @summary List all the Saturdays and Sundays in the given month.
*
* @description
* Get all the Saturdays and Sundays in the given month.
*
* @param {Date|Number} date - the given month
* @returns {Date[]} an array containing all the Saturdays and Sundays
* @throws {TypeError} 1 argument required
* @throws {RangeError} The passed date is invalid
*
* @example
* // Lists all Saturdays and Sundays in the given month
* var result = eachWeekendOfMonth(new Date(2022, 1, 1))
* //=> [
* // Sat Feb 05 2022 00:00:00,
* // Sun Feb 06 2022 00:00:00,
* // Sat Feb 12 2022 00:00:00,
* // Sun Feb 13 2022 00:00:00,
* // Sat Feb 19 2022 00:00:00,
* // Sun Feb 20 2022 00:00:00,
* // Sat Feb 26 2022 00:00:00,
* // Sun Feb 27 2022 00:00:00
* // ]
*/
function eachWeekendOfMonth(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 arguments required, but only ' + arguments.length + ' present');
}
var startDate = Object(_startOfMonth_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
if (isNaN(startDate)) throw new RangeError('The passed date is invalid');
var endDate = Object(_endOfMonth_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dirtyDate);
return Object(_eachWeekendOfInterval_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])({
start: startDate,
end: endDate
});
}
/***/ }),
/***/ "./node_modules/date-fns/esm/eachWeekendOfYear/index.js":
/*!**************************************************************!*\
!*** ./node_modules/date-fns/esm/eachWeekendOfYear/index.js ***!
\**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return eachWeekendOfYear; });
/* harmony import */ var _eachWeekendOfInterval_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../eachWeekendOfInterval/index.js */ "./node_modules/date-fns/esm/eachWeekendOfInterval/index.js");
/* harmony import */ var _startOfYear_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfYear/index.js */ "./node_modules/date-fns/esm/startOfYear/index.js");
/* harmony import */ var _endOfYear_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../endOfYear/index.js */ "./node_modules/date-fns/esm/endOfYear/index.js");
/**
* @name eachWeekendOfYear
* @category Year Helpers
* @summary List all the Saturdays and Sundays in the year.
*
* @description
* Get all the Saturdays and Sundays in the year.
*
* @param {Date|Number} date - the given year
* @returns {Date[]} an array containing all the Saturdays and Sundays
* @throws {TypeError} 1 argument required
* @throws {RangeError} The passed date is invalid
*
* @example
* // Lists all Saturdays and Sundays in the year
* var result = eachWeekendOfYear(new Date(2020, 1, 1))
* //=> [
* // Sat Jan 03 2020 00:00:00,
* // Sun Jan 04 2020 00:00:00,
* // ...
* // Sun Dec 27 2020 00:00:00
* // ]
* ]
*/
function eachWeekendOfYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 arguments required, but only ' + arguments.length + ' present');
}
var startDate = Object(_startOfYear_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
if (isNaN(startDate)) throw new RangeError('The passed date is invalid');
var endDate = Object(_endOfYear_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dirtyDate);
return Object(_eachWeekendOfInterval_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])({
start: startDate,
end: endDate
});
}
/***/ }),
/***/ "./node_modules/date-fns/esm/endOfDay/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/endOfDay/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return endOfDay; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name endOfDay
* @category Day Helpers
* @summary Return the end of a day for the given date.
*
* @description
* Return the end of a day for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of a day
* @throws {TypeError} 1 argument required
*
* @example
* // The end of a day for 2 September 2014 11:55:00:
* var result = endOfDay(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 02 2014 23:59:59.999
*/
function endOfDay(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
date.setHours(23, 59, 59, 999);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/endOfDecade/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/endOfDecade/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return endOfDecade; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name endOfDecade
* @category Decade Helpers
* @summary Return the end of a decade for the given date.
*
* @description
* Return the end of a decade for the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of a decade
* @param {Object} [options] - an object with options.
* @param {0|1|2} [options.additionalDigits=2] - passed to `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2
*
* @example
* // The end of a decade for 12 May 1984 00:00:00:
* var result = endOfDecade(new Date(1984, 4, 12, 00, 00, 00))
* //=> Dec 31 1989 23:59:59.999
*/
function endOfDecade(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var year = date.getFullYear();
var decade = 9 + Math.floor(year / 10) * 10;
date.setFullYear(decade, 11, 31);
date.setHours(23, 59, 59, 999);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/endOfHour/index.js":
/*!******************************************************!*\
!*** ./node_modules/date-fns/esm/endOfHour/index.js ***!
\******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return endOfHour; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name endOfHour
* @category Hour Helpers
* @summary Return the end of an hour for the given date.
*
* @description
* Return the end of an hour for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of an hour
* @throws {TypeError} 1 argument required
*
* @example
* // The end of an hour for 2 September 2014 11:55:00:
* var result = endOfHour(new Date(2014, 8, 2, 11, 55))
* //=> Tue Sep 02 2014 11:59:59.999
*/
function endOfHour(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
date.setMinutes(59, 59, 999);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/endOfISOWeek/index.js":
/*!*********************************************************!*\
!*** ./node_modules/date-fns/esm/endOfISOWeek/index.js ***!
\*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return endOfISOWeek; });
/* harmony import */ var _endOfWeek_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../endOfWeek/index.js */ "./node_modules/date-fns/esm/endOfWeek/index.js");
/**
* @name endOfISOWeek
* @category ISO Week Helpers
* @summary Return the end of an ISO week for the given date.
*
* @description
* Return the end of an ISO week for the given date.
* The result will be in the local timezone.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of an ISO week
* @throws {TypeError} 1 argument required
*
* @example
* // The end of an ISO week for 2 September 2014 11:55:00:
* var result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sun Sep 07 2014 23:59:59.999
*/
function endOfISOWeek(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return Object(_endOfWeek_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate, {
weekStartsOn: 1
});
}
/***/ }),
/***/ "./node_modules/date-fns/esm/endOfISOWeekYear/index.js":
/*!*************************************************************!*\
!*** ./node_modules/date-fns/esm/endOfISOWeekYear/index.js ***!
\*************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return endOfISOWeekYear; });
/* harmony import */ var _getISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../getISOWeekYear/index.js */ "./node_modules/date-fns/esm/getISOWeekYear/index.js");
/* harmony import */ var _startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfISOWeek/index.js */ "./node_modules/date-fns/esm/startOfISOWeek/index.js");
/**
* @name endOfISOWeekYear
* @category ISO Week-Numbering Year Helpers
* @summary Return the end of an ISO week-numbering year for the given date.
*
* @description
* Return the end of an ISO week-numbering year,
* which always starts 3 days before the year's first Thursday.
* The result will be in the local timezone.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `endOfISOYear` to `endOfISOWeekYear`.
* "ISO week year" is short for [ISO week-numbering year](https://en.wikipedia.org/wiki/ISO_week_date).
* This change makes the name consistent with
* locale-dependent week-numbering year helpers, e.g., `addWeekYears`.
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of an ISO week-numbering year
* @throws {TypeError} 1 argument required
*
* @example
* // The end of an ISO week-numbering year for 2 July 2005:
* var result = endOfISOWeekYear(new Date(2005, 6, 2))
* //=> Sun Jan 01 2006 23:59:59.999
*/
function endOfISOWeekYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var year = Object(_getISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var fourthOfJanuaryOfNextYear = new Date(0);
fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);
fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);
var date = Object(_startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(fourthOfJanuaryOfNextYear);
date.setMilliseconds(date.getMilliseconds() - 1);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/endOfMinute/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/endOfMinute/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return endOfMinute; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name endOfMinute
* @category Minute Helpers
* @summary Return the end of a minute for the given date.
*
* @description
* Return the end of a minute for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of a minute
* @throws {TypeError} 1 argument required
*
* @example
* // The end of a minute for 1 December 2014 22:15:45.400:
* var result = endOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400))
* //=> Mon Dec 01 2014 22:15:59.999
*/
function endOfMinute(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
date.setSeconds(59, 999);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/endOfMonth/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/endOfMonth/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return endOfMonth; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name endOfMonth
* @category Month Helpers
* @summary Return the end of a month for the given date.
*
* @description
* Return the end of a month for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of a month
* @throws {TypeError} 1 argument required
*
* @example
* // The end of a month for 2 September 2014 11:55:00:
* var result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 30 2014 23:59:59.999
*/
function endOfMonth(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var month = date.getMonth();
date.setFullYear(date.getFullYear(), month + 1, 0);
date.setHours(23, 59, 59, 999);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/endOfQuarter/index.js":
/*!*********************************************************!*\
!*** ./node_modules/date-fns/esm/endOfQuarter/index.js ***!
\*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return endOfQuarter; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name endOfQuarter
* @category Quarter Helpers
* @summary Return the end of a year quarter for the given date.
*
* @description
* Return the end of a year quarter for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of a quarter
* @throws {TypeError} 1 argument required
*
* @example
* // The end of a quarter for 2 September 2014 11:55:00:
* var result = endOfQuarter(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 30 2014 23:59:59.999
*/
function endOfQuarter(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var currentMonth = date.getMonth();
var month = currentMonth - currentMonth % 3 + 3;
date.setMonth(month, 0);
date.setHours(23, 59, 59, 999);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/endOfSecond/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/endOfSecond/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return endOfSecond; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name endOfSecond
* @category Second Helpers
* @summary Return the end of a second for the given date.
*
* @description
* Return the end of a second for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of a second
* @throws {TypeError} 1 argument required
*
* @example
* // The end of a second for 1 December 2014 22:15:45.400:
* var result = endOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400))
* //=> Mon Dec 01 2014 22:15:45.999
*/
function endOfSecond(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
date.setMilliseconds(999);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/endOfWeek/index.js":
/*!******************************************************!*\
!*** ./node_modules/date-fns/esm/endOfWeek/index.js ***!
\******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return endOfWeek; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name endOfWeek
* @category Week Helpers
* @summary Return the end of a week for the given date.
*
* @description
* Return the end of a week for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {Date} the end of a week
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // The end of a week for 2 September 2014 11:55:00:
* var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sat Sep 06 2014 23:59:59.999
*
* @example
* // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00:
* var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
* //=> Sun Sep 07 2014 23:59:59.999
*/
function endOfWeek(dirtyDate, dirtyOptions) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var options = dirtyOptions || {};
var locale = options.locale;
var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeWeekStartsOn);
var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var day = date.getDay();
var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
date.setDate(date.getDate() + diff);
date.setHours(23, 59, 59, 999);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/endOfYear/index.js":
/*!******************************************************!*\
!*** ./node_modules/date-fns/esm/endOfYear/index.js ***!
\******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return endOfYear; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name endOfYear
* @category Year Helpers
* @summary Return the end of a year for the given date.
*
* @description
* Return the end of a year for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of a year
* @throws {TypeError} 1 argument required
*
* @example
* // The end of a year for 2 September 2014 11:55:00:
* var result = endOfYear(new Date(2014, 8, 2, 11, 55, 00))
* //=> Wed Dec 31 2014 23:59:59.999
*/
function endOfYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var year = date.getFullYear();
date.setFullYear(year + 1, 0, 0);
date.setHours(23, 59, 59, 999);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/format/index.js":
/*!***************************************************!*\
!*** ./node_modules/date-fns/esm/format/index.js ***!
\***************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return format; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../_lib/getTimezoneOffsetInMilliseconds/index.js */ "./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _isValid_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../isValid/index.js */ "./node_modules/date-fns/esm/isValid/index.js");
/* harmony import */ var _locale_en_US_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../locale/en-US/index.js */ "./node_modules/date-fns/esm/locale/en-US/index.js");
/* harmony import */ var _lib_format_formatters_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../_lib/format/formatters/index.js */ "./node_modules/date-fns/esm/_lib/format/formatters/index.js");
/* harmony import */ var _lib_format_longFormatters_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../_lib/format/longFormatters/index.js */ "./node_modules/date-fns/esm/_lib/format/longFormatters/index.js");
/* harmony import */ var _subMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../subMilliseconds/index.js */ "./node_modules/date-fns/esm/subMilliseconds/index.js");
/* harmony import */ var _lib_protectedTokens_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../_lib/protectedTokens/index.js */ "./node_modules/date-fns/esm/_lib/protectedTokens/index.js");
// This RegExp consists of three parts separated by `|`:
// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
// (one of the certain letters followed by `o`)
// - (\w)\1* matches any sequences of the same letter
// - '' matches two quote characters in a row
// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
// except a single quote symbol, which ends the sequence.
// Two quote characters do not end the sequence.
// If there is no matching single quote
// then the sequence will continue until the end of the string.
// - . matches any single character unmatched by previous parts of the RegExps
var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also
// sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
var escapedStringRegExp = /^'(.*?)'?$/;
var doubleQuoteRegExp = /''/g;
/**
* @name format
* @category Common Helpers
* @summary Format the date.
*
* @description
* Return the formatted date string in the given format. The result may vary by locale.
*
* > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
* > See: https://git.io/fxCyr
*
* The characters wrapped between two single quotes characters (') are escaped.
* Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
* (see the last example)
*
* Format of the string is based on Unicode Technical Standard #35:
* https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
* with a few additions (see note 7 below the table).
*
* Accepted patterns:
* | Unit | Pattern | Result examples | Notes |
* |---------------------------------|---------|-----------------------------------|-------|
* | Era | G..GGG | AD, BC | |
* | | GGGG | Anno Domini, Before Christ | 2 |
* | | GGGGG | A, B | |
* | Calendar year | y | 44, 1, 1900, 2017 | 5 |
* | | yo | 44th, 1st, 0th, 17th | 5,7 |
* | | yy | 44, 01, 00, 17 | 5 |
* | | yyy | 044, 001, 1900, 2017 | 5 |
* | | yyyy | 0044, 0001, 1900, 2017 | 5 |
* | | yyyyy | ... | 3,5 |
* | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |
* | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |
* | | YY | 44, 01, 00, 17 | 5,8 |
* | | YYY | 044, 001, 1900, 2017 | 5 |
* | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |
* | | YYYYY | ... | 3,5 |
* | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |
* | | RR | -43, 00, 01, 1900, 2017 | 5,7 |
* | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |
* | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |
* | | RRRRR | ... | 3,5,7 |
* | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |
* | | uu | -43, 01, 1900, 2017 | 5 |
* | | uuu | -043, 001, 1900, 2017 | 5 |
* | | uuuu | -0043, 0001, 1900, 2017 | 5 |
* | | uuuuu | ... | 3,5 |
* | Quarter (formatting) | Q | 1, 2, 3, 4 | |
* | | Qo | 1st, 2nd, 3rd, 4th | 7 |
* | | QQ | 01, 02, 03, 04 | |
* | | QQQ | Q1, Q2, Q3, Q4 | |
* | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
* | | QQQQQ | 1, 2, 3, 4 | 4 |
* | Quarter (stand-alone) | q | 1, 2, 3, 4 | |
* | | qo | 1st, 2nd, 3rd, 4th | 7 |
* | | qq | 01, 02, 03, 04 | |
* | | qqq | Q1, Q2, Q3, Q4 | |
* | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
* | | qqqqq | 1, 2, 3, 4 | 4 |
* | Month (formatting) | M | 1, 2, ..., 12 | |
* | | Mo | 1st, 2nd, ..., 12th | 7 |
* | | MM | 01, 02, ..., 12 | |
* | | MMM | Jan, Feb, ..., Dec | |
* | | MMMM | January, February, ..., December | 2 |
* | | MMMMM | J, F, ..., D | |
* | Month (stand-alone) | L | 1, 2, ..., 12 | |
* | | Lo | 1st, 2nd, ..., 12th | 7 |
* | | LL | 01, 02, ..., 12 | |
* | | LLL | Jan, Feb, ..., Dec | |
* | | LLLL | January, February, ..., December | 2 |
* | | LLLLL | J, F, ..., D | |
* | Local week of year | w | 1, 2, ..., 53 | |
* | | wo | 1st, 2nd, ..., 53th | 7 |
* | | ww | 01, 02, ..., 53 | |
* | ISO week of year | I | 1, 2, ..., 53 | 7 |
* | | Io | 1st, 2nd, ..., 53th | 7 |
* | | II | 01, 02, ..., 53 | 7 |
* | Day of month | d | 1, 2, ..., 31 | |
* | | do | 1st, 2nd, ..., 31st | 7 |
* | | dd | 01, 02, ..., 31 | |
* | Day of year | D | 1, 2, ..., 365, 366 | 8 |
* | | Do | 1st, 2nd, ..., 365th, 366th | 7 |
* | | DD | 01, 02, ..., 365, 366 | 8 |
* | | DDD | 001, 002, ..., 365, 366 | |
* | | DDDD | ... | 3 |
* | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Su | |
* | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
* | | EEEEE | M, T, W, T, F, S, S | |
* | | EEEEEE | Mo, Tu, We, Th, Fr, Su, Sa | |
* | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |
* | | io | 1st, 2nd, ..., 7th | 7 |
* | | ii | 01, 02, ..., 07 | 7 |
* | | iii | Mon, Tue, Wed, ..., Su | 7 |
* | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |
* | | iiiii | M, T, W, T, F, S, S | 7 |
* | | iiiiii | Mo, Tu, We, Th, Fr, Su, Sa | 7 |
* | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |
* | | eo | 2nd, 3rd, ..., 1st | 7 |
* | | ee | 02, 03, ..., 01 | |
* | | eee | Mon, Tue, Wed, ..., Su | |
* | | eeee | Monday, Tuesday, ..., Sunday | 2 |
* | | eeeee | M, T, W, T, F, S, S | |
* | | eeeeee | Mo, Tu, We, Th, Fr, Su, Sa | |
* | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |
* | | co | 2nd, 3rd, ..., 1st | 7 |
* | | cc | 02, 03, ..., 01 | |
* | | ccc | Mon, Tue, Wed, ..., Su | |
* | | cccc | Monday, Tuesday, ..., Sunday | 2 |
* | | ccccc | M, T, W, T, F, S, S | |
* | | cccccc | Mo, Tu, We, Th, Fr, Su, Sa | |
* | AM, PM | a..aaa | AM, PM | |
* | | aaaa | a.m., p.m. | 2 |
* | | aaaaa | a, p | |
* | AM, PM, noon, midnight | b..bbb | AM, PM, noon, midnight | |
* | | bbbb | a.m., p.m., noon, midnight | 2 |
* | | bbbbb | a, p, n, mi | |
* | Flexible day period | B..BBB | at night, in the morning, ... | |
* | | BBBB | at night, in the morning, ... | 2 |
* | | BBBBB | at night, in the morning, ... | |
* | Hour [1-12] | h | 1, 2, ..., 11, 12 | |
* | | ho | 1st, 2nd, ..., 11th, 12th | 7 |
* | | hh | 01, 02, ..., 11, 12 | |
* | Hour [0-23] | H | 0, 1, 2, ..., 23 | |
* | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |
* | | HH | 00, 01, 02, ..., 23 | |
* | Hour [0-11] | K | 1, 2, ..., 11, 0 | |
* | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |
* | | KK | 1, 2, ..., 11, 0 | |
* | Hour [1-24] | k | 24, 1, 2, ..., 23 | |
* | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |
* | | kk | 24, 01, 02, ..., 23 | |
* | Minute | m | 0, 1, ..., 59 | |
* | | mo | 0th, 1st, ..., 59th | 7 |
* | | mm | 00, 01, ..., 59 | |
* | Second | s | 0, 1, ..., 59 | |
* | | so | 0th, 1st, ..., 59th | 7 |
* | | ss | 00, 01, ..., 59 | |
* | Fraction of second | S | 0, 1, ..., 9 | |
* | | SS | 00, 01, ..., 99 | |
* | | SSS | 000, 0001, ..., 999 | |
* | | SSSS | ... | 3 |
* | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |
* | | XX | -0800, +0530, Z | |
* | | XXX | -08:00, +05:30, Z | |
* | | XXXX | -0800, +0530, Z, +123456 | 2 |
* | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
* | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |
* | | xx | -0800, +0530, +0000 | |
* | | xxx | -08:00, +05:30, +00:00 | 2 |
* | | xxxx | -0800, +0530, +0000, +123456 | |
* | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
* | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |
* | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |
* | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |
* | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |
* | Seconds timestamp | t | 512969520 | 7 |
* | | tt | ... | 3,7 |
* | Milliseconds timestamp | T | 512969520900 | 7 |
* | | TT | ... | 3,7 |
* | Long localized date | P | 05/29/1453 | 7 |
* | | PP | May 29, 1453 | 7 |
* | | PPP | May 29th, 1453 | 7 |
* | | PPPP | Sunday, May 29th, 1453 | 2,7 |
* | Long localized time | p | 12:00 AM | 7 |
* | | pp | 12:00:00 AM | 7 |
* | | ppp | 12:00:00 AM GMT+2 | 7 |
* | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |
* | Combination of date and time | Pp | 05/29/1453, 12:00 AM | 7 |
* | | PPpp | May 29, 1453, 12:00:00 AM | 7 |
* | | PPPppp | May 29th, 1453 at ... | 7 |
* | | PPPPpppp| Sunday, May 29th, 1453 at ... | 2,7 |
* Notes:
* 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
* are the same as "stand-alone" units, but are different in some languages.
* "Formatting" units are declined according to the rules of the language
* in the context of a date. "Stand-alone" units are always nominative singular:
*
* `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
*
* `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
*
* 2. Any sequence of the identical letters is a pattern, unless it is escaped by
* the single quote characters (see below).
* If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
* the output will be the same as default pattern for this unit, usually
* the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
* are marked with "2" in the last column of the table.
*
* `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
*
* `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
*
* `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
*
* `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
*
* `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
*
* 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
* The output will be padded with zeros to match the length of the pattern.
*
* `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
*
* 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
* These tokens represent the shortest form of the quarter.
*
* 5. The main difference between `y` and `u` patterns are B.C. years:
*
* | Year | `y` | `u` |
* |------|-----|-----|
* | AC 1 | 1 | 1 |
* | BC 1 | 1 | 0 |
* | BC 2 | 2 | -1 |
*
* Also `yy` always returns the last two digits of a year,
* while `uu` pads single digit years to 2 characters and returns other years unchanged:
*
* | Year | `yy` | `uu` |
* |------|------|------|
* | 1 | 01 | 01 |
* | 14 | 14 | 14 |
* | 376 | 76 | 376 |
* | 1453 | 53 | 1453 |
*
* The same difference is true for local and ISO week-numbering years (`Y` and `R`),
* except local week-numbering years are dependent on `options.weekStartsOn`
* and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear}
* and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}).
*
* 6. Specific non-location timezones are currently unavailable in `date-fns`,
* so right now these tokens fall back to GMT timezones.
*
* 7. These patterns are not in the Unicode Technical Standard #35:
* - `i`: ISO day of week
* - `I`: ISO week of year
* - `R`: ISO week-numbering year
* - `t`: seconds timestamp
* - `T`: milliseconds timestamp
* - `o`: ordinal number modifier
* - `P`: long localized date
* - `p`: long localized time
*
* 8. These tokens are often confused with others. See: https://git.io/fxCyr
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The second argument is now required for the sake of explicitness.
*
* ```javascript
* // Before v2.0.0
* format(new Date(2016, 0, 1))
*
* // v2.0.0 onward
* format(new Date(2016, 0, 1), "yyyy-MM-dd'T'HH:mm:ss.SSSxxx")
* ```
*
* - New format string API for `format` function
* which is based on [Unicode Technical Standard #35](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table).
* See [this post](https://blog.date-fns.org/post/unicode-tokens-in-date-fns-v2-sreatyki91jg) for more details.
*
* - Characters are now escaped using single quote symbols (`'`) instead of square brackets.
*
* @param {Date|Number} date - the original date
* @param {String} format - the string of tokens
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @param {Boolean} [options.awareOfUnicodeTokens=false] - if true, allows usage of Unicode tokens causes confusion:
* - Some of the day of year tokens (`D`, `DD`) that are confused with the day of month tokens (`d`, `dd`).
* - Some of the local week-numbering year tokens (`YY`, `YYYY`) that are confused with the calendar year tokens (`yy`, `yyyy`).
* See: https://git.io/fxCyr
* @returns {String} the formatted date string
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.locale` must contain `localize` property
* @throws {RangeError} `options.locale` must contain `formatLong` property
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
* @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
* @throws {RangeError} `options.awareOfUnicodeTokens` must be set to `true` to use `XX` token; see: https://git.io/fxCyr
*
* @example
* // Represent 11 February 2014 in middle-endian format:
* var result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
* //=> '02/11/2014'
*
* @example
* // Represent 2 July 2014 in Esperanto:
* import { eoLocale } from 'date-fns/locale/eo'
* var result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
* locale: eoLocale
* })
* //=> '2-a de julio 2014'
*
* @example
* // Escape string by single quote characters:
* var result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
* //=> "3 o'clock"
*/
function format(dirtyDate, dirtyFormatStr, dirtyOptions) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var formatStr = String(dirtyFormatStr);
var options = dirtyOptions || {};
var locale = options.locale || _locale_en_US_index_js__WEBPACK_IMPORTED_MODULE_4__["default"];
var localeFirstWeekContainsDate = locale.options && locale.options.firstWeekContainsDate;
var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeFirstWeekContainsDate);
var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.firstWeekContainsDate); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
}
var localeWeekStartsOn = locale.options && locale.options.weekStartsOn;
var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeWeekStartsOn);
var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
if (!locale.localize) {
throw new RangeError('locale must contain localize property');
}
if (!locale.formatLong) {
throw new RangeError('locale must contain formatLong property');
}
var originalDate = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dirtyDate);
if (!Object(_isValid_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(originalDate)) {
throw new RangeError('Invalid time value');
} // Convert the date in system timezone to the same date in UTC+00:00 timezone.
// This ensures that when UTC functions will be implemented, locales will be compatible with them.
// See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
var timezoneOffset = Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(originalDate);
var utcDate = Object(_subMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_7__["default"])(originalDate, timezoneOffset);
var formatterOptions = {
firstWeekContainsDate: firstWeekContainsDate,
weekStartsOn: weekStartsOn,
locale: locale,
_originalDate: originalDate
};
var result = formatStr.match(longFormattingTokensRegExp).map(function (substring) {
var firstCharacter = substring[0];
if (firstCharacter === 'p' || firstCharacter === 'P') {
var longFormatter = _lib_format_longFormatters_index_js__WEBPACK_IMPORTED_MODULE_6__["default"][firstCharacter];
return longFormatter(substring, locale.formatLong, formatterOptions);
}
return substring;
}).join('').match(formattingTokensRegExp).map(function (substring) {
// Replace two single quote characters with one single quote character
if (substring === "''") {
return "'";
}
var firstCharacter = substring[0];
if (firstCharacter === "'") {
return cleanEscapedString(substring);
}
var formatter = _lib_format_formatters_index_js__WEBPACK_IMPORTED_MODULE_5__["default"][firstCharacter];
if (formatter) {
if (!options.awareOfUnicodeTokens && Object(_lib_protectedTokens_index_js__WEBPACK_IMPORTED_MODULE_8__["isProtectedToken"])(substring)) {
Object(_lib_protectedTokens_index_js__WEBPACK_IMPORTED_MODULE_8__["throwProtectedError"])(substring);
}
return formatter(utcDate, substring, locale.localize, formatterOptions);
}
return substring;
}).join('');
return result;
}
function cleanEscapedString(input) {
return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'");
}
/***/ }),
/***/ "./node_modules/date-fns/esm/formatDistance/index.js":
/*!***********************************************************!*\
!*** ./node_modules/date-fns/esm/formatDistance/index.js ***!
\***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return formatDistance; });
/* harmony import */ var _lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/getTimezoneOffsetInMilliseconds/index.js */ "./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js");
/* harmony import */ var _compareAsc_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../compareAsc/index.js */ "./node_modules/date-fns/esm/compareAsc/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _differenceInSeconds_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../differenceInSeconds/index.js */ "./node_modules/date-fns/esm/differenceInSeconds/index.js");
/* harmony import */ var _differenceInMonths_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../differenceInMonths/index.js */ "./node_modules/date-fns/esm/differenceInMonths/index.js");
/* harmony import */ var _lib_cloneObject_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../_lib/cloneObject/index.js */ "./node_modules/date-fns/esm/_lib/cloneObject/index.js");
/* harmony import */ var _locale_en_US_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../locale/en-US/index.js */ "./node_modules/date-fns/esm/locale/en-US/index.js");
var MINUTES_IN_DAY = 1440;
var MINUTES_IN_ALMOST_TWO_DAYS = 2520;
var MINUTES_IN_MONTH = 43200;
var MINUTES_IN_TWO_MONTHS = 86400;
/**
* @name formatDistance
* @category Common Helpers
* @summary Return the distance between the given dates in words.
*
* @description
* Return the distance between the given dates in words.
*
* | Distance between dates | Result |
* |-------------------------------------------------------------------|---------------------|
* | 0 ... 30 secs | less than a minute |
* | 30 secs ... 1 min 30 secs | 1 minute |
* | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes |
* | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour |
* | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours |
* | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day |
* | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days |
* | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month |
* | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months |
* | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months |
* | 1 yr ... 1 yr 3 months | about 1 year |
* | 1 yr 3 months ... 1 yr 9 month s | over 1 year |
* | 1 yr 9 months ... 2 yrs | almost 2 years |
* | N yrs ... N yrs 3 months | about N years |
* | N yrs 3 months ... N yrs 9 months | over N years |
* | N yrs 9 months ... N+1 yrs | almost N+1 years |
*
* With `options.includeSeconds == true`:
* | Distance between dates | Result |
* |------------------------|----------------------|
* | 0 secs ... 5 secs | less than 5 seconds |
* | 5 secs ... 10 secs | less than 10 seconds |
* | 10 secs ... 20 secs | less than 20 seconds |
* | 20 secs ... 40 secs | half a minute |
* | 40 secs ... 60 secs | less than a minute |
* | 60 secs ... 90 secs | 1 minute |
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `distanceInWords ` to `formatDistance `
* to make its name consistent with `format` and `formatRelative`.
*
* - The order of arguments is swapped to make the function
* consistent with `differenceIn...` functions.
*
* ```javascript
* // Before v2.0.0
*
* distanceInWords(
* new Date(1986, 3, 4, 10, 32, 0),
* new Date(1986, 3, 4, 11, 32, 0),
* { addSuffix: true }
* ) //=> 'in about 1 hour'
*
* // v2.0.0 onward
*
* formatDistance(
* new Date(1986, 3, 4, 11, 32, 0),
* new Date(1986, 3, 4, 10, 32, 0),
* { addSuffix: true }
* ) //=> 'in about 1 hour'
* ```
*
* @param {Date|Number} date - the date
* @param {Date|Number} baseDate - the date to compare with
* @param {Object} [options] - an object with options.
* @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed
* @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {String} the distance in words
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.locale` must contain `formatDistance` property
*
* @example
* // What is the distance between 2 July 2014 and 1 January 2015?
* var result = formatDistance(new Date(2014, 6, 2), new Date(2015, 0, 1))
* //=> '6 months'
*
* @example
* // What is the distance between 1 January 2015 00:00:15
* // and 1 January 2015 00:00:00, including seconds?
* var result = formatDistance(
* new Date(2015, 0, 1, 0, 0, 15),
* new Date(2015, 0, 1, 0, 0, 0),
* { includeSeconds: true }
* )
* //=> 'less than 20 seconds'
*
* @example
* // What is the distance from 1 January 2016
* // to 1 January 2015, with a suffix?
* var result = formatDistance(new Date(2015, 0, 1), new Date(2016, 0, 1), {
* addSuffix: true
* })
* //=> 'about 1 year ago'
*
* @example
* // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto?
* import { eoLocale } from 'date-fns/locale/eo'
* var result = formatDistance(new Date(2016, 7, 1), new Date(2015, 0, 1), {
* locale: eoLocale
* })
* //=> 'pli ol 1 jaro'
*/
function formatDistance(dirtyDate, dirtyBaseDate, dirtyOptions) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var options = dirtyOptions || {};
var locale = options.locale || _locale_en_US_index_js__WEBPACK_IMPORTED_MODULE_6__["default"];
if (!locale.formatDistance) {
throw new RangeError('locale must contain formatDistance property');
}
var comparison = Object(_compareAsc_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, dirtyBaseDate);
if (isNaN(comparison)) {
throw new RangeError('Invalid time value');
}
var localizeOptions = Object(_lib_cloneObject_index_js__WEBPACK_IMPORTED_MODULE_5__["default"])(options);
localizeOptions.addSuffix = Boolean(options.addSuffix);
localizeOptions.comparison = comparison;
var dateLeft;
var dateRight;
if (comparison > 0) {
dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dirtyBaseDate);
dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dirtyDate);
} else {
dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dirtyDate);
dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dirtyBaseDate);
}
var seconds = Object(_differenceInSeconds_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(dateRight, dateLeft);
var offsetInSeconds = (Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dateRight) - Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dateLeft)) / 1000;
var minutes = Math.round((seconds - offsetInSeconds) / 60);
var months; // 0 up to 2 mins
if (minutes < 2) {
if (options.includeSeconds) {
if (seconds < 5) {
return locale.formatDistance('lessThanXSeconds', 5, localizeOptions);
} else if (seconds < 10) {
return locale.formatDistance('lessThanXSeconds', 10, localizeOptions);
} else if (seconds < 20) {
return locale.formatDistance('lessThanXSeconds', 20, localizeOptions);
} else if (seconds < 40) {
return locale.formatDistance('halfAMinute', null, localizeOptions);
} else if (seconds < 60) {
return locale.formatDistance('lessThanXMinutes', 1, localizeOptions);
} else {
return locale.formatDistance('xMinutes', 1, localizeOptions);
}
} else {
if (minutes === 0) {
return locale.formatDistance('lessThanXMinutes', 1, localizeOptions);
} else {
return locale.formatDistance('xMinutes', minutes, localizeOptions);
}
} // 2 mins up to 0.75 hrs
} else if (minutes < 45) {
return locale.formatDistance('xMinutes', minutes, localizeOptions); // 0.75 hrs up to 1.5 hrs
} else if (minutes < 90) {
return locale.formatDistance('aboutXHours', 1, localizeOptions); // 1.5 hrs up to 24 hrs
} else if (minutes < MINUTES_IN_DAY) {
var hours = Math.round(minutes / 60);
return locale.formatDistance('aboutXHours', hours, localizeOptions); // 1 day up to 1.75 days
} else if (minutes < MINUTES_IN_ALMOST_TWO_DAYS) {
return locale.formatDistance('xDays', 1, localizeOptions); // 1.75 days up to 30 days
} else if (minutes < MINUTES_IN_MONTH) {
var days = Math.round(minutes / MINUTES_IN_DAY);
return locale.formatDistance('xDays', days, localizeOptions); // 1 month up to 2 months
} else if (minutes < MINUTES_IN_TWO_MONTHS) {
months = Math.round(minutes / MINUTES_IN_MONTH);
return locale.formatDistance('aboutXMonths', months, localizeOptions);
}
months = Object(_differenceInMonths_index_js__WEBPACK_IMPORTED_MODULE_4__["default"])(dateRight, dateLeft); // 2 months up to 12 months
if (months < 12) {
var nearestMonth = Math.round(minutes / MINUTES_IN_MONTH);
return locale.formatDistance('xMonths', nearestMonth, localizeOptions); // 1 year up to max Date
} else {
var monthsSinceStartOfYear = months % 12;
var years = Math.floor(months / 12); // N years up to 1 years 3 months
if (monthsSinceStartOfYear < 3) {
return locale.formatDistance('aboutXYears', years, localizeOptions); // N years 3 months up to N years 9 months
} else if (monthsSinceStartOfYear < 9) {
return locale.formatDistance('overXYears', years, localizeOptions); // N years 9 months up to N year 12 months
} else {
return locale.formatDistance('almostXYears', years + 1, localizeOptions);
}
}
}
/***/ }),
/***/ "./node_modules/date-fns/esm/formatDistanceStrict/index.js":
/*!*****************************************************************!*\
!*** ./node_modules/date-fns/esm/formatDistanceStrict/index.js ***!
\*****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return formatDistanceStrict; });
/* harmony import */ var _lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/getTimezoneOffsetInMilliseconds/index.js */ "./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js");
/* harmony import */ var _compareAsc_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../compareAsc/index.js */ "./node_modules/date-fns/esm/compareAsc/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _differenceInSeconds_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../differenceInSeconds/index.js */ "./node_modules/date-fns/esm/differenceInSeconds/index.js");
/* harmony import */ var _lib_cloneObject_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../_lib/cloneObject/index.js */ "./node_modules/date-fns/esm/_lib/cloneObject/index.js");
/* harmony import */ var _locale_en_US_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../locale/en-US/index.js */ "./node_modules/date-fns/esm/locale/en-US/index.js");
var MINUTES_IN_DAY = 1440;
var MINUTES_IN_MONTH = 43200;
var MINUTES_IN_YEAR = 525600;
/**
* @name formatDistanceStrict
* @category Common Helpers
* @summary Return the distance between the given dates in words.
*
* @description
* Return the distance between the given dates in words, using strict units.
* This is like `formatDistance`, but does not use helpers like 'almost', 'over',
* 'less than' and the like.
*
* | Distance between dates | Result |
* |------------------------|---------------------|
* | 0 ... 59 secs | [0..59] seconds |
* | 1 ... 59 mins | [1..59] minutes |
* | 1 ... 23 hrs | [1..23] hours |
* | 1 ... 29 days | [1..29] days |
* | 1 ... 11 months | [1..11] months |
* | 1 ... N years | [1..N] years |
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `distanceInWordsStrict` to `formatDistanceStrict`
* to make its name consistent with `format` and `formatRelative`.
*
* - The order of arguments is swapped to make the function
* consistent with `differenceIn...` functions.
*
* ```javascript
* // Before v2.0.0
*
* distanceInWordsStrict(
* new Date(2015, 0, 2),
* new Date(2014, 6, 2)
* ) //=> '6 months'
*
* // v2.0.0 onward
*
* formatDistanceStrict(
* new Date(2014, 6, 2),
* new Date(2015, 0, 2)
* ) //=> '6 months'
* ```
*
* - `partialMethod` option is renamed to `roundingMethod`.
*
* ```javascript
* // Before v2.0.0
*
* distanceInWordsStrict(
* new Date(1986, 3, 4, 10, 32, 0),
* new Date(1986, 3, 4, 10, 33, 1),
* { partialMethod: 'ceil' }
* ) //=> '2 minutes'
*
* // v2.0.0 onward
*
* formatDistanceStrict(
* new Date(1986, 3, 4, 10, 33, 1),
* new Date(1986, 3, 4, 10, 32, 0),
* { roundingMethod: 'ceil' }
* ) //=> '2 minutes'
* ```
*
* - If `roundingMethod` is not specified, it now defaults to `round` instead of `floor`.
*
* - `unit` option now accepts one of the strings:
* 'second', 'minute', 'hour', 'day', 'month' or 'year' instead of 's', 'm', 'h', 'd', 'M' or 'Y'
*
* ```javascript
* // Before v2.0.0
*
* distanceInWordsStrict(
* new Date(1986, 3, 4, 10, 32, 0),
* new Date(1986, 3, 4, 10, 33, 1),
* { unit: 'm' }
* )
*
* // v2.0.0 onward
*
* formatDistanceStrict(
* new Date(1986, 3, 4, 10, 33, 1),
* new Date(1986, 3, 4, 10, 32, 0),
* { unit: 'minute' }
* )
* ```
*
* @param {Date|Number} date - the date
* @param {Date|Number} baseDate - the date to compare with
* @param {Object} [options] - an object with options.
* @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first
* @param {'second'|'minute'|'hour'|'day'|'month'|'year'} [options.unit] - if specified, will force a unit
* @param {'floor'|'ceil'|'round'} [options.roundingMethod='round'] - which way to round partial units
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {String} the distance in words
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.roundingMethod` must be 'floor', 'ceil' or 'round'
* @throws {RangeError} `options.unit` must be 'second', 'minute', 'hour', 'day', 'month' or 'year'
* @throws {RangeError} `options.locale` must contain `formatDistance` property
*
* @example
* // What is the distance between 2 July 2014 and 1 January 2015?
* var result = formatDistanceStrict(new Date(2014, 6, 2), new Date(2015, 0, 2))
* //=> '6 months'
*
* @example
* // What is the distance between 1 January 2015 00:00:15
* // and 1 January 2015 00:00:00?
* var result = formatDistanceStrict(
* new Date(2015, 0, 1, 0, 0, 15),
* new Date(2015, 0, 1, 0, 0, 0)
* )
* //=> '15 seconds'
*
* @example
* // What is the distance from 1 January 2016
* // to 1 January 2015, with a suffix?
* var result = formatDistanceStrict(new Date(2015, 0, 1), new Date(2016, 0, 1), {
* addSuffix: true
* })
* //=> '1 year ago'
*
* @example
* // What is the distance from 1 January 2016
* // to 1 January 2015, in minutes?
* var result = formatDistanceStrict(new Date(2016, 0, 1), new Date(2015, 0, 1), {
* unit: 'minute'
* })
* //=> '525600 minutes'
*
* @example
* // What is the distance from 1 January 2016
* // to 28 January 2015, in months, rounded up?
* var result = formatDistanceStrict(new Date(2015, 0, 28), new Date(2015, 0, 1), {
* unit: 'month',
* roundingMethod: 'ceil'
* })
* //=> '1 month'
*
* @example
* // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto?
* import { eoLocale } from 'date-fns/locale/eo'
* var result = formatDistanceStrict(new Date(2016, 7, 1), new Date(2015, 0, 1), {
* locale: eoLocale
* })
* //=> '1 jaro'
*/
function formatDistanceStrict(dirtyDate, dirtyBaseDate, dirtyOptions) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var options = dirtyOptions || {};
var locale = options.locale || _locale_en_US_index_js__WEBPACK_IMPORTED_MODULE_5__["default"];
if (!locale.formatDistance) {
throw new RangeError('locale must contain localize.formatDistance property');
}
var comparison = Object(_compareAsc_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, dirtyBaseDate);
if (isNaN(comparison)) {
throw new RangeError('Invalid time value');
}
var localizeOptions = Object(_lib_cloneObject_index_js__WEBPACK_IMPORTED_MODULE_4__["default"])(options);
localizeOptions.addSuffix = Boolean(options.addSuffix);
localizeOptions.comparison = comparison;
var dateLeft;
var dateRight;
if (comparison > 0) {
dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dirtyBaseDate);
dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dirtyDate);
} else {
dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dirtyDate);
dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dirtyBaseDate);
}
var roundingMethod = options.roundingMethod == null ? 'round' : String(options.roundingMethod);
var roundingMethodFn;
if (roundingMethod === 'floor') {
roundingMethodFn = Math.floor;
} else if (roundingMethod === 'ceil') {
roundingMethodFn = Math.ceil;
} else if (roundingMethod === 'round') {
roundingMethodFn = Math.round;
} else {
throw new RangeError("roundingMethod must be 'floor', 'ceil' or 'round'");
}
var seconds = Object(_differenceInSeconds_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(dateRight, dateLeft);
var offsetInSeconds = (Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dateRight) - Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dateLeft)) / 1000;
var minutes = roundingMethodFn((seconds - offsetInSeconds) / 60);
var unit;
if (options.unit == null) {
if (minutes < 1) {
unit = 'second';
} else if (minutes < 60) {
unit = 'minute';
} else if (minutes < MINUTES_IN_DAY) {
unit = 'hour';
} else if (minutes < MINUTES_IN_MONTH) {
unit = 'day';
} else if (minutes < MINUTES_IN_YEAR) {
unit = 'month';
} else {
unit = 'year';
}
} else {
unit = String(options.unit);
} // 0 up to 60 seconds
if (unit === 'second') {
return locale.formatDistance('xSeconds', seconds, localizeOptions); // 1 up to 60 mins
} else if (unit === 'minute') {
return locale.formatDistance('xMinutes', minutes, localizeOptions); // 1 up to 24 hours
} else if (unit === 'hour') {
var hours = roundingMethodFn(minutes / 60);
return locale.formatDistance('xHours', hours, localizeOptions); // 1 up to 30 days
} else if (unit === 'day') {
var days = roundingMethodFn(minutes / MINUTES_IN_DAY);
return locale.formatDistance('xDays', days, localizeOptions); // 1 up to 12 months
} else if (unit === 'month') {
var months = roundingMethodFn(minutes / MINUTES_IN_MONTH);
return locale.formatDistance('xMonths', months, localizeOptions); // 1 year up to max Date
} else if (unit === 'year') {
var years = roundingMethodFn(minutes / MINUTES_IN_YEAR);
return locale.formatDistance('xYears', years, localizeOptions);
}
throw new RangeError("unit must be 'second', 'minute', 'hour', 'day', 'month' or 'year'");
}
/***/ }),
/***/ "./node_modules/date-fns/esm/formatRelative/index.js":
/*!***********************************************************!*\
!*** ./node_modules/date-fns/esm/formatRelative/index.js ***!
\***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return formatRelative; });
/* harmony import */ var _lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/getTimezoneOffsetInMilliseconds/index.js */ "./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _format_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../format/index.js */ "./node_modules/date-fns/esm/format/index.js");
/* harmony import */ var _differenceInCalendarDays_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../differenceInCalendarDays/index.js */ "./node_modules/date-fns/esm/differenceInCalendarDays/index.js");
/* harmony import */ var _locale_en_US_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../locale/en-US/index.js */ "./node_modules/date-fns/esm/locale/en-US/index.js");
/* harmony import */ var _subMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../subMilliseconds/index.js */ "./node_modules/date-fns/esm/subMilliseconds/index.js");
/**
* @name formatRelative
* @category Common Helpers
* @summary Represent the date in words relative to the given base date.
*
* @description
* Represent the date in words relative to the given base date.
*
* | Distance to the base date | Result |
* |---------------------------|---------------------------|
* | Previous 6 days | last Sunday at 04:30 AM |
* | Last day | yesterday at 04:30 AM |
* | Same day | today at 04:30 AM |
* | Next day | tomorrow at 04:30 AM |
* | Next 6 days | Sunday at 04:30 AM |
* | Other | 12/31/2017 |
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to format
* @param {Date|Number} baseDate - the date to compare with
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {String} the date in words
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
* @throws {RangeError} `options.locale` must contain `localize` property
* @throws {RangeError} `options.locale` must contain `formatLong` property
* @throws {RangeError} `options.locale` must contain `formatRelative` property
*/
function formatRelative(dirtyDate, dirtyBaseDate, dirtyOptions) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var baseDate = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyBaseDate);
var options = dirtyOptions || {};
var locale = options.locale || _locale_en_US_index_js__WEBPACK_IMPORTED_MODULE_4__["default"];
if (!locale.localize) {
throw new RangeError('locale must contain localize property');
}
if (!locale.formatLong) {
throw new RangeError('locale must contain formatLong property');
}
if (!locale.formatRelative) {
throw new RangeError('locale must contain formatRelative property');
}
var diff = Object(_differenceInCalendarDays_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(date, baseDate);
if (isNaN(diff)) {
throw new RangeError('Invalid time value');
}
var token;
if (diff < -6) {
token = 'other';
} else if (diff < -1) {
token = 'lastWeek';
} else if (diff < 0) {
token = 'yesterday';
} else if (diff < 1) {
token = 'today';
} else if (diff < 2) {
token = 'tomorrow';
} else if (diff < 7) {
token = 'nextWeek';
} else {
token = 'other';
}
var utcDate = Object(_subMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_5__["default"])(date, Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(date));
var utcBaseDate = Object(_subMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_5__["default"])(baseDate, Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(baseDate));
var formatStr = locale.formatRelative(token, utcDate, utcBaseDate, options);
return Object(_format_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date, formatStr, options);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/fromUnixTime/index.js":
/*!*********************************************************!*\
!*** ./node_modules/date-fns/esm/fromUnixTime/index.js ***!
\*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return fromUnixTime; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/**
* @name fromUnixTime
* @category Timestamp Helpers
* @summary Create a date from a Unix timestamp.
*
* @description
* Create a date from a Unix timestamp.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Number} unixTime - the given Unix timestamp
* @returns {Date} the date
* @throws {TypeError} 1 argument required
*
* @example
* // Create the date 29 February 2012 11:45:05:
* var result = fromUnixTime(1330515905)
* //=> Wed Feb 29 2012 11:45:05
*/
function fromUnixTime(dirtyUnixTime) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var unixTime = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyUnixTime);
return Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(unixTime * 1000);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getDate/index.js":
/*!****************************************************!*\
!*** ./node_modules/date-fns/esm/getDate/index.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getDate; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name getDate
* @category Day Helpers
* @summary Get the day of the month of the given date.
*
* @description
* Get the day of the month of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the day of month
* @throws {TypeError} 1 argument required
*
* @example
* // Which day of the month is 29 February 2012?
* var result = getDate(new Date(2012, 1, 29))
* //=> 29
*/
function getDate(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var dayOfMonth = date.getDate();
return dayOfMonth;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getDay/index.js":
/*!***************************************************!*\
!*** ./node_modules/date-fns/esm/getDay/index.js ***!
\***************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getDay; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name getDay
* @category Weekday Helpers
* @summary Get the day of the week of the given date.
*
* @description
* Get the day of the week of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the day of week
* @throws {TypeError} 1 argument required
*
* @example
* // Which day of the week is 29 February 2012?
* var result = getDay(new Date(2012, 1, 29))
* //=> 3
*/
function getDay(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var day = date.getDay();
return day;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getDayOfYear/index.js":
/*!*********************************************************!*\
!*** ./node_modules/date-fns/esm/getDayOfYear/index.js ***!
\*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getDayOfYear; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _startOfYear_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfYear/index.js */ "./node_modules/date-fns/esm/startOfYear/index.js");
/* harmony import */ var _differenceInCalendarDays_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../differenceInCalendarDays/index.js */ "./node_modules/date-fns/esm/differenceInCalendarDays/index.js");
/**
* @name getDayOfYear
* @category Day Helpers
* @summary Get the day of the year of the given date.
*
* @description
* Get the day of the year of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the day of year
* @throws {TypeError} 1 argument required
*
* @example
* // Which day of the year is 2 July 2014?
* var result = getDayOfYear(new Date(2014, 6, 2))
* //=> 183
*/
function getDayOfYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var diff = Object(_differenceInCalendarDays_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date, Object(_startOfYear_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date));
var dayOfYear = diff + 1;
return dayOfYear;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getDaysInMonth/index.js":
/*!***********************************************************!*\
!*** ./node_modules/date-fns/esm/getDaysInMonth/index.js ***!
\***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getDaysInMonth; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name getDaysInMonth
* @category Month Helpers
* @summary Get the number of days in a month of the given date.
*
* @description
* Get the number of days in a month of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the number of days in a month
* @throws {TypeError} 1 argument required
*
* @example
* // How many days are in February 2000?
* var result = getDaysInMonth(new Date(2000, 1))
* //=> 29
*/
function getDaysInMonth(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var year = date.getFullYear();
var monthIndex = date.getMonth();
var lastDayOfMonth = new Date(0);
lastDayOfMonth.setFullYear(year, monthIndex + 1, 0);
lastDayOfMonth.setHours(0, 0, 0, 0);
return lastDayOfMonth.getDate();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getDaysInYear/index.js":
/*!**********************************************************!*\
!*** ./node_modules/date-fns/esm/getDaysInYear/index.js ***!
\**********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getDaysInYear; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _isLeapYear_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../isLeapYear/index.js */ "./node_modules/date-fns/esm/isLeapYear/index.js");
/**
* @name getDaysInYear
* @category Year Helpers
* @summary Get the number of days in a year of the given date.
*
* @description
* Get the number of days in a year of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the number of days in a year
* @throws {TypeError} 1 argument required
*
* @example
* // How many days are in 2012?
* var result = getDaysInYear(new Date(2012, 0, 1))
* //=> 366
*/
function getDaysInYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
if (isNaN(date)) {
return NaN;
}
return Object(_isLeapYear_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date) ? 366 : 365;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getDecade/index.js":
/*!******************************************************!*\
!*** ./node_modules/date-fns/esm/getDecade/index.js ***!
\******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getDecade; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name getDecade
* @category Decade Helpers
* @summary Get the decade of the given date.
*
* @description
* Get the decade of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the year of decade
* @throws {TypeError} 1 argument required
*
* @example
* // Which decade belongs 27 November 1942?
* var result = getDecade(new Date(1942, 10, 27))
* //=> 1940
*/
function getDecade(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var year = date.getFullYear();
var decade = Math.floor(year / 10) * 10;
return decade;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getHours/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/getHours/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getHours; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name getHours
* @category Hour Helpers
* @summary Get the hours of the given date.
*
* @description
* Get the hours of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the hours
* @throws {TypeError} 1 argument required
*
* @example
* // Get the hours of 29 February 2012 11:45:00:
* var result = getHours(new Date(2012, 1, 29, 11, 45))
* //=> 11
*/
function getHours(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var hours = date.getHours();
return hours;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getISODay/index.js":
/*!******************************************************!*\
!*** ./node_modules/date-fns/esm/getISODay/index.js ***!
\******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getISODay; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name getISODay
* @category Weekday Helpers
* @summary Get the day of the ISO week of the given date.
*
* @description
* Get the day of the ISO week of the given date,
* which is 7 for Sunday, 1 for Monday etc.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the day of ISO week
* @throws {TypeError} 1 argument required
*
* @example
* // Which day of the ISO week is 26 February 2012?
* var result = getISODay(new Date(2012, 1, 26))
* //=> 7
*/
function getISODay(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var day = date.getDay();
if (day === 0) {
day = 7;
}
return day;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getISOWeek/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/getISOWeek/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getISOWeek; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfISOWeek/index.js */ "./node_modules/date-fns/esm/startOfISOWeek/index.js");
/* harmony import */ var _startOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../startOfISOWeekYear/index.js */ "./node_modules/date-fns/esm/startOfISOWeekYear/index.js");
var MILLISECONDS_IN_WEEK = 604800000;
/**
* @name getISOWeek
* @category ISO Week Helpers
* @summary Get the ISO week of the given date.
*
* @description
* Get the ISO week of the given date.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the ISO week
* @throws {TypeError} 1 argument required
*
* @example
* // Which week of the ISO-week numbering year is 2 January 2005?
* var result = getISOWeek(new Date(2005, 0, 2))
* //=> 53
*/
function getISOWeek(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var diff = Object(_startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date).getTime() - Object(_startOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date).getTime(); // Round the number of days to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getISOWeekYear/index.js":
/*!***********************************************************!*\
!*** ./node_modules/date-fns/esm/getISOWeekYear/index.js ***!
\***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getISOWeekYear; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfISOWeek/index.js */ "./node_modules/date-fns/esm/startOfISOWeek/index.js");
/**
* @name getISOWeekYear
* @category ISO Week-Numbering Year Helpers
* @summary Get the ISO week-numbering year of the given date.
*
* @description
* Get the ISO week-numbering year of the given date,
* which always starts 3 days before the year's first Thursday.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `getISOYear` to `getISOWeekYear`.
* "ISO week year" is short for [ISO week-numbering year](https://en.wikipedia.org/wiki/ISO_week_date).
* This change makes the name consistent with
* locale-dependent week-numbering year helpers, e.g., `getWeekYear`.
*
* @param {Date|Number} date - the given date
* @returns {Number} the ISO week-numbering year
* @throws {TypeError} 1 argument required
*
* @example
* // Which ISO-week numbering year is 2 January 2005?
* var result = getISOWeekYear(new Date(2005, 0, 2))
* //=> 2004
*/
function getISOWeekYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var year = date.getFullYear();
var fourthOfJanuaryOfNextYear = new Date(0);
fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);
fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);
var startOfNextYear = Object(_startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(fourthOfJanuaryOfNextYear);
var fourthOfJanuaryOfThisYear = new Date(0);
fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);
fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);
var startOfThisYear = Object(_startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(fourthOfJanuaryOfThisYear);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getISOWeeksInYear/index.js":
/*!**************************************************************!*\
!*** ./node_modules/date-fns/esm/getISOWeeksInYear/index.js ***!
\**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getISOWeeksInYear; });
/* harmony import */ var _startOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../startOfISOWeekYear/index.js */ "./node_modules/date-fns/esm/startOfISOWeekYear/index.js");
/* harmony import */ var _addWeeks_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addWeeks/index.js */ "./node_modules/date-fns/esm/addWeeks/index.js");
var MILLISECONDS_IN_WEEK = 604800000;
/**
* @name getISOWeeksInYear
* @category ISO Week-Numbering Year Helpers
* @summary Get the number of weeks in an ISO week-numbering year of the given date.
*
* @description
* Get the number of weeks in an ISO week-numbering year of the given date.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the number of ISO weeks in a year
* @throws {TypeError} 1 argument required
*
* @example
* // How many weeks are in ISO week-numbering year 2015?
* var result = getISOWeeksInYear(new Date(2015, 1, 11))
* //=> 53
*/
function getISOWeeksInYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var thisYear = Object(_startOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var nextYear = Object(_startOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(Object(_addWeeks_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(thisYear, 60));
var diff = nextYear.valueOf() - thisYear.valueOf(); // Round the number of weeks to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round(diff / MILLISECONDS_IN_WEEK);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getMilliseconds/index.js":
/*!************************************************************!*\
!*** ./node_modules/date-fns/esm/getMilliseconds/index.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getMilliseconds; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name getMilliseconds
* @category Millisecond Helpers
* @summary Get the milliseconds of the given date.
*
* @description
* Get the milliseconds of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the milliseconds
* @throws {TypeError} 1 argument required
*
* @example
* // Get the milliseconds of 29 February 2012 11:45:05.123:
* var result = getMilliseconds(new Date(2012, 1, 29, 11, 45, 5, 123))
* //=> 123
*/
function getMilliseconds(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var milliseconds = date.getMilliseconds();
return milliseconds;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getMinutes/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/getMinutes/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getMinutes; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name getMinutes
* @category Minute Helpers
* @summary Get the minutes of the given date.
*
* @description
* Get the minutes of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the minutes
* @throws {TypeError} 1 argument required
*
* @example
* // Get the minutes of 29 February 2012 11:45:05:
* var result = getMinutes(new Date(2012, 1, 29, 11, 45, 5))
* //=> 45
*/
function getMinutes(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var minutes = date.getMinutes();
return minutes;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getMonth/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/getMonth/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getMonth; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name getMonth
* @category Month Helpers
* @summary Get the month of the given date.
*
* @description
* Get the month of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the month
* @throws {TypeError} 1 argument required
*
* @example
* // Which month is 29 February 2012?
* var result = getMonth(new Date(2012, 1, 29))
* //=> 1
*/
function getMonth(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var month = date.getMonth();
return month;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getOverlappingDaysInIntervals/index.js":
/*!**************************************************************************!*\
!*** ./node_modules/date-fns/esm/getOverlappingDaysInIntervals/index.js ***!
\**************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getOverlappingDaysInIntervals; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
var MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000;
/**
* @name getOverlappingDaysInIntervals
* @category Interval Helpers
* @summary Get the number of days that overlap in two time intervals
*
* @description
* Get the number of days that overlap in two time intervals
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `getOverlappingDaysInRanges` to `getOverlappingDaysInIntervals`.
* This change was made to mirror the use of the word "interval" in standard ISO 8601:2004 terminology:
*
* ```
* 2.1.3
* time interval
* part of the time axis limited by two instants
* ```
*
* Also, this function now accepts an object with `start` and `end` properties
* instead of two arguments as an interval.
* This function now throws `RangeError` if the start of the interval is after its end
* or if any date in the interval is `Invalid Date`.
*
* ```javascript
* // Before v2.0.0
*
* getOverlappingDaysInRanges(
* new Date(2014, 0, 10), new Date(2014, 0, 20),
* new Date(2014, 0, 17), new Date(2014, 0, 21)
* )
*
* // v2.0.0 onward
*
* getOverlappingDaysInIntervals(
* { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
* { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }
* )
* ```
*
* @param {Interval} intervalLeft - the first interval to compare. See [Interval]{@link docs/Interval}
* @param {Interval} intervalRight - the second interval to compare. See [Interval]{@link docs/Interval}
* @returns {Number} the number of days that overlap in two time intervals
* @throws {TypeError} 2 arguments required
* @throws {RangeError} The start of an interval cannot be after its end
* @throws {RangeError} Date in interval cannot be `Invalid Date`
*
* @example
* // For overlapping time intervals adds 1 for each started overlapping day:
* getOverlappingDaysInIntervals(
* { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
* { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }
* )
* //=> 3
*
* @example
* // For non-overlapping time intervals returns 0:
* getOverlappingDaysInIntervals(
* { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
* { start: new Date(2014, 0, 21), end: new Date(2014, 0, 22) }
* )
* //=> 0
*/
function getOverlappingDaysInIntervals(dirtyIntervalLeft, dirtyIntervalRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var intervalLeft = dirtyIntervalLeft || {};
var intervalRight = dirtyIntervalRight || {};
var leftStartTime = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(intervalLeft.start).getTime();
var leftEndTime = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(intervalLeft.end).getTime();
var rightStartTime = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(intervalRight.start).getTime();
var rightEndTime = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(intervalRight.end).getTime(); // Throw an exception if start date is after end date or if any date is `Invalid Date`
if (!(leftStartTime <= leftEndTime && rightStartTime <= rightEndTime)) {
throw new RangeError('Invalid interval');
}
var isOverlapping = leftStartTime < rightEndTime && rightStartTime < leftEndTime;
if (!isOverlapping) {
return 0;
}
var overlapStartDate = rightStartTime < leftStartTime ? leftStartTime : rightStartTime;
var overlapEndDate = rightEndTime > leftEndTime ? leftEndTime : rightEndTime;
var differenceInMs = overlapEndDate - overlapStartDate;
return Math.ceil(differenceInMs / MILLISECONDS_IN_DAY);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getQuarter/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/getQuarter/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getQuarter; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name getQuarter
* @category Quarter Helpers
* @summary Get the year quarter of the given date.
*
* @description
* Get the year quarter of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the quarter
* @throws {TypeError} 1 argument required
*
* @example
* // Which quarter is 2 July 2014?
* var result = getQuarter(new Date(2014, 6, 2))
* //=> 3
*/
function getQuarter(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var quarter = Math.floor(date.getMonth() / 3) + 1;
return quarter;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getSeconds/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/getSeconds/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getSeconds; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name getSeconds
* @category Second Helpers
* @summary Get the seconds of the given date.
*
* @description
* Get the seconds of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the seconds
* @throws {TypeError} 1 argument required
*
* @example
* // Get the seconds of 29 February 2012 11:45:05.123:
* var result = getSeconds(new Date(2012, 1, 29, 11, 45, 5, 123))
* //=> 5
*/
function getSeconds(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var seconds = date.getSeconds();
return seconds;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getTime/index.js":
/*!****************************************************!*\
!*** ./node_modules/date-fns/esm/getTime/index.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getTime; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name getTime
* @category Timestamp Helpers
* @summary Get the milliseconds timestamp of the given date.
*
* @description
* Get the milliseconds timestamp of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the timestamp
* @throws {TypeError} 1 argument required
*
* @example
* // Get the timestamp of 29 February 2012 11:45:05.123:
* var result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123))
* //=> 1330515905123
*/
function getTime(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var timestamp = date.getTime();
return timestamp;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getUnixTime/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/getUnixTime/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getUnixTime; });
/* harmony import */ var _getTime_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../getTime/index.js */ "./node_modules/date-fns/esm/getTime/index.js");
/**
* @name getUnixTime
* @category Timestamp Helpers
* @summary Get the seconds timestamp of the given date.
*
* @description
* Get the seconds timestamp of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the timestamp
* @throws {TypeError} 1 argument required
*
* @example
* // Get the timestamp of 29 February 2012 11:45:05 CET:
* var result = getUnixTime(new Date(2012, 1, 29, 11, 45, 5))
* //=> 1330512305
*/
function getUnixTime(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return Math.floor(Object(_getTime_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate) / 1000);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getWeek/index.js":
/*!****************************************************!*\
!*** ./node_modules/date-fns/esm/getWeek/index.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getWeek; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfWeek/index.js */ "./node_modules/date-fns/esm/startOfWeek/index.js");
/* harmony import */ var _startOfWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../startOfWeekYear/index.js */ "./node_modules/date-fns/esm/startOfWeekYear/index.js");
var MILLISECONDS_IN_WEEK = 604800000;
/**
* @name getWeek
* @category Week Helpers
* @summary Get the local week index of the given date.
*
* @description
* Get the local week index of the given date.
* The exact calculation depends on the values of
* `options.weekStartsOn` (which is the index of the first day of the week)
* and `options.firstWeekContainsDate` (which is the day of January, which is always in
* the first week of the week-numbering year)
*
* Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year
* @returns {Number} the week
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
* @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
*
* @example
* // Which week of the local week numbering year is 2 January 2005 with default options?
* var result = getISOWeek(new Date(2005, 0, 2))
* //=> 2
*
* // Which week of the local week numbering year is 2 January 2005,
* // if Monday is the first day of the week,
* // and the first week of the year always contains 4 January?
* var result = getISOWeek(new Date(2005, 0, 2), {
* weekStartsOn: 1,
* firstWeekContainsDate: 4
* })
* //=> 53
*/
function getWeek(dirtyDate, options) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var diff = Object(_startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date, options).getTime() - Object(_startOfWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date, options).getTime(); // Round the number of days to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getWeekOfMonth/index.js":
/*!***********************************************************!*\
!*** ./node_modules/date-fns/esm/getWeekOfMonth/index.js ***!
\***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getWeekOfMonth; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _getDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../getDate/index.js */ "./node_modules/date-fns/esm/getDate/index.js");
/* harmony import */ var _startOfMonth_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../startOfMonth/index.js */ "./node_modules/date-fns/esm/startOfMonth/index.js");
/* harmony import */ var _getDay_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../getDay/index.js */ "./node_modules/date-fns/esm/getDay/index.js");
/**
* @name getWeekOfMonth
* @category Week Helpers
* @summary Get the week of the month of the given date.
*
* @description
* Get the week of the month of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @returns {Number} the week of month
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // Which week of the month is 9 November 2017?
* var result = getWeekOfMonth(new Date(2017, 10, 9))
* //=> 2
*/
function getWeekOfMonth(date, dirtyOptions) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var options = dirtyOptions || {};
var locale = options.locale;
var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeWeekStartsOn);
var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var startWeekDay = Object(_getDay_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(Object(_startOfMonth_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date));
var currentWeekDay = Object(_getDay_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(date);
var startWeekDayWithOptions = startWeekDay < weekStartsOn ? 7 - weekStartsOn : startWeekDay;
var diff = startWeekDayWithOptions > currentWeekDay ? 7 - weekStartsOn : 0;
return Math.ceil((Object(_getDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date) + diff) / 7);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getWeekYear/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/getWeekYear/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getWeekYear; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../startOfWeek/index.js */ "./node_modules/date-fns/esm/startOfWeek/index.js");
/**
* @name getWeekYear
* @category Week-Numbering Year Helpers
* @summary Get the local week-numbering year of the given date.
*
* @description
* Get the local week-numbering year of the given date.
* The exact calculation depends on the values of
* `options.weekStartsOn` (which is the index of the first day of the week)
* and `options.firstWeekContainsDate` (which is the day of January, which is always in
* the first week of the week-numbering year)
*
* Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year
* @returns {Number} the local week-numbering year
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
* @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
*
* @example
* // Which week numbering year is 26 December 2004 with the default settings?
* var result = getWeekYear(new Date(2004, 11, 26))
* //=> 2005
*
* @example
* // Which week numbering year is 26 December 2004 if week starts on Saturday?
* var result = getWeekYear(new Date(2004, 11, 26), { weekStartsOn: 6 })
* //=> 2004
*
* @example
* // Which week numbering year is 26 December 2004 if the first week contains 4 January?
* var result = getWeekYear(new Date(2004, 11, 26), { firstWeekContainsDate: 4 })
* //=> 2004
*/
function getWeekYear(dirtyDate, dirtyOptions) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var year = date.getFullYear();
var options = dirtyOptions || {};
var locale = options.locale;
var localeFirstWeekContainsDate = locale && locale.options && locale.options.firstWeekContainsDate;
var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeFirstWeekContainsDate);
var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.firstWeekContainsDate); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
}
var firstWeekOfNextYear = new Date(0);
firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);
firstWeekOfNextYear.setHours(0, 0, 0, 0);
var startOfNextYear = Object(_startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(firstWeekOfNextYear, dirtyOptions);
var firstWeekOfThisYear = new Date(0);
firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);
firstWeekOfThisYear.setHours(0, 0, 0, 0);
var startOfThisYear = Object(_startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(firstWeekOfThisYear, dirtyOptions);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getWeeksInMonth/index.js":
/*!************************************************************!*\
!*** ./node_modules/date-fns/esm/getWeeksInMonth/index.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getWeeksInMonth; });
/* harmony import */ var _differenceInCalendarWeeks_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../differenceInCalendarWeeks/index.js */ "./node_modules/date-fns/esm/differenceInCalendarWeeks/index.js");
/* harmony import */ var _lastDayOfMonth_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../lastDayOfMonth/index.js */ "./node_modules/date-fns/esm/lastDayOfMonth/index.js");
/* harmony import */ var _startOfMonth_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../startOfMonth/index.js */ "./node_modules/date-fns/esm/startOfMonth/index.js");
/**
* @name getWeeksInMonth
* @category Week Helpers
* @summary Get the number of calendar weeks a month spans.
*
* @description
* Get the number of calendar weeks the month in the given date spans.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {Number} the number of calendar weeks
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // How many calendar weeks does February 2015 span?
* var result = getWeeksInMonth(new Date(2015, 1, 8))
* //=> 4
*
* @example
* // If the week starts on Monday,
* // how many calendar weeks does July 2017 span?
* var result = getWeeksInMonth(new Date(2017, 6, 5), { weekStartsOn: 1 })
* //=> 6
*/
function getWeeksInMonth(date, options) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return Object(_differenceInCalendarWeeks_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(Object(_lastDayOfMonth_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date), Object(_startOfMonth_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date), options) + 1;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/getYear/index.js":
/*!****************************************************!*\
!*** ./node_modules/date-fns/esm/getYear/index.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getYear; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name getYear
* @category Year Helpers
* @summary Get the year of the given date.
*
* @description
* Get the year of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the year
* @throws {TypeError} 1 argument required
*
* @example
* // Which year is 2 July 2014?
* var result = getYear(new Date(2014, 6, 2))
* //=> 2014
*/
function getYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var year = date.getFullYear();
return year;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/index.js":
/*!********************************************!*\
!*** ./node_modules/date-fns/esm/index.js ***!
\********************************************/
/*! exports provided: addDays, addHours, addISOWeekYears, addMilliseconds, addMinutes, addMonths, addQuarters, addSeconds, addWeeks, addYears, areIntervalsOverlapping, closestIndexTo, closestTo, compareAsc, compareDesc, differenceInCalendarDays, differenceInCalendarISOWeekYears, differenceInCalendarISOWeeks, differenceInCalendarMonths, differenceInCalendarQuarters, differenceInCalendarWeeks, differenceInCalendarYears, differenceInDays, differenceInHours, differenceInISOWeekYears, differenceInMilliseconds, differenceInMinutes, differenceInMonths, differenceInQuarters, differenceInSeconds, differenceInWeeks, differenceInYears, eachDayOfInterval, eachWeekOfInterval, eachWeekendOfInterval, eachWeekendOfMonth, eachWeekendOfYear, endOfDay, endOfDecade, endOfHour, endOfISOWeek, endOfISOWeekYear, endOfMinute, endOfMonth, endOfQuarter, endOfSecond, endOfWeek, endOfYear, format, formatDistance, formatDistanceStrict, formatRelative, fromUnixTime, getDate, getDay, getDayOfYear, getDaysInMonth, getDaysInYear, getDecade, getHours, getISODay, getISOWeek, getISOWeekYear, getISOWeeksInYear, getMilliseconds, getMinutes, getMonth, getOverlappingDaysInIntervals, getQuarter, getSeconds, getTime, getUnixTime, getWeek, getWeekOfMonth, getWeekYear, getWeeksInMonth, getYear, isAfter, isBefore, isDate, isEqual, isFirstDayOfMonth, isFriday, isLastDayOfMonth, isLeapYear, isMonday, isSameDay, isSameHour, isSameISOWeek, isSameISOWeekYear, isSameMinute, isSameMonth, isSameQuarter, isSameSecond, isSameWeek, isSameYear, isSaturday, isSunday, isThursday, isTuesday, isValid, isWednesday, isWeekend, isWithinInterval, lastDayOfDecade, lastDayOfISOWeek, lastDayOfISOWeekYear, lastDayOfMonth, lastDayOfQuarter, lastDayOfWeek, lastDayOfYear, lightFormat, max, min, parse, parseISO, roundToNearestMinutes, setDate, setDay, setDayOfYear, setHours, setISODay, setISOWeek, setISOWeekYear, setMilliseconds, setMinutes, setMonth, setQuarter, setSeconds, setWeek, setWeekYear, setYear, startOfDay, startOfDecade, startOfHour, startOfISOWeek, startOfISOWeekYear, startOfMinute, startOfMonth, startOfQuarter, startOfSecond, startOfWeek, startOfWeekYear, startOfYear, subDays, subHours, subISOWeekYears, subMilliseconds, subMinutes, subMonths, subQuarters, subSeconds, subWeeks, subYears, toDate */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _addDays_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./addDays/index.js */ "./node_modules/date-fns/esm/addDays/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addDays", function() { return _addDays_index_js__WEBPACK_IMPORTED_MODULE_0__["default"]; });
/* harmony import */ var _addHours_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./addHours/index.js */ "./node_modules/date-fns/esm/addHours/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addHours", function() { return _addHours_index_js__WEBPACK_IMPORTED_MODULE_1__["default"]; });
/* harmony import */ var _addISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./addISOWeekYears/index.js */ "./node_modules/date-fns/esm/addISOWeekYears/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addISOWeekYears", function() { return _addISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_2__["default"]; });
/* harmony import */ var _addMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./addMilliseconds/index.js */ "./node_modules/date-fns/esm/addMilliseconds/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addMilliseconds", function() { return _addMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_3__["default"]; });
/* harmony import */ var _addMinutes_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./addMinutes/index.js */ "./node_modules/date-fns/esm/addMinutes/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addMinutes", function() { return _addMinutes_index_js__WEBPACK_IMPORTED_MODULE_4__["default"]; });
/* harmony import */ var _addMonths_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./addMonths/index.js */ "./node_modules/date-fns/esm/addMonths/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addMonths", function() { return _addMonths_index_js__WEBPACK_IMPORTED_MODULE_5__["default"]; });
/* harmony import */ var _addQuarters_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./addQuarters/index.js */ "./node_modules/date-fns/esm/addQuarters/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addQuarters", function() { return _addQuarters_index_js__WEBPACK_IMPORTED_MODULE_6__["default"]; });
/* harmony import */ var _addSeconds_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./addSeconds/index.js */ "./node_modules/date-fns/esm/addSeconds/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addSeconds", function() { return _addSeconds_index_js__WEBPACK_IMPORTED_MODULE_7__["default"]; });
/* harmony import */ var _addWeeks_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./addWeeks/index.js */ "./node_modules/date-fns/esm/addWeeks/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addWeeks", function() { return _addWeeks_index_js__WEBPACK_IMPORTED_MODULE_8__["default"]; });
/* harmony import */ var _addYears_index_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./addYears/index.js */ "./node_modules/date-fns/esm/addYears/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addYears", function() { return _addYears_index_js__WEBPACK_IMPORTED_MODULE_9__["default"]; });
/* harmony import */ var _areIntervalsOverlapping_index_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./areIntervalsOverlapping/index.js */ "./node_modules/date-fns/esm/areIntervalsOverlapping/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "areIntervalsOverlapping", function() { return _areIntervalsOverlapping_index_js__WEBPACK_IMPORTED_MODULE_10__["default"]; });
/* harmony import */ var _closestIndexTo_index_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./closestIndexTo/index.js */ "./node_modules/date-fns/esm/closestIndexTo/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "closestIndexTo", function() { return _closestIndexTo_index_js__WEBPACK_IMPORTED_MODULE_11__["default"]; });
/* harmony import */ var _closestTo_index_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./closestTo/index.js */ "./node_modules/date-fns/esm/closestTo/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "closestTo", function() { return _closestTo_index_js__WEBPACK_IMPORTED_MODULE_12__["default"]; });
/* harmony import */ var _compareAsc_index_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./compareAsc/index.js */ "./node_modules/date-fns/esm/compareAsc/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "compareAsc", function() { return _compareAsc_index_js__WEBPACK_IMPORTED_MODULE_13__["default"]; });
/* harmony import */ var _compareDesc_index_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./compareDesc/index.js */ "./node_modules/date-fns/esm/compareDesc/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "compareDesc", function() { return _compareDesc_index_js__WEBPACK_IMPORTED_MODULE_14__["default"]; });
/* harmony import */ var _differenceInCalendarDays_index_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./differenceInCalendarDays/index.js */ "./node_modules/date-fns/esm/differenceInCalendarDays/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInCalendarDays", function() { return _differenceInCalendarDays_index_js__WEBPACK_IMPORTED_MODULE_15__["default"]; });
/* harmony import */ var _differenceInCalendarISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./differenceInCalendarISOWeekYears/index.js */ "./node_modules/date-fns/esm/differenceInCalendarISOWeekYears/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInCalendarISOWeekYears", function() { return _differenceInCalendarISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_16__["default"]; });
/* harmony import */ var _differenceInCalendarISOWeeks_index_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./differenceInCalendarISOWeeks/index.js */ "./node_modules/date-fns/esm/differenceInCalendarISOWeeks/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInCalendarISOWeeks", function() { return _differenceInCalendarISOWeeks_index_js__WEBPACK_IMPORTED_MODULE_17__["default"]; });
/* harmony import */ var _differenceInCalendarMonths_index_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./differenceInCalendarMonths/index.js */ "./node_modules/date-fns/esm/differenceInCalendarMonths/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInCalendarMonths", function() { return _differenceInCalendarMonths_index_js__WEBPACK_IMPORTED_MODULE_18__["default"]; });
/* harmony import */ var _differenceInCalendarQuarters_index_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./differenceInCalendarQuarters/index.js */ "./node_modules/date-fns/esm/differenceInCalendarQuarters/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInCalendarQuarters", function() { return _differenceInCalendarQuarters_index_js__WEBPACK_IMPORTED_MODULE_19__["default"]; });
/* harmony import */ var _differenceInCalendarWeeks_index_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./differenceInCalendarWeeks/index.js */ "./node_modules/date-fns/esm/differenceInCalendarWeeks/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInCalendarWeeks", function() { return _differenceInCalendarWeeks_index_js__WEBPACK_IMPORTED_MODULE_20__["default"]; });
/* harmony import */ var _differenceInCalendarYears_index_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./differenceInCalendarYears/index.js */ "./node_modules/date-fns/esm/differenceInCalendarYears/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInCalendarYears", function() { return _differenceInCalendarYears_index_js__WEBPACK_IMPORTED_MODULE_21__["default"]; });
/* harmony import */ var _differenceInDays_index_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./differenceInDays/index.js */ "./node_modules/date-fns/esm/differenceInDays/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInDays", function() { return _differenceInDays_index_js__WEBPACK_IMPORTED_MODULE_22__["default"]; });
/* harmony import */ var _differenceInHours_index_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./differenceInHours/index.js */ "./node_modules/date-fns/esm/differenceInHours/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInHours", function() { return _differenceInHours_index_js__WEBPACK_IMPORTED_MODULE_23__["default"]; });
/* harmony import */ var _differenceInISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./differenceInISOWeekYears/index.js */ "./node_modules/date-fns/esm/differenceInISOWeekYears/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInISOWeekYears", function() { return _differenceInISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_24__["default"]; });
/* harmony import */ var _differenceInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./differenceInMilliseconds/index.js */ "./node_modules/date-fns/esm/differenceInMilliseconds/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInMilliseconds", function() { return _differenceInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_25__["default"]; });
/* harmony import */ var _differenceInMinutes_index_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./differenceInMinutes/index.js */ "./node_modules/date-fns/esm/differenceInMinutes/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInMinutes", function() { return _differenceInMinutes_index_js__WEBPACK_IMPORTED_MODULE_26__["default"]; });
/* harmony import */ var _differenceInMonths_index_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./differenceInMonths/index.js */ "./node_modules/date-fns/esm/differenceInMonths/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInMonths", function() { return _differenceInMonths_index_js__WEBPACK_IMPORTED_MODULE_27__["default"]; });
/* harmony import */ var _differenceInQuarters_index_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./differenceInQuarters/index.js */ "./node_modules/date-fns/esm/differenceInQuarters/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInQuarters", function() { return _differenceInQuarters_index_js__WEBPACK_IMPORTED_MODULE_28__["default"]; });
/* harmony import */ var _differenceInSeconds_index_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./differenceInSeconds/index.js */ "./node_modules/date-fns/esm/differenceInSeconds/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInSeconds", function() { return _differenceInSeconds_index_js__WEBPACK_IMPORTED_MODULE_29__["default"]; });
/* harmony import */ var _differenceInWeeks_index_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./differenceInWeeks/index.js */ "./node_modules/date-fns/esm/differenceInWeeks/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInWeeks", function() { return _differenceInWeeks_index_js__WEBPACK_IMPORTED_MODULE_30__["default"]; });
/* harmony import */ var _differenceInYears_index_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./differenceInYears/index.js */ "./node_modules/date-fns/esm/differenceInYears/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "differenceInYears", function() { return _differenceInYears_index_js__WEBPACK_IMPORTED_MODULE_31__["default"]; });
/* harmony import */ var _eachDayOfInterval_index_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./eachDayOfInterval/index.js */ "./node_modules/date-fns/esm/eachDayOfInterval/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "eachDayOfInterval", function() { return _eachDayOfInterval_index_js__WEBPACK_IMPORTED_MODULE_32__["default"]; });
/* harmony import */ var _eachWeekOfInterval_index_js__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./eachWeekOfInterval/index.js */ "./node_modules/date-fns/esm/eachWeekOfInterval/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "eachWeekOfInterval", function() { return _eachWeekOfInterval_index_js__WEBPACK_IMPORTED_MODULE_33__["default"]; });
/* harmony import */ var _eachWeekendOfInterval_index_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./eachWeekendOfInterval/index.js */ "./node_modules/date-fns/esm/eachWeekendOfInterval/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "eachWeekendOfInterval", function() { return _eachWeekendOfInterval_index_js__WEBPACK_IMPORTED_MODULE_34__["default"]; });
/* harmony import */ var _eachWeekendOfMonth_index_js__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./eachWeekendOfMonth/index.js */ "./node_modules/date-fns/esm/eachWeekendOfMonth/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "eachWeekendOfMonth", function() { return _eachWeekendOfMonth_index_js__WEBPACK_IMPORTED_MODULE_35__["default"]; });
/* harmony import */ var _eachWeekendOfYear_index_js__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./eachWeekendOfYear/index.js */ "./node_modules/date-fns/esm/eachWeekendOfYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "eachWeekendOfYear", function() { return _eachWeekendOfYear_index_js__WEBPACK_IMPORTED_MODULE_36__["default"]; });
/* harmony import */ var _endOfDay_index_js__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./endOfDay/index.js */ "./node_modules/date-fns/esm/endOfDay/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endOfDay", function() { return _endOfDay_index_js__WEBPACK_IMPORTED_MODULE_37__["default"]; });
/* harmony import */ var _endOfDecade_index_js__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./endOfDecade/index.js */ "./node_modules/date-fns/esm/endOfDecade/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endOfDecade", function() { return _endOfDecade_index_js__WEBPACK_IMPORTED_MODULE_38__["default"]; });
/* harmony import */ var _endOfHour_index_js__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./endOfHour/index.js */ "./node_modules/date-fns/esm/endOfHour/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endOfHour", function() { return _endOfHour_index_js__WEBPACK_IMPORTED_MODULE_39__["default"]; });
/* harmony import */ var _endOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./endOfISOWeek/index.js */ "./node_modules/date-fns/esm/endOfISOWeek/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endOfISOWeek", function() { return _endOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_40__["default"]; });
/* harmony import */ var _endOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ./endOfISOWeekYear/index.js */ "./node_modules/date-fns/esm/endOfISOWeekYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endOfISOWeekYear", function() { return _endOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_41__["default"]; });
/* harmony import */ var _endOfMinute_index_js__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ./endOfMinute/index.js */ "./node_modules/date-fns/esm/endOfMinute/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endOfMinute", function() { return _endOfMinute_index_js__WEBPACK_IMPORTED_MODULE_42__["default"]; });
/* harmony import */ var _endOfMonth_index_js__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./endOfMonth/index.js */ "./node_modules/date-fns/esm/endOfMonth/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endOfMonth", function() { return _endOfMonth_index_js__WEBPACK_IMPORTED_MODULE_43__["default"]; });
/* harmony import */ var _endOfQuarter_index_js__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ./endOfQuarter/index.js */ "./node_modules/date-fns/esm/endOfQuarter/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endOfQuarter", function() { return _endOfQuarter_index_js__WEBPACK_IMPORTED_MODULE_44__["default"]; });
/* harmony import */ var _endOfSecond_index_js__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ./endOfSecond/index.js */ "./node_modules/date-fns/esm/endOfSecond/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endOfSecond", function() { return _endOfSecond_index_js__WEBPACK_IMPORTED_MODULE_45__["default"]; });
/* harmony import */ var _endOfWeek_index_js__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ./endOfWeek/index.js */ "./node_modules/date-fns/esm/endOfWeek/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endOfWeek", function() { return _endOfWeek_index_js__WEBPACK_IMPORTED_MODULE_46__["default"]; });
/* harmony import */ var _endOfYear_index_js__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ./endOfYear/index.js */ "./node_modules/date-fns/esm/endOfYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endOfYear", function() { return _endOfYear_index_js__WEBPACK_IMPORTED_MODULE_47__["default"]; });
/* harmony import */ var _format_index_js__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ./format/index.js */ "./node_modules/date-fns/esm/format/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "format", function() { return _format_index_js__WEBPACK_IMPORTED_MODULE_48__["default"]; });
/* harmony import */ var _formatDistance_index_js__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! ./formatDistance/index.js */ "./node_modules/date-fns/esm/formatDistance/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "formatDistance", function() { return _formatDistance_index_js__WEBPACK_IMPORTED_MODULE_49__["default"]; });
/* harmony import */ var _formatDistanceStrict_index_js__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(/*! ./formatDistanceStrict/index.js */ "./node_modules/date-fns/esm/formatDistanceStrict/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "formatDistanceStrict", function() { return _formatDistanceStrict_index_js__WEBPACK_IMPORTED_MODULE_50__["default"]; });
/* harmony import */ var _formatRelative_index_js__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(/*! ./formatRelative/index.js */ "./node_modules/date-fns/esm/formatRelative/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "formatRelative", function() { return _formatRelative_index_js__WEBPACK_IMPORTED_MODULE_51__["default"]; });
/* harmony import */ var _fromUnixTime_index_js__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(/*! ./fromUnixTime/index.js */ "./node_modules/date-fns/esm/fromUnixTime/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromUnixTime", function() { return _fromUnixTime_index_js__WEBPACK_IMPORTED_MODULE_52__["default"]; });
/* harmony import */ var _getDate_index_js__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(/*! ./getDate/index.js */ "./node_modules/date-fns/esm/getDate/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDate", function() { return _getDate_index_js__WEBPACK_IMPORTED_MODULE_53__["default"]; });
/* harmony import */ var _getDay_index_js__WEBPACK_IMPORTED_MODULE_54__ = __webpack_require__(/*! ./getDay/index.js */ "./node_modules/date-fns/esm/getDay/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDay", function() { return _getDay_index_js__WEBPACK_IMPORTED_MODULE_54__["default"]; });
/* harmony import */ var _getDayOfYear_index_js__WEBPACK_IMPORTED_MODULE_55__ = __webpack_require__(/*! ./getDayOfYear/index.js */ "./node_modules/date-fns/esm/getDayOfYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDayOfYear", function() { return _getDayOfYear_index_js__WEBPACK_IMPORTED_MODULE_55__["default"]; });
/* harmony import */ var _getDaysInMonth_index_js__WEBPACK_IMPORTED_MODULE_56__ = __webpack_require__(/*! ./getDaysInMonth/index.js */ "./node_modules/date-fns/esm/getDaysInMonth/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDaysInMonth", function() { return _getDaysInMonth_index_js__WEBPACK_IMPORTED_MODULE_56__["default"]; });
/* harmony import */ var _getDaysInYear_index_js__WEBPACK_IMPORTED_MODULE_57__ = __webpack_require__(/*! ./getDaysInYear/index.js */ "./node_modules/date-fns/esm/getDaysInYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDaysInYear", function() { return _getDaysInYear_index_js__WEBPACK_IMPORTED_MODULE_57__["default"]; });
/* harmony import */ var _getDecade_index_js__WEBPACK_IMPORTED_MODULE_58__ = __webpack_require__(/*! ./getDecade/index.js */ "./node_modules/date-fns/esm/getDecade/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDecade", function() { return _getDecade_index_js__WEBPACK_IMPORTED_MODULE_58__["default"]; });
/* harmony import */ var _getHours_index_js__WEBPACK_IMPORTED_MODULE_59__ = __webpack_require__(/*! ./getHours/index.js */ "./node_modules/date-fns/esm/getHours/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getHours", function() { return _getHours_index_js__WEBPACK_IMPORTED_MODULE_59__["default"]; });
/* harmony import */ var _getISODay_index_js__WEBPACK_IMPORTED_MODULE_60__ = __webpack_require__(/*! ./getISODay/index.js */ "./node_modules/date-fns/esm/getISODay/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getISODay", function() { return _getISODay_index_js__WEBPACK_IMPORTED_MODULE_60__["default"]; });
/* harmony import */ var _getISOWeek_index_js__WEBPACK_IMPORTED_MODULE_61__ = __webpack_require__(/*! ./getISOWeek/index.js */ "./node_modules/date-fns/esm/getISOWeek/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getISOWeek", function() { return _getISOWeek_index_js__WEBPACK_IMPORTED_MODULE_61__["default"]; });
/* harmony import */ var _getISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_62__ = __webpack_require__(/*! ./getISOWeekYear/index.js */ "./node_modules/date-fns/esm/getISOWeekYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getISOWeekYear", function() { return _getISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_62__["default"]; });
/* harmony import */ var _getISOWeeksInYear_index_js__WEBPACK_IMPORTED_MODULE_63__ = __webpack_require__(/*! ./getISOWeeksInYear/index.js */ "./node_modules/date-fns/esm/getISOWeeksInYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getISOWeeksInYear", function() { return _getISOWeeksInYear_index_js__WEBPACK_IMPORTED_MODULE_63__["default"]; });
/* harmony import */ var _getMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_64__ = __webpack_require__(/*! ./getMilliseconds/index.js */ "./node_modules/date-fns/esm/getMilliseconds/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getMilliseconds", function() { return _getMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_64__["default"]; });
/* harmony import */ var _getMinutes_index_js__WEBPACK_IMPORTED_MODULE_65__ = __webpack_require__(/*! ./getMinutes/index.js */ "./node_modules/date-fns/esm/getMinutes/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getMinutes", function() { return _getMinutes_index_js__WEBPACK_IMPORTED_MODULE_65__["default"]; });
/* harmony import */ var _getMonth_index_js__WEBPACK_IMPORTED_MODULE_66__ = __webpack_require__(/*! ./getMonth/index.js */ "./node_modules/date-fns/esm/getMonth/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getMonth", function() { return _getMonth_index_js__WEBPACK_IMPORTED_MODULE_66__["default"]; });
/* harmony import */ var _getOverlappingDaysInIntervals_index_js__WEBPACK_IMPORTED_MODULE_67__ = __webpack_require__(/*! ./getOverlappingDaysInIntervals/index.js */ "./node_modules/date-fns/esm/getOverlappingDaysInIntervals/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getOverlappingDaysInIntervals", function() { return _getOverlappingDaysInIntervals_index_js__WEBPACK_IMPORTED_MODULE_67__["default"]; });
/* harmony import */ var _getQuarter_index_js__WEBPACK_IMPORTED_MODULE_68__ = __webpack_require__(/*! ./getQuarter/index.js */ "./node_modules/date-fns/esm/getQuarter/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getQuarter", function() { return _getQuarter_index_js__WEBPACK_IMPORTED_MODULE_68__["default"]; });
/* harmony import */ var _getSeconds_index_js__WEBPACK_IMPORTED_MODULE_69__ = __webpack_require__(/*! ./getSeconds/index.js */ "./node_modules/date-fns/esm/getSeconds/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getSeconds", function() { return _getSeconds_index_js__WEBPACK_IMPORTED_MODULE_69__["default"]; });
/* harmony import */ var _getTime_index_js__WEBPACK_IMPORTED_MODULE_70__ = __webpack_require__(/*! ./getTime/index.js */ "./node_modules/date-fns/esm/getTime/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getTime", function() { return _getTime_index_js__WEBPACK_IMPORTED_MODULE_70__["default"]; });
/* harmony import */ var _getUnixTime_index_js__WEBPACK_IMPORTED_MODULE_71__ = __webpack_require__(/*! ./getUnixTime/index.js */ "./node_modules/date-fns/esm/getUnixTime/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getUnixTime", function() { return _getUnixTime_index_js__WEBPACK_IMPORTED_MODULE_71__["default"]; });
/* harmony import */ var _getWeek_index_js__WEBPACK_IMPORTED_MODULE_72__ = __webpack_require__(/*! ./getWeek/index.js */ "./node_modules/date-fns/esm/getWeek/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getWeek", function() { return _getWeek_index_js__WEBPACK_IMPORTED_MODULE_72__["default"]; });
/* harmony import */ var _getWeekOfMonth_index_js__WEBPACK_IMPORTED_MODULE_73__ = __webpack_require__(/*! ./getWeekOfMonth/index.js */ "./node_modules/date-fns/esm/getWeekOfMonth/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getWeekOfMonth", function() { return _getWeekOfMonth_index_js__WEBPACK_IMPORTED_MODULE_73__["default"]; });
/* harmony import */ var _getWeekYear_index_js__WEBPACK_IMPORTED_MODULE_74__ = __webpack_require__(/*! ./getWeekYear/index.js */ "./node_modules/date-fns/esm/getWeekYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getWeekYear", function() { return _getWeekYear_index_js__WEBPACK_IMPORTED_MODULE_74__["default"]; });
/* harmony import */ var _getWeeksInMonth_index_js__WEBPACK_IMPORTED_MODULE_75__ = __webpack_require__(/*! ./getWeeksInMonth/index.js */ "./node_modules/date-fns/esm/getWeeksInMonth/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getWeeksInMonth", function() { return _getWeeksInMonth_index_js__WEBPACK_IMPORTED_MODULE_75__["default"]; });
/* harmony import */ var _getYear_index_js__WEBPACK_IMPORTED_MODULE_76__ = __webpack_require__(/*! ./getYear/index.js */ "./node_modules/date-fns/esm/getYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getYear", function() { return _getYear_index_js__WEBPACK_IMPORTED_MODULE_76__["default"]; });
/* harmony import */ var _isAfter_index_js__WEBPACK_IMPORTED_MODULE_77__ = __webpack_require__(/*! ./isAfter/index.js */ "./node_modules/date-fns/esm/isAfter/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isAfter", function() { return _isAfter_index_js__WEBPACK_IMPORTED_MODULE_77__["default"]; });
/* harmony import */ var _isBefore_index_js__WEBPACK_IMPORTED_MODULE_78__ = __webpack_require__(/*! ./isBefore/index.js */ "./node_modules/date-fns/esm/isBefore/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isBefore", function() { return _isBefore_index_js__WEBPACK_IMPORTED_MODULE_78__["default"]; });
/* harmony import */ var _isDate_index_js__WEBPACK_IMPORTED_MODULE_79__ = __webpack_require__(/*! ./isDate/index.js */ "./node_modules/date-fns/esm/isDate/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isDate", function() { return _isDate_index_js__WEBPACK_IMPORTED_MODULE_79__["default"]; });
/* harmony import */ var _isEqual_index_js__WEBPACK_IMPORTED_MODULE_80__ = __webpack_require__(/*! ./isEqual/index.js */ "./node_modules/date-fns/esm/isEqual/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isEqual", function() { return _isEqual_index_js__WEBPACK_IMPORTED_MODULE_80__["default"]; });
/* harmony import */ var _isFirstDayOfMonth_index_js__WEBPACK_IMPORTED_MODULE_81__ = __webpack_require__(/*! ./isFirstDayOfMonth/index.js */ "./node_modules/date-fns/esm/isFirstDayOfMonth/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isFirstDayOfMonth", function() { return _isFirstDayOfMonth_index_js__WEBPACK_IMPORTED_MODULE_81__["default"]; });
/* harmony import */ var _isFriday_index_js__WEBPACK_IMPORTED_MODULE_82__ = __webpack_require__(/*! ./isFriday/index.js */ "./node_modules/date-fns/esm/isFriday/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isFriday", function() { return _isFriday_index_js__WEBPACK_IMPORTED_MODULE_82__["default"]; });
/* harmony import */ var _isLastDayOfMonth_index_js__WEBPACK_IMPORTED_MODULE_83__ = __webpack_require__(/*! ./isLastDayOfMonth/index.js */ "./node_modules/date-fns/esm/isLastDayOfMonth/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isLastDayOfMonth", function() { return _isLastDayOfMonth_index_js__WEBPACK_IMPORTED_MODULE_83__["default"]; });
/* harmony import */ var _isLeapYear_index_js__WEBPACK_IMPORTED_MODULE_84__ = __webpack_require__(/*! ./isLeapYear/index.js */ "./node_modules/date-fns/esm/isLeapYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isLeapYear", function() { return _isLeapYear_index_js__WEBPACK_IMPORTED_MODULE_84__["default"]; });
/* harmony import */ var _isMonday_index_js__WEBPACK_IMPORTED_MODULE_85__ = __webpack_require__(/*! ./isMonday/index.js */ "./node_modules/date-fns/esm/isMonday/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isMonday", function() { return _isMonday_index_js__WEBPACK_IMPORTED_MODULE_85__["default"]; });
/* harmony import */ var _isSameDay_index_js__WEBPACK_IMPORTED_MODULE_86__ = __webpack_require__(/*! ./isSameDay/index.js */ "./node_modules/date-fns/esm/isSameDay/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSameDay", function() { return _isSameDay_index_js__WEBPACK_IMPORTED_MODULE_86__["default"]; });
/* harmony import */ var _isSameHour_index_js__WEBPACK_IMPORTED_MODULE_87__ = __webpack_require__(/*! ./isSameHour/index.js */ "./node_modules/date-fns/esm/isSameHour/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSameHour", function() { return _isSameHour_index_js__WEBPACK_IMPORTED_MODULE_87__["default"]; });
/* harmony import */ var _isSameISOWeek_index_js__WEBPACK_IMPORTED_MODULE_88__ = __webpack_require__(/*! ./isSameISOWeek/index.js */ "./node_modules/date-fns/esm/isSameISOWeek/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSameISOWeek", function() { return _isSameISOWeek_index_js__WEBPACK_IMPORTED_MODULE_88__["default"]; });
/* harmony import */ var _isSameISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_89__ = __webpack_require__(/*! ./isSameISOWeekYear/index.js */ "./node_modules/date-fns/esm/isSameISOWeekYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSameISOWeekYear", function() { return _isSameISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_89__["default"]; });
/* harmony import */ var _isSameMinute_index_js__WEBPACK_IMPORTED_MODULE_90__ = __webpack_require__(/*! ./isSameMinute/index.js */ "./node_modules/date-fns/esm/isSameMinute/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSameMinute", function() { return _isSameMinute_index_js__WEBPACK_IMPORTED_MODULE_90__["default"]; });
/* harmony import */ var _isSameMonth_index_js__WEBPACK_IMPORTED_MODULE_91__ = __webpack_require__(/*! ./isSameMonth/index.js */ "./node_modules/date-fns/esm/isSameMonth/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSameMonth", function() { return _isSameMonth_index_js__WEBPACK_IMPORTED_MODULE_91__["default"]; });
/* harmony import */ var _isSameQuarter_index_js__WEBPACK_IMPORTED_MODULE_92__ = __webpack_require__(/*! ./isSameQuarter/index.js */ "./node_modules/date-fns/esm/isSameQuarter/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSameQuarter", function() { return _isSameQuarter_index_js__WEBPACK_IMPORTED_MODULE_92__["default"]; });
/* harmony import */ var _isSameSecond_index_js__WEBPACK_IMPORTED_MODULE_93__ = __webpack_require__(/*! ./isSameSecond/index.js */ "./node_modules/date-fns/esm/isSameSecond/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSameSecond", function() { return _isSameSecond_index_js__WEBPACK_IMPORTED_MODULE_93__["default"]; });
/* harmony import */ var _isSameWeek_index_js__WEBPACK_IMPORTED_MODULE_94__ = __webpack_require__(/*! ./isSameWeek/index.js */ "./node_modules/date-fns/esm/isSameWeek/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSameWeek", function() { return _isSameWeek_index_js__WEBPACK_IMPORTED_MODULE_94__["default"]; });
/* harmony import */ var _isSameYear_index_js__WEBPACK_IMPORTED_MODULE_95__ = __webpack_require__(/*! ./isSameYear/index.js */ "./node_modules/date-fns/esm/isSameYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSameYear", function() { return _isSameYear_index_js__WEBPACK_IMPORTED_MODULE_95__["default"]; });
/* harmony import */ var _isSaturday_index_js__WEBPACK_IMPORTED_MODULE_96__ = __webpack_require__(/*! ./isSaturday/index.js */ "./node_modules/date-fns/esm/isSaturday/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSaturday", function() { return _isSaturday_index_js__WEBPACK_IMPORTED_MODULE_96__["default"]; });
/* harmony import */ var _isSunday_index_js__WEBPACK_IMPORTED_MODULE_97__ = __webpack_require__(/*! ./isSunday/index.js */ "./node_modules/date-fns/esm/isSunday/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSunday", function() { return _isSunday_index_js__WEBPACK_IMPORTED_MODULE_97__["default"]; });
/* harmony import */ var _isThursday_index_js__WEBPACK_IMPORTED_MODULE_98__ = __webpack_require__(/*! ./isThursday/index.js */ "./node_modules/date-fns/esm/isThursday/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isThursday", function() { return _isThursday_index_js__WEBPACK_IMPORTED_MODULE_98__["default"]; });
/* harmony import */ var _isTuesday_index_js__WEBPACK_IMPORTED_MODULE_99__ = __webpack_require__(/*! ./isTuesday/index.js */ "./node_modules/date-fns/esm/isTuesday/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isTuesday", function() { return _isTuesday_index_js__WEBPACK_IMPORTED_MODULE_99__["default"]; });
/* harmony import */ var _isValid_index_js__WEBPACK_IMPORTED_MODULE_100__ = __webpack_require__(/*! ./isValid/index.js */ "./node_modules/date-fns/esm/isValid/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isValid", function() { return _isValid_index_js__WEBPACK_IMPORTED_MODULE_100__["default"]; });
/* harmony import */ var _isWednesday_index_js__WEBPACK_IMPORTED_MODULE_101__ = __webpack_require__(/*! ./isWednesday/index.js */ "./node_modules/date-fns/esm/isWednesday/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isWednesday", function() { return _isWednesday_index_js__WEBPACK_IMPORTED_MODULE_101__["default"]; });
/* harmony import */ var _isWeekend_index_js__WEBPACK_IMPORTED_MODULE_102__ = __webpack_require__(/*! ./isWeekend/index.js */ "./node_modules/date-fns/esm/isWeekend/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isWeekend", function() { return _isWeekend_index_js__WEBPACK_IMPORTED_MODULE_102__["default"]; });
/* harmony import */ var _isWithinInterval_index_js__WEBPACK_IMPORTED_MODULE_103__ = __webpack_require__(/*! ./isWithinInterval/index.js */ "./node_modules/date-fns/esm/isWithinInterval/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isWithinInterval", function() { return _isWithinInterval_index_js__WEBPACK_IMPORTED_MODULE_103__["default"]; });
/* harmony import */ var _lastDayOfDecade_index_js__WEBPACK_IMPORTED_MODULE_104__ = __webpack_require__(/*! ./lastDayOfDecade/index.js */ "./node_modules/date-fns/esm/lastDayOfDecade/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "lastDayOfDecade", function() { return _lastDayOfDecade_index_js__WEBPACK_IMPORTED_MODULE_104__["default"]; });
/* harmony import */ var _lastDayOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_105__ = __webpack_require__(/*! ./lastDayOfISOWeek/index.js */ "./node_modules/date-fns/esm/lastDayOfISOWeek/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "lastDayOfISOWeek", function() { return _lastDayOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_105__["default"]; });
/* harmony import */ var _lastDayOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_106__ = __webpack_require__(/*! ./lastDayOfISOWeekYear/index.js */ "./node_modules/date-fns/esm/lastDayOfISOWeekYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "lastDayOfISOWeekYear", function() { return _lastDayOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_106__["default"]; });
/* harmony import */ var _lastDayOfMonth_index_js__WEBPACK_IMPORTED_MODULE_107__ = __webpack_require__(/*! ./lastDayOfMonth/index.js */ "./node_modules/date-fns/esm/lastDayOfMonth/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "lastDayOfMonth", function() { return _lastDayOfMonth_index_js__WEBPACK_IMPORTED_MODULE_107__["default"]; });
/* harmony import */ var _lastDayOfQuarter_index_js__WEBPACK_IMPORTED_MODULE_108__ = __webpack_require__(/*! ./lastDayOfQuarter/index.js */ "./node_modules/date-fns/esm/lastDayOfQuarter/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "lastDayOfQuarter", function() { return _lastDayOfQuarter_index_js__WEBPACK_IMPORTED_MODULE_108__["default"]; });
/* harmony import */ var _lastDayOfWeek_index_js__WEBPACK_IMPORTED_MODULE_109__ = __webpack_require__(/*! ./lastDayOfWeek/index.js */ "./node_modules/date-fns/esm/lastDayOfWeek/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "lastDayOfWeek", function() { return _lastDayOfWeek_index_js__WEBPACK_IMPORTED_MODULE_109__["default"]; });
/* harmony import */ var _lastDayOfYear_index_js__WEBPACK_IMPORTED_MODULE_110__ = __webpack_require__(/*! ./lastDayOfYear/index.js */ "./node_modules/date-fns/esm/lastDayOfYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "lastDayOfYear", function() { return _lastDayOfYear_index_js__WEBPACK_IMPORTED_MODULE_110__["default"]; });
/* harmony import */ var _lightFormat_index_js__WEBPACK_IMPORTED_MODULE_111__ = __webpack_require__(/*! ./lightFormat/index.js */ "./node_modules/date-fns/esm/lightFormat/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "lightFormat", function() { return _lightFormat_index_js__WEBPACK_IMPORTED_MODULE_111__["default"]; });
/* harmony import */ var _max_index_js__WEBPACK_IMPORTED_MODULE_112__ = __webpack_require__(/*! ./max/index.js */ "./node_modules/date-fns/esm/max/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "max", function() { return _max_index_js__WEBPACK_IMPORTED_MODULE_112__["default"]; });
/* harmony import */ var _min_index_js__WEBPACK_IMPORTED_MODULE_113__ = __webpack_require__(/*! ./min/index.js */ "./node_modules/date-fns/esm/min/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "min", function() { return _min_index_js__WEBPACK_IMPORTED_MODULE_113__["default"]; });
/* harmony import */ var _parse_index_js__WEBPACK_IMPORTED_MODULE_114__ = __webpack_require__(/*! ./parse/index.js */ "./node_modules/date-fns/esm/parse/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return _parse_index_js__WEBPACK_IMPORTED_MODULE_114__["default"]; });
/* harmony import */ var _parseISO_index_js__WEBPACK_IMPORTED_MODULE_115__ = __webpack_require__(/*! ./parseISO/index.js */ "./node_modules/date-fns/esm/parseISO/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "parseISO", function() { return _parseISO_index_js__WEBPACK_IMPORTED_MODULE_115__["default"]; });
/* harmony import */ var _roundToNearestMinutes_index_js__WEBPACK_IMPORTED_MODULE_116__ = __webpack_require__(/*! ./roundToNearestMinutes/index.js */ "./node_modules/date-fns/esm/roundToNearestMinutes/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "roundToNearestMinutes", function() { return _roundToNearestMinutes_index_js__WEBPACK_IMPORTED_MODULE_116__["default"]; });
/* harmony import */ var _setDate_index_js__WEBPACK_IMPORTED_MODULE_117__ = __webpack_require__(/*! ./setDate/index.js */ "./node_modules/date-fns/esm/setDate/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setDate", function() { return _setDate_index_js__WEBPACK_IMPORTED_MODULE_117__["default"]; });
/* harmony import */ var _setDay_index_js__WEBPACK_IMPORTED_MODULE_118__ = __webpack_require__(/*! ./setDay/index.js */ "./node_modules/date-fns/esm/setDay/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setDay", function() { return _setDay_index_js__WEBPACK_IMPORTED_MODULE_118__["default"]; });
/* harmony import */ var _setDayOfYear_index_js__WEBPACK_IMPORTED_MODULE_119__ = __webpack_require__(/*! ./setDayOfYear/index.js */ "./node_modules/date-fns/esm/setDayOfYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setDayOfYear", function() { return _setDayOfYear_index_js__WEBPACK_IMPORTED_MODULE_119__["default"]; });
/* harmony import */ var _setHours_index_js__WEBPACK_IMPORTED_MODULE_120__ = __webpack_require__(/*! ./setHours/index.js */ "./node_modules/date-fns/esm/setHours/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setHours", function() { return _setHours_index_js__WEBPACK_IMPORTED_MODULE_120__["default"]; });
/* harmony import */ var _setISODay_index_js__WEBPACK_IMPORTED_MODULE_121__ = __webpack_require__(/*! ./setISODay/index.js */ "./node_modules/date-fns/esm/setISODay/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setISODay", function() { return _setISODay_index_js__WEBPACK_IMPORTED_MODULE_121__["default"]; });
/* harmony import */ var _setISOWeek_index_js__WEBPACK_IMPORTED_MODULE_122__ = __webpack_require__(/*! ./setISOWeek/index.js */ "./node_modules/date-fns/esm/setISOWeek/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setISOWeek", function() { return _setISOWeek_index_js__WEBPACK_IMPORTED_MODULE_122__["default"]; });
/* harmony import */ var _setISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_123__ = __webpack_require__(/*! ./setISOWeekYear/index.js */ "./node_modules/date-fns/esm/setISOWeekYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setISOWeekYear", function() { return _setISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_123__["default"]; });
/* harmony import */ var _setMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_124__ = __webpack_require__(/*! ./setMilliseconds/index.js */ "./node_modules/date-fns/esm/setMilliseconds/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setMilliseconds", function() { return _setMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_124__["default"]; });
/* harmony import */ var _setMinutes_index_js__WEBPACK_IMPORTED_MODULE_125__ = __webpack_require__(/*! ./setMinutes/index.js */ "./node_modules/date-fns/esm/setMinutes/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setMinutes", function() { return _setMinutes_index_js__WEBPACK_IMPORTED_MODULE_125__["default"]; });
/* harmony import */ var _setMonth_index_js__WEBPACK_IMPORTED_MODULE_126__ = __webpack_require__(/*! ./setMonth/index.js */ "./node_modules/date-fns/esm/setMonth/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setMonth", function() { return _setMonth_index_js__WEBPACK_IMPORTED_MODULE_126__["default"]; });
/* harmony import */ var _setQuarter_index_js__WEBPACK_IMPORTED_MODULE_127__ = __webpack_require__(/*! ./setQuarter/index.js */ "./node_modules/date-fns/esm/setQuarter/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setQuarter", function() { return _setQuarter_index_js__WEBPACK_IMPORTED_MODULE_127__["default"]; });
/* harmony import */ var _setSeconds_index_js__WEBPACK_IMPORTED_MODULE_128__ = __webpack_require__(/*! ./setSeconds/index.js */ "./node_modules/date-fns/esm/setSeconds/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setSeconds", function() { return _setSeconds_index_js__WEBPACK_IMPORTED_MODULE_128__["default"]; });
/* harmony import */ var _setWeek_index_js__WEBPACK_IMPORTED_MODULE_129__ = __webpack_require__(/*! ./setWeek/index.js */ "./node_modules/date-fns/esm/setWeek/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setWeek", function() { return _setWeek_index_js__WEBPACK_IMPORTED_MODULE_129__["default"]; });
/* harmony import */ var _setWeekYear_index_js__WEBPACK_IMPORTED_MODULE_130__ = __webpack_require__(/*! ./setWeekYear/index.js */ "./node_modules/date-fns/esm/setWeekYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setWeekYear", function() { return _setWeekYear_index_js__WEBPACK_IMPORTED_MODULE_130__["default"]; });
/* harmony import */ var _setYear_index_js__WEBPACK_IMPORTED_MODULE_131__ = __webpack_require__(/*! ./setYear/index.js */ "./node_modules/date-fns/esm/setYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setYear", function() { return _setYear_index_js__WEBPACK_IMPORTED_MODULE_131__["default"]; });
/* harmony import */ var _startOfDay_index_js__WEBPACK_IMPORTED_MODULE_132__ = __webpack_require__(/*! ./startOfDay/index.js */ "./node_modules/date-fns/esm/startOfDay/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startOfDay", function() { return _startOfDay_index_js__WEBPACK_IMPORTED_MODULE_132__["default"]; });
/* harmony import */ var _startOfDecade_index_js__WEBPACK_IMPORTED_MODULE_133__ = __webpack_require__(/*! ./startOfDecade/index.js */ "./node_modules/date-fns/esm/startOfDecade/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startOfDecade", function() { return _startOfDecade_index_js__WEBPACK_IMPORTED_MODULE_133__["default"]; });
/* harmony import */ var _startOfHour_index_js__WEBPACK_IMPORTED_MODULE_134__ = __webpack_require__(/*! ./startOfHour/index.js */ "./node_modules/date-fns/esm/startOfHour/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startOfHour", function() { return _startOfHour_index_js__WEBPACK_IMPORTED_MODULE_134__["default"]; });
/* harmony import */ var _startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_135__ = __webpack_require__(/*! ./startOfISOWeek/index.js */ "./node_modules/date-fns/esm/startOfISOWeek/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startOfISOWeek", function() { return _startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_135__["default"]; });
/* harmony import */ var _startOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_136__ = __webpack_require__(/*! ./startOfISOWeekYear/index.js */ "./node_modules/date-fns/esm/startOfISOWeekYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startOfISOWeekYear", function() { return _startOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_136__["default"]; });
/* harmony import */ var _startOfMinute_index_js__WEBPACK_IMPORTED_MODULE_137__ = __webpack_require__(/*! ./startOfMinute/index.js */ "./node_modules/date-fns/esm/startOfMinute/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startOfMinute", function() { return _startOfMinute_index_js__WEBPACK_IMPORTED_MODULE_137__["default"]; });
/* harmony import */ var _startOfMonth_index_js__WEBPACK_IMPORTED_MODULE_138__ = __webpack_require__(/*! ./startOfMonth/index.js */ "./node_modules/date-fns/esm/startOfMonth/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startOfMonth", function() { return _startOfMonth_index_js__WEBPACK_IMPORTED_MODULE_138__["default"]; });
/* harmony import */ var _startOfQuarter_index_js__WEBPACK_IMPORTED_MODULE_139__ = __webpack_require__(/*! ./startOfQuarter/index.js */ "./node_modules/date-fns/esm/startOfQuarter/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startOfQuarter", function() { return _startOfQuarter_index_js__WEBPACK_IMPORTED_MODULE_139__["default"]; });
/* harmony import */ var _startOfSecond_index_js__WEBPACK_IMPORTED_MODULE_140__ = __webpack_require__(/*! ./startOfSecond/index.js */ "./node_modules/date-fns/esm/startOfSecond/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startOfSecond", function() { return _startOfSecond_index_js__WEBPACK_IMPORTED_MODULE_140__["default"]; });
/* harmony import */ var _startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_141__ = __webpack_require__(/*! ./startOfWeek/index.js */ "./node_modules/date-fns/esm/startOfWeek/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startOfWeek", function() { return _startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_141__["default"]; });
/* harmony import */ var _startOfWeekYear_index_js__WEBPACK_IMPORTED_MODULE_142__ = __webpack_require__(/*! ./startOfWeekYear/index.js */ "./node_modules/date-fns/esm/startOfWeekYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startOfWeekYear", function() { return _startOfWeekYear_index_js__WEBPACK_IMPORTED_MODULE_142__["default"]; });
/* harmony import */ var _startOfYear_index_js__WEBPACK_IMPORTED_MODULE_143__ = __webpack_require__(/*! ./startOfYear/index.js */ "./node_modules/date-fns/esm/startOfYear/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startOfYear", function() { return _startOfYear_index_js__WEBPACK_IMPORTED_MODULE_143__["default"]; });
/* harmony import */ var _subDays_index_js__WEBPACK_IMPORTED_MODULE_144__ = __webpack_require__(/*! ./subDays/index.js */ "./node_modules/date-fns/esm/subDays/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subDays", function() { return _subDays_index_js__WEBPACK_IMPORTED_MODULE_144__["default"]; });
/* harmony import */ var _subHours_index_js__WEBPACK_IMPORTED_MODULE_145__ = __webpack_require__(/*! ./subHours/index.js */ "./node_modules/date-fns/esm/subHours/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subHours", function() { return _subHours_index_js__WEBPACK_IMPORTED_MODULE_145__["default"]; });
/* harmony import */ var _subISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_146__ = __webpack_require__(/*! ./subISOWeekYears/index.js */ "./node_modules/date-fns/esm/subISOWeekYears/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subISOWeekYears", function() { return _subISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_146__["default"]; });
/* harmony import */ var _subMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_147__ = __webpack_require__(/*! ./subMilliseconds/index.js */ "./node_modules/date-fns/esm/subMilliseconds/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subMilliseconds", function() { return _subMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_147__["default"]; });
/* harmony import */ var _subMinutes_index_js__WEBPACK_IMPORTED_MODULE_148__ = __webpack_require__(/*! ./subMinutes/index.js */ "./node_modules/date-fns/esm/subMinutes/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subMinutes", function() { return _subMinutes_index_js__WEBPACK_IMPORTED_MODULE_148__["default"]; });
/* harmony import */ var _subMonths_index_js__WEBPACK_IMPORTED_MODULE_149__ = __webpack_require__(/*! ./subMonths/index.js */ "./node_modules/date-fns/esm/subMonths/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subMonths", function() { return _subMonths_index_js__WEBPACK_IMPORTED_MODULE_149__["default"]; });
/* harmony import */ var _subQuarters_index_js__WEBPACK_IMPORTED_MODULE_150__ = __webpack_require__(/*! ./subQuarters/index.js */ "./node_modules/date-fns/esm/subQuarters/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subQuarters", function() { return _subQuarters_index_js__WEBPACK_IMPORTED_MODULE_150__["default"]; });
/* harmony import */ var _subSeconds_index_js__WEBPACK_IMPORTED_MODULE_151__ = __webpack_require__(/*! ./subSeconds/index.js */ "./node_modules/date-fns/esm/subSeconds/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subSeconds", function() { return _subSeconds_index_js__WEBPACK_IMPORTED_MODULE_151__["default"]; });
/* harmony import */ var _subWeeks_index_js__WEBPACK_IMPORTED_MODULE_152__ = __webpack_require__(/*! ./subWeeks/index.js */ "./node_modules/date-fns/esm/subWeeks/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subWeeks", function() { return _subWeeks_index_js__WEBPACK_IMPORTED_MODULE_152__["default"]; });
/* harmony import */ var _subYears_index_js__WEBPACK_IMPORTED_MODULE_153__ = __webpack_require__(/*! ./subYears/index.js */ "./node_modules/date-fns/esm/subYears/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subYears", function() { return _subYears_index_js__WEBPACK_IMPORTED_MODULE_153__["default"]; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_154__ = __webpack_require__(/*! ./toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toDate", function() { return _toDate_index_js__WEBPACK_IMPORTED_MODULE_154__["default"]; });
// This file is generated automatically by `scripts/build/indices.js`. Please, don't change it.
/***/ }),
/***/ "./node_modules/date-fns/esm/isAfter/index.js":
/*!****************************************************!*\
!*** ./node_modules/date-fns/esm/isAfter/index.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isAfter; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isAfter
* @category Common Helpers
* @summary Is the first date after the second one?
*
* @description
* Is the first date after the second one?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date that should be after the other one to return true
* @param {Date|Number} dateToCompare - the date to compare with
* @returns {Boolean} the first date is after the second date
* @throws {TypeError} 2 arguments required
*
* @example
* // Is 10 July 1989 after 11 February 1987?
* var result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11))
* //=> true
*/
function isAfter(dirtyDate, dirtyDateToCompare) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var dateToCompare = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateToCompare);
return date.getTime() > dateToCompare.getTime();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isBefore/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/isBefore/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isBefore; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isBefore
* @category Common Helpers
* @summary Is the first date before the second one?
*
* @description
* Is the first date before the second one?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date that should be before the other one to return true
* @param {Date|Number} dateToCompare - the date to compare with
* @returns {Boolean} the first date is before the second date
* @throws {TypeError} 2 arguments required
*
* @example
* // Is 10 July 1989 before 11 February 1987?
* var result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11))
* //=> false
*/
function isBefore(dirtyDate, dirtyDateToCompare) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var dateToCompare = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateToCompare);
return date.getTime() < dateToCompare.getTime();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isDate/index.js":
/*!***************************************************!*\
!*** ./node_modules/date-fns/esm/isDate/index.js ***!
\***************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isDate; });
/**
* @name isDate
* @category Common Helpers
* @summary Is the given value a date?
*
* @description
* Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {*} value - the value to check
* @returns {boolean} true if the given value is a date
* @throws {TypeError} 1 arguments required
*
* @example
* // For a valid date:
* var result = isDate(new Date())
* //=> true
*
* @example
* // For an invalid date:
* var result = isDate(new Date(NaN))
* //=> true
*
* @example
* // For some value:
* var result = isDate('2014-02-31')
* //=> false
*
* @example
* // For an object:
* var result = isDate({})
* //=> false
*/
function isDate(value) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return value instanceof Date || typeof value === 'object' && Object.prototype.toString.call(value) === '[object Date]';
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isEqual/index.js":
/*!****************************************************!*\
!*** ./node_modules/date-fns/esm/isEqual/index.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isEqual; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isEqual
* @category Common Helpers
* @summary Are the given dates equal?
*
* @description
* Are the given dates equal?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to compare
* @param {Date|Number} dateRight - the second date to compare
* @returns {Boolean} the dates are equal
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal?
* var result = isEqual(
* new Date(2014, 6, 2, 6, 30, 45, 0),
* new Date(2014, 6, 2, 6, 30, 45, 500)
* )
* //=> false
*/
function isEqual(dirtyLeftDate, dirtyRightDate) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyLeftDate);
var dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyRightDate);
return dateLeft.getTime() === dateRight.getTime();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isFirstDayOfMonth/index.js":
/*!**************************************************************!*\
!*** ./node_modules/date-fns/esm/isFirstDayOfMonth/index.js ***!
\**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isFirstDayOfMonth; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isFirstDayOfMonth
* @category Month Helpers
* @summary Is the given date the first day of a month?
*
* @description
* Is the given date the first day of a month?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to check
* @returns {Boolean} the date is the first day of a month
* @throws {TypeError} 1 argument required
*
* @example
* // Is 1 September 2014 the first day of a month?
* var result = isFirstDayOfMonth(new Date(2014, 8, 1))
* //=> true
*/
function isFirstDayOfMonth(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate).getDate() === 1;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isFriday/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/isFriday/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isFriday; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isFriday
* @category Weekday Helpers
* @summary Is the given date Friday?
*
* @description
* Is the given date Friday?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to check
* @returns {Boolean} the date is Friday
* @throws {TypeError} 1 argument required
*
* @example
* // Is 26 September 2014 Friday?
* var result = isFriday(new Date(2014, 8, 26))
* //=> true
*/
function isFriday(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate).getDay() === 5;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isLastDayOfMonth/index.js":
/*!*************************************************************!*\
!*** ./node_modules/date-fns/esm/isLastDayOfMonth/index.js ***!
\*************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isLastDayOfMonth; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _endOfDay_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../endOfDay/index.js */ "./node_modules/date-fns/esm/endOfDay/index.js");
/* harmony import */ var _endOfMonth_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../endOfMonth/index.js */ "./node_modules/date-fns/esm/endOfMonth/index.js");
/**
* @name isLastDayOfMonth
* @category Month Helpers
* @summary Is the given date the last day of a month?
*
* @description
* Is the given date the last day of a month?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to check
* @returns {Boolean} the date is the last day of a month
* @throws {TypeError} 1 argument required
*
* @example
* // Is 28 February 2014 the last day of a month?
* var result = isLastDayOfMonth(new Date(2014, 1, 28))
* //=> true
*/
function isLastDayOfMonth(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
return Object(_endOfDay_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date).getTime() === Object(_endOfMonth_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date).getTime();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isLeapYear/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/isLeapYear/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isLeapYear; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isLeapYear
* @category Year Helpers
* @summary Is the given date in the leap year?
*
* @description
* Is the given date in the leap year?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to check
* @returns {Boolean} the date is in the leap year
* @throws {TypeError} 1 argument required
*
* @example
* // Is 1 September 2012 in the leap year?
* var result = isLeapYear(new Date(2012, 8, 1))
* //=> true
*/
function isLeapYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var year = date.getFullYear();
return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isMonday/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/isMonday/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isMonday; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isMonday
* @category Weekday Helpers
* @summary Is the given date Monday?
*
* @description
* Is the given date Monday?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to check
* @returns {Boolean} the date is Monday
* @throws {TypeError} 1 argument required
*
* @example
* // Is 22 September 2014 Monday?
* var result = isMonday(new Date(2014, 8, 22))
* //=> true
*/
function isMonday(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate).getDay() === 1;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isSameDay/index.js":
/*!******************************************************!*\
!*** ./node_modules/date-fns/esm/isSameDay/index.js ***!
\******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isSameDay; });
/* harmony import */ var _startOfDay_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../startOfDay/index.js */ "./node_modules/date-fns/esm/startOfDay/index.js");
/**
* @name isSameDay
* @category Day Helpers
* @summary Are the given dates in the same day?
*
* @description
* Are the given dates in the same day?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same day
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day?
* var result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0))
* //=> true
*/
function isSameDay(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeftStartOfDay = Object(_startOfDay_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRightStartOfDay = Object(_startOfDay_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isSameHour/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/isSameHour/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isSameHour; });
/* harmony import */ var _startOfHour_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../startOfHour/index.js */ "./node_modules/date-fns/esm/startOfHour/index.js");
/**
* @name isSameHour
* @category Hour Helpers
* @summary Are the given dates in the same hour?
*
* @description
* Are the given dates in the same hour?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same hour
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 4 September 2014 06:00:00 and 4 September 06:30:00 in the same hour?
* var result = isSameHour(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 6, 30))
* //=> true
*/
function isSameHour(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeftStartOfHour = Object(_startOfHour_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRightStartOfHour = Object(_startOfHour_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
return dateLeftStartOfHour.getTime() === dateRightStartOfHour.getTime();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isSameISOWeek/index.js":
/*!**********************************************************!*\
!*** ./node_modules/date-fns/esm/isSameISOWeek/index.js ***!
\**********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isSameISOWeek; });
/* harmony import */ var _isSameWeek_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../isSameWeek/index.js */ "./node_modules/date-fns/esm/isSameWeek/index.js");
/**
* @name isSameISOWeek
* @category ISO Week Helpers
* @summary Are the given dates in the same ISO week?
*
* @description
* Are the given dates in the same ISO week?
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same ISO week
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 1 September 2014 and 7 September 2014 in the same ISO week?
* var result = isSameISOWeek(new Date(2014, 8, 1), new Date(2014, 8, 7))
* //=> true
*/
function isSameISOWeek(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
return Object(_isSameWeek_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft, dirtyDateRight, {
weekStartsOn: 1
});
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isSameISOWeekYear/index.js":
/*!**************************************************************!*\
!*** ./node_modules/date-fns/esm/isSameISOWeekYear/index.js ***!
\**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isSameISOWeekYear; });
/* harmony import */ var _startOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../startOfISOWeekYear/index.js */ "./node_modules/date-fns/esm/startOfISOWeekYear/index.js");
/**
* @name isSameISOWeekYear
* @category ISO Week-Numbering Year Helpers
* @summary Are the given dates in the same ISO week-numbering year?
*
* @description
* Are the given dates in the same ISO week-numbering year?
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `isSameISOYear` to `isSameISOWeekYear`.
* "ISO week year" is short for [ISO week-numbering year](https://en.wikipedia.org/wiki/ISO_week_date).
* This change makes the name consistent with
* locale-dependent week-numbering year helpers, e.g., `getWeekYear`.
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same ISO week-numbering year
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year?
* var result = isSameISOWeekYear(new Date(2003, 11, 29), new Date(2005, 0, 2))
* //=> true
*/
function isSameISOWeekYear(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeftStartOfYear = Object(_startOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRightStartOfYear = Object(_startOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
return dateLeftStartOfYear.getTime() === dateRightStartOfYear.getTime();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isSameMinute/index.js":
/*!*********************************************************!*\
!*** ./node_modules/date-fns/esm/isSameMinute/index.js ***!
\*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isSameMinute; });
/* harmony import */ var _startOfMinute_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../startOfMinute/index.js */ "./node_modules/date-fns/esm/startOfMinute/index.js");
/**
* @name isSameMinute
* @category Minute Helpers
* @summary Are the given dates in the same minute?
*
* @description
* Are the given dates in the same minute?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same minute
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 4 September 2014 06:30:00 and 4 September 2014 06:30:15
* // in the same minute?
* var result = isSameMinute(
* new Date(2014, 8, 4, 6, 30),
* new Date(2014, 8, 4, 6, 30, 15)
* )
* //=> true
*/
function isSameMinute(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeftStartOfMinute = Object(_startOfMinute_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRightStartOfMinute = Object(_startOfMinute_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
return dateLeftStartOfMinute.getTime() === dateRightStartOfMinute.getTime();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isSameMonth/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/isSameMonth/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isSameMonth; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isSameMonth
* @category Month Helpers
* @summary Are the given dates in the same month?
*
* @description
* Are the given dates in the same month?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same month
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 2 September 2014 and 25 September 2014 in the same month?
* var result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25))
* //=> true
*/
function isSameMonth(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
return dateLeft.getFullYear() === dateRight.getFullYear() && dateLeft.getMonth() === dateRight.getMonth();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isSameQuarter/index.js":
/*!**********************************************************!*\
!*** ./node_modules/date-fns/esm/isSameQuarter/index.js ***!
\**********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isSameQuarter; });
/* harmony import */ var _startOfQuarter_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../startOfQuarter/index.js */ "./node_modules/date-fns/esm/startOfQuarter/index.js");
/**
* @name isSameQuarter
* @category Quarter Helpers
* @summary Are the given dates in the same year quarter?
*
* @description
* Are the given dates in the same year quarter?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same quarter
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 1 January 2014 and 8 March 2014 in the same quarter?
* var result = isSameQuarter(new Date(2014, 0, 1), new Date(2014, 2, 8))
* //=> true
*/
function isSameQuarter(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeftStartOfQuarter = Object(_startOfQuarter_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRightStartOfQuarter = Object(_startOfQuarter_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
return dateLeftStartOfQuarter.getTime() === dateRightStartOfQuarter.getTime();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isSameSecond/index.js":
/*!*********************************************************!*\
!*** ./node_modules/date-fns/esm/isSameSecond/index.js ***!
\*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isSameSecond; });
/* harmony import */ var _startOfSecond_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../startOfSecond/index.js */ "./node_modules/date-fns/esm/startOfSecond/index.js");
/**
* @name isSameSecond
* @category Second Helpers
* @summary Are the given dates in the same second?
*
* @description
* Are the given dates in the same second?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same second
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 4 September 2014 06:30:15.000 and 4 September 2014 06:30.15.500
* // in the same second?
* var result = isSameSecond(
* new Date(2014, 8, 4, 6, 30, 15),
* new Date(2014, 8, 4, 6, 30, 15, 500)
* )
* //=> true
*/
function isSameSecond(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeftStartOfSecond = Object(_startOfSecond_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRightStartOfSecond = Object(_startOfSecond_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
return dateLeftStartOfSecond.getTime() === dateRightStartOfSecond.getTime();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isSameWeek/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/isSameWeek/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isSameWeek; });
/* harmony import */ var _startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../startOfWeek/index.js */ "./node_modules/date-fns/esm/startOfWeek/index.js");
/**
* @name isSameWeek
* @category Week Helpers
* @summary Are the given dates in the same week?
*
* @description
* Are the given dates in the same week?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {Boolean} the dates are in the same week
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // Are 31 August 2014 and 4 September 2014 in the same week?
* var result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4))
* //=> true
*
* @example
* // If week starts with Monday,
* // are 31 August 2014 and 4 September 2014 in the same week?
* var result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4), {
* weekStartsOn: 1
* })
* //=> false
*/
function isSameWeek(dirtyDateLeft, dirtyDateRight, dirtyOptions) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeftStartOfWeek = Object(_startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft, dirtyOptions);
var dateRightStartOfWeek = Object(_startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight, dirtyOptions);
return dateLeftStartOfWeek.getTime() === dateRightStartOfWeek.getTime();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isSameYear/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/isSameYear/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isSameYear; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isSameYear
* @category Year Helpers
* @summary Are the given dates in the same year?
*
* @description
* Are the given dates in the same year?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same year
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 2 September 2014 and 25 September 2014 in the same year?
* var result = isSameYear(new Date(2014, 8, 2), new Date(2014, 8, 25))
* //=> true
*/
function isSameYear(dirtyDateLeft, dirtyDateRight) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var dateLeft = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateLeft);
var dateRight = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDateRight);
return dateLeft.getFullYear() === dateRight.getFullYear();
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isSaturday/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/isSaturday/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isSaturday; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isSaturday
* @category Weekday Helpers
* @summary Is the given date Saturday?
*
* @description
* Is the given date Saturday?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to check
* @returns {Boolean} the date is Saturday
* @throws {TypeError} 1 argument required
*
* @example
* // Is 27 September 2014 Saturday?
* var result = isSaturday(new Date(2014, 8, 27))
* //=> true
*/
function isSaturday(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate).getDay() === 6;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isSunday/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/isSunday/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isSunday; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isSunday
* @category Weekday Helpers
* @summary Is the given date Sunday?
*
* @description
* Is the given date Sunday?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to check
* @returns {Boolean} the date is Sunday
* @throws {TypeError} 1 argument required
*
* @example
* // Is 21 September 2014 Sunday?
* var result = isSunday(new Date(2014, 8, 21))
* //=> true
*/
function isSunday(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate).getDay() === 0;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isThursday/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/isThursday/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isThursday; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isThursday
* @category Weekday Helpers
* @summary Is the given date Thursday?
*
* @description
* Is the given date Thursday?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to check
* @returns {Boolean} the date is Thursday
* @throws {TypeError} 1 argument required
*
* @example
* // Is 25 September 2014 Thursday?
* var result = isThursday(new Date(2014, 8, 25))
* //=> true
*/
function isThursday(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate).getDay() === 4;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isTuesday/index.js":
/*!******************************************************!*\
!*** ./node_modules/date-fns/esm/isTuesday/index.js ***!
\******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isTuesday; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isTuesday
* @category Weekday Helpers
* @summary Is the given date Tuesday?
*
* @description
* Is the given date Tuesday?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to check
* @returns {Boolean} the date is Tuesday
* @throws {TypeError} 1 argument required
*
* @example
* // Is 23 September 2014 Tuesday?
* var result = isTuesday(new Date(2014, 8, 23))
* //=> true
*/
function isTuesday(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate).getDay() === 2;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isValid/index.js":
/*!****************************************************!*\
!*** ./node_modules/date-fns/esm/isValid/index.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isValid; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isValid
* @category Common Helpers
* @summary Is the given date valid?
*
* @description
* Returns false if argument is Invalid Date and true otherwise.
* Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
* Invalid Date is a Date, whose time value is NaN.
*
* Time value of Date: http://es5.github.io/#x15.9.1.1
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - Now `isValid` doesn't throw an exception
* if the first argument is not an instance of Date.
* Instead, argument is converted beforehand using `toDate`.
*
* Examples:
*
* | `isValid` argument | Before v2.0.0 | v2.0.0 onward |
* |---------------------------|---------------|---------------|
* | `new Date()` | `true` | `true` |
* | `new Date('2016-01-01')` | `true` | `true` |
* | `new Date('')` | `false` | `false` |
* | `new Date(1488370835081)` | `true` | `true` |
* | `new Date(NaN)` | `false` | `false` |
* | `'2016-01-01'` | `TypeError` | `true` |
* | `''` | `TypeError` | `false` |
* | `1488370835081` | `TypeError` | `true` |
* | `NaN` | `TypeError` | `false` |
*
* We introduce this change to make *date-fns* consistent with ECMAScript behavior
* that try to coerce arguments to the expected type
* (which is also the case with other *date-fns* functions).
*
* @param {*} date - the date to check
* @returns {Boolean} the date is valid
* @throws {TypeError} 1 argument required
*
* @example
* // For the valid date:
* var result = isValid(new Date(2014, 1, 31))
* //=> true
*
* @example
* // For the value, convertable into a date:
* var result = isValid(1393804800000)
* //=> true
*
* @example
* // For the invalid date:
* var result = isValid(new Date(''))
* //=> false
*/
function isValid(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
return !isNaN(date);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isWednesday/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/isWednesday/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isWednesday; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isWednesday
* @category Weekday Helpers
* @summary Is the given date Wednesday?
*
* @description
* Is the given date Wednesday?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to check
* @returns {Boolean} the date is Wednesday
* @throws {TypeError} 1 argument required
*
* @example
* // Is 24 September 2014 Wednesday?
* var result = isWednesday(new Date(2014, 8, 24))
* //=> true
*/
function isWednesday(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate).getDay() === 3;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isWeekend/index.js":
/*!******************************************************!*\
!*** ./node_modules/date-fns/esm/isWeekend/index.js ***!
\******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isWeekend; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isWeekend
* @category Weekday Helpers
* @summary Does the given date fall on a weekend?
*
* @description
* Does the given date fall on a weekend?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to check
* @returns {Boolean} the date falls on a weekend
* @throws {TypeError} 1 argument required
*
* @example
* // Does 5 October 2014 fall on a weekend?
* var result = isWeekend(new Date(2014, 9, 5))
* //=> true
*/
function isWeekend(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var day = date.getDay();
return day === 0 || day === 6;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/isWithinInterval/index.js":
/*!*************************************************************!*\
!*** ./node_modules/date-fns/esm/isWithinInterval/index.js ***!
\*************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isWithinInterval; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name isWithinInterval
* @category Interval Helpers
* @summary Is the given date within the interval?
*
* @description
* Is the given date within the interval?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `isWithinRange` to `isWithinInterval`.
* This change was made to mirror the use of the word "interval" in standard ISO 8601:2004 terminology:
*
* ```
* 2.1.3
* time interval
* part of the time axis limited by two instants
* ```
*
* Also, this function now accepts an object with `start` and `end` properties
* instead of two arguments as an interval.
* This function now throws `RangeError` if the start of the interval is after its end
* or if any date in the interval is `Invalid Date`.
*
* ```javascript
* // Before v2.0.0
*
* isWithinRange(
* new Date(2014, 0, 3),
* new Date(2014, 0, 1), new Date(2014, 0, 7)
* )
*
* // v2.0.0 onward
*
* isWithinInterval(
* new Date(2014, 0, 3),
* { start: new Date(2014, 0, 1), end: new Date(2014, 0, 7) }
* )
* ```
*
* @param {Date|Number} date - the date to check
* @param {Interval} interval - the interval to check
* @returns {Boolean} the date is within the interval
* @throws {TypeError} 2 arguments required
* @throws {RangeError} The start of an interval cannot be after its end
* @throws {RangeError} Date in interval cannot be `Invalid Date`
*
* @example
* // For the date within the interval:
* isWithinInterval(new Date(2014, 0, 3), {
* start: new Date(2014, 0, 1),
* end: new Date(2014, 0, 7)
* })
* //=> true
*
* @example
* // For the date outside of the interval:
* isWithinInterval(new Date(2014, 0, 10), {
* start: new Date(2014, 0, 1),
* end: new Date(2014, 0, 7)
* })
* //=> false
*/
function isWithinInterval(dirtyDate, dirtyInterval) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var interval = dirtyInterval || {};
var time = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate).getTime();
var startTime = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(interval.start).getTime();
var endTime = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(interval.end).getTime(); // Throw an exception if start date is after end date or if any date is `Invalid Date`
if (!(startTime <= endTime)) {
throw new RangeError('Invalid interval');
}
return time >= startTime && time <= endTime;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/lastDayOfDecade/index.js":
/*!************************************************************!*\
!*** ./node_modules/date-fns/esm/lastDayOfDecade/index.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return lastDayOfDecade; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name lastDayOfDecade
* @category Decade Helpers
* @summary Return the last day of a decade for the given date.
*
* @description
* Return the last day of a decade for the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the last day of a decade
* @throws {TypeError} 1 argument required
*
* @example
* // The last day of a decade for 21 December 2012 21:12:00:
* var result = lastDayOfDecade(new Date(2012, 11, 21, 21, 12, 00))
* //=> Wed Dec 31 2019 00:00:00
*/
function lastDayOfDecade(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var year = date.getFullYear();
var decade = 9 + Math.floor(year / 10) * 10;
date.setFullYear(decade + 1, 0, 0);
date.setHours(0, 0, 0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/lastDayOfISOWeek/index.js":
/*!*************************************************************!*\
!*** ./node_modules/date-fns/esm/lastDayOfISOWeek/index.js ***!
\*************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return lastDayOfISOWeek; });
/* harmony import */ var _lastDayOfWeek_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../lastDayOfWeek/index.js */ "./node_modules/date-fns/esm/lastDayOfWeek/index.js");
/**
* @name lastDayOfISOWeek
* @category ISO Week Helpers
* @summary Return the last day of an ISO week for the given date.
*
* @description
* Return the last day of an ISO week for the given date.
* The result will be in the local timezone.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the last day of an ISO week
* @throws {TypeError} 1 argument required
*
* @example
* // The last day of an ISO week for 2 September 2014 11:55:00:
* var result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sun Sep 07 2014 00:00:00
*/
function lastDayOfISOWeek(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return Object(_lastDayOfWeek_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate, {
weekStartsOn: 1
});
}
/***/ }),
/***/ "./node_modules/date-fns/esm/lastDayOfISOWeekYear/index.js":
/*!*****************************************************************!*\
!*** ./node_modules/date-fns/esm/lastDayOfISOWeekYear/index.js ***!
\*****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return lastDayOfISOWeekYear; });
/* harmony import */ var _getISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../getISOWeekYear/index.js */ "./node_modules/date-fns/esm/getISOWeekYear/index.js");
/* harmony import */ var _startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfISOWeek/index.js */ "./node_modules/date-fns/esm/startOfISOWeek/index.js");
/**
* @name lastDayOfISOWeekYear
* @category ISO Week-Numbering Year Helpers
* @summary Return the last day of an ISO week-numbering year for the given date.
*
* @description
* Return the last day of an ISO week-numbering year,
* which always starts 3 days before the year's first Thursday.
* The result will be in the local timezone.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `lastDayOfISOYear` to `lastDayOfISOWeekYear`.
* "ISO week year" is short for [ISO week-numbering year](https://en.wikipedia.org/wiki/ISO_week_date).
* This change makes the name consistent with
* locale-dependent week-numbering year helpers, e.g., `getWeekYear`.
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of an ISO week-numbering year
* @throws {TypeError} 1 argument required
*
* @example
* // The last day of an ISO week-numbering year for 2 July 2005:
* var result = lastDayOfISOWeekYear(new Date(2005, 6, 2))
* //=> Sun Jan 01 2006 00:00:00
*/
function lastDayOfISOWeekYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var year = Object(_getISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var fourthOfJanuary = new Date(0);
fourthOfJanuary.setFullYear(year + 1, 0, 4);
fourthOfJanuary.setHours(0, 0, 0, 0);
var date = Object(_startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(fourthOfJanuary);
date.setDate(date.getDate() - 1);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/lastDayOfMonth/index.js":
/*!***********************************************************!*\
!*** ./node_modules/date-fns/esm/lastDayOfMonth/index.js ***!
\***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return lastDayOfMonth; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name lastDayOfMonth
* @category Month Helpers
* @summary Return the last day of a month for the given date.
*
* @description
* Return the last day of a month for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the last day of a month
* @throws {TypeError} 1 argument required
*
* @example
* // The last day of a month for 2 September 2014 11:55:00:
* var result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 30 2014 00:00:00
*/
function lastDayOfMonth(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var month = date.getMonth();
date.setFullYear(date.getFullYear(), month + 1, 0);
date.setHours(0, 0, 0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/lastDayOfQuarter/index.js":
/*!*************************************************************!*\
!*** ./node_modules/date-fns/esm/lastDayOfQuarter/index.js ***!
\*************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return lastDayOfQuarter; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name lastDayOfQuarter
* @category Quarter Helpers
* @summary Return the last day of a year quarter for the given date.
*
* @description
* Return the last day of a year quarter for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @param {Object} [options] - an object with options.
* @param {0|1|2} [options.additionalDigits=2] - passed to `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
* @returns {Date} the last day of a quarter
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2
*
* @example
* // The last day of a quarter for 2 September 2014 11:55:00:
* var result = lastDayOfQuarter(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 30 2014 00:00:00
*/
function lastDayOfQuarter(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var currentMonth = date.getMonth();
var month = currentMonth - currentMonth % 3 + 3;
date.setMonth(month, 0);
date.setHours(0, 0, 0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/lastDayOfWeek/index.js":
/*!**********************************************************!*\
!*** ./node_modules/date-fns/esm/lastDayOfWeek/index.js ***!
\**********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return lastDayOfWeek; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name lastDayOfWeek
* @category Week Helpers
* @summary Return the last day of a week for the given date.
*
* @description
* Return the last day of a week for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {Date} the last day of a week
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // The last day of a week for 2 September 2014 11:55:00:
* var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sat Sep 06 2014 00:00:00
*
* @example
* // If the week starts on Monday, the last day of the week for 2 September 2014 11:55:00:
* var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
* //=> Sun Sep 07 2014 00:00:00
*/
function lastDayOfWeek(dirtyDate, dirtyOptions) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var options = dirtyOptions || {};
var locale = options.locale;
var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeWeekStartsOn);
var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var day = date.getDay();
var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
date.setHours(0, 0, 0, 0);
date.setDate(date.getDate() + diff);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/lastDayOfYear/index.js":
/*!**********************************************************!*\
!*** ./node_modules/date-fns/esm/lastDayOfYear/index.js ***!
\**********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return lastDayOfYear; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name lastDayOfYear
* @category Year Helpers
* @summary Return the last day of a year for the given date.
*
* @description
* Return the last day of a year for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the last day of a year
* @throws {TypeError} 1 argument required
*
* @example
* // The last day of a year for 2 September 2014 11:55:00:
* var result = lastDayOfYear(new Date(2014, 8, 2, 11, 55, 00))
* //=> Wed Dec 31 2014 00:00:00
*/
function lastDayOfYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var year = date.getFullYear();
date.setFullYear(year + 1, 0, 0);
date.setHours(0, 0, 0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/lightFormat/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/lightFormat/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return lightFormat; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _lib_format_lightFormatters_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../_lib/format/lightFormatters/index.js */ "./node_modules/date-fns/esm/_lib/format/lightFormatters/index.js");
/* harmony import */ var _lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../_lib/getTimezoneOffsetInMilliseconds/index.js */ "./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js");
/* harmony import */ var _isValid_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../isValid/index.js */ "./node_modules/date-fns/esm/isValid/index.js");
/* harmony import */ var _subMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../subMilliseconds/index.js */ "./node_modules/date-fns/esm/subMilliseconds/index.js");
// This RegExp consists of three parts separated by `|`:
// - (\w)\1* matches any sequences of the same letter
// - '' matches two quote characters in a row
// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
// except a single quote symbol, which ends the sequence.
// Two quote characters do not end the sequence.
// If there is no matching single quote
// then the sequence will continue until the end of the string.
// - . matches any single character unmatched by previous parts of the RegExps
var formattingTokensRegExp = /(\w)\1*|''|'(''|[^'])+('|$)|./g;
var escapedStringRegExp = /^'(.*?)'?$/;
var doubleQuoteRegExp = /''/g;
/**
* @name lightFormat
* @category Common Helpers
* @summary Format the date.
*
* @description
* Return the formatted date string in the given format. Unlike `format`,
* `lightFormat` doesn't use locales and outputs date using the most popular tokens.
*
* > ⚠️ Please note that the `lightFormat` tokens differ from Moment.js and other libraries.
* > See: https://git.io/fxCyr
*
* The characters wrapped between two single quotes characters (') are escaped.
* Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
* (see the last example)
*
* Format of the string is based on Unicode Technical Standard #35:
* https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
* with a few additions (see note 7 below the table).
*
* Accepted patterns:
* | Unit | Pattern | Result examples |
* |---------------------------------|---------|-----------------------------------|
* | AM, PM | a..aaa | AM, PM |
* | | aaaa | a.m., p.m. |
* | | aaaaa | a, p |
* | Calendar year | y | 44, 1, 1900, 2017 |
* | | yy | 44, 01, 00, 17 |
* | | yyy | 044, 001, 000, 017 |
* | | yyyy | 0044, 0001, 1900, 2017 |
* | Month (formatting) | M | 1, 2, ..., 12 |
* | | MM | 01, 02, ..., 12 |
* | Day of month | d | 1, 2, ..., 31 |
* | | dd | 01, 02, ..., 31 |
* | Hour [1-12] | h | 1, 2, ..., 11, 12 |
* | | hh | 01, 02, ..., 11, 12 |
* | Hour [0-23] | H | 0, 1, 2, ..., 23 |
* | | HH | 00, 01, 02, ..., 23 |
* | Minute | m | 0, 1, ..., 59 |
* | | mm | 00, 01, ..., 59 |
* | Second | s | 0, 1, ..., 59 |
* | | ss | 00, 01, ..., 59 |
* | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z |
* | | XX | -0800, +0530, Z |
* | | XXX | -08:00, +05:30, Z |
* | | XXXX | -0800, +0530, Z, +123456 |
* | | XXXXX | -08:00, +05:30, Z, +12:34:56 |
* | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 |
* | | xx | -0800, +0530, +0000 |
* | | xxx | -08:00, +05:30, +00:00 |
* | | xxxx | -0800, +0530, +0000, +123456 |
* | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 |
*
* @param {Date|Number} date - the original date
* @param {String} format - the string of tokens
* @returns {String} the formatted date string
* @throws {TypeError} 2 arguments required
*
* @example
* var result = format(new Date(2014, 1, 11), 'yyyy-MM-dd')
* //=> '1987-02-11'
*/
function lightFormat(dirtyDate, dirtyFormatStr) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var formatStr = String(dirtyFormatStr);
var originalDate = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
if (!Object(_isValid_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(originalDate)) {
throw new RangeError('Invalid time value');
} // Convert the date in system timezone to the same date in UTC+00:00 timezone.
// This ensures that when UTC functions will be implemented, locales will be compatible with them.
// See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
var timezoneOffset = Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(originalDate);
var utcDate = Object(_subMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_4__["default"])(originalDate, timezoneOffset);
var result = formatStr.match(formattingTokensRegExp).map(function (substring) {
// Replace two single quote characters with one single quote character
if (substring === "''") {
return "'";
}
var firstCharacter = substring[0];
if (firstCharacter === "'") {
return cleanEscapedString(substring);
}
var formatter = _lib_format_lightFormatters_index_js__WEBPACK_IMPORTED_MODULE_1__["default"][firstCharacter];
if (formatter) {
return formatter(utcDate, substring, null, {});
}
return substring;
}).join('');
return result;
}
function cleanEscapedString(input) {
return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'");
}
/***/ }),
/***/ "./node_modules/date-fns/esm/locale/_lib/buildFormatLongFn/index.js":
/*!**************************************************************************!*\
!*** ./node_modules/date-fns/esm/locale/_lib/buildFormatLongFn/index.js ***!
\**************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return buildFormatLongFn; });
function buildFormatLongFn(args) {
return function (dirtyOptions) {
var options = dirtyOptions || {};
var width = options.width ? String(options.width) : args.defaultWidth;
var format = args.formats[width] || args.formats[args.defaultWidth];
return format;
};
}
/***/ }),
/***/ "./node_modules/date-fns/esm/locale/_lib/buildLocalizeFn/index.js":
/*!************************************************************************!*\
!*** ./node_modules/date-fns/esm/locale/_lib/buildLocalizeFn/index.js ***!
\************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return buildLocalizeFn; });
function buildLocalizeFn(args) {
return function (dirtyIndex, dirtyOptions) {
var options = dirtyOptions || {};
var width = options.width ? String(options.width) : args.defaultWidth;
var context = options.context ? String(options.context) : 'standalone';
var valuesArray;
if (context === 'formatting' && args.formattingValues) {
valuesArray = args.formattingValues[width] || args.formattingValues[args.defaultFormattingWidth];
} else {
valuesArray = args.values[width] || args.values[args.defaultWidth];
}
var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex;
return valuesArray[index];
};
}
/***/ }),
/***/ "./node_modules/date-fns/esm/locale/_lib/buildMatchFn/index.js":
/*!*********************************************************************!*\
!*** ./node_modules/date-fns/esm/locale/_lib/buildMatchFn/index.js ***!
\*********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return buildMatchFn; });
function buildMatchFn(args) {
return function (dirtyString, dirtyOptions) {
var string = String(dirtyString);
var options = dirtyOptions || {};
var width = options.width;
var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
var matchResult = string.match(matchPattern);
if (!matchResult) {
return null;
}
var matchedString = matchResult[0];
var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
var value;
if (Object.prototype.toString.call(parsePatterns) === '[object Array]') {
value = parsePatterns.findIndex(function (pattern) {
return pattern.test(string);
});
} else {
value = findKey(parsePatterns, function (pattern) {
return pattern.test(string);
});
}
value = args.valueCallback ? args.valueCallback(value) : value;
value = options.valueCallback ? options.valueCallback(value) : value;
return {
value: value,
rest: string.slice(matchedString.length)
};
};
}
function findKey(object, predicate) {
for (var key in object) {
if (object.hasOwnProperty(key) && predicate(object[key])) {
return key;
}
}
}
/***/ }),
/***/ "./node_modules/date-fns/esm/locale/_lib/buildMatchPatternFn/index.js":
/*!****************************************************************************!*\
!*** ./node_modules/date-fns/esm/locale/_lib/buildMatchPatternFn/index.js ***!
\****************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return buildMatchPatternFn; });
function buildMatchPatternFn(args) {
return function (dirtyString, dirtyOptions) {
var string = String(dirtyString);
var options = dirtyOptions || {};
var matchResult = string.match(args.matchPattern);
if (!matchResult) {
return null;
}
var matchedString = matchResult[0];
var parseResult = string.match(args.parsePattern);
if (!parseResult) {
return null;
}
var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
value = options.valueCallback ? options.valueCallback(value) : value;
return {
value: value,
rest: string.slice(matchedString.length)
};
};
}
/***/ }),
/***/ "./node_modules/date-fns/esm/locale/en-US/_lib/formatDistance/index.js":
/*!*****************************************************************************!*\
!*** ./node_modules/date-fns/esm/locale/en-US/_lib/formatDistance/index.js ***!
\*****************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return formatDistance; });
var formatDistanceLocale = {
lessThanXSeconds: {
one: 'less than a second',
other: 'less than {{count}} seconds'
},
xSeconds: {
one: '1 second',
other: '{{count}} seconds'
},
halfAMinute: 'half a minute',
lessThanXMinutes: {
one: 'less than a minute',
other: 'less than {{count}} minutes'
},
xMinutes: {
one: '1 minute',
other: '{{count}} minutes'
},
aboutXHours: {
one: 'about 1 hour',
other: 'about {{count}} hours'
},
xHours: {
one: '1 hour',
other: '{{count}} hours'
},
xDays: {
one: '1 day',
other: '{{count}} days'
},
aboutXMonths: {
one: 'about 1 month',
other: 'about {{count}} months'
},
xMonths: {
one: '1 month',
other: '{{count}} months'
},
aboutXYears: {
one: 'about 1 year',
other: 'about {{count}} years'
},
xYears: {
one: '1 year',
other: '{{count}} years'
},
overXYears: {
one: 'over 1 year',
other: 'over {{count}} years'
},
almostXYears: {
one: 'almost 1 year',
other: 'almost {{count}} years'
}
};
function formatDistance(token, count, options) {
options = options || {};
var result;
if (typeof formatDistanceLocale[token] === 'string') {
result = formatDistanceLocale[token];
} else if (count === 1) {
result = formatDistanceLocale[token].one;
} else {
result = formatDistanceLocale[token].other.replace('{{count}}', count);
}
if (options.addSuffix) {
if (options.comparison > 0) {
return 'in ' + result;
} else {
return result + ' ago';
}
}
return result;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/locale/en-US/_lib/formatLong/index.js":
/*!*************************************************************************!*\
!*** ./node_modules/date-fns/esm/locale/en-US/_lib/formatLong/index.js ***!
\*************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_buildFormatLongFn_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../_lib/buildFormatLongFn/index.js */ "./node_modules/date-fns/esm/locale/_lib/buildFormatLongFn/index.js");
var dateFormats = {
full: 'EEEE, MMMM do, y',
long: 'MMMM do, y',
medium: 'MMM d, y',
short: 'MM/dd/yyyy'
};
var timeFormats = {
full: 'h:mm:ss a zzzz',
long: 'h:mm:ss a z',
medium: 'h:mm:ss a',
short: 'h:mm a'
};
var dateTimeFormats = {
full: "{{date}} 'at' {{time}}",
long: "{{date}} 'at' {{time}}",
medium: '{{date}}, {{time}}',
short: '{{date}}, {{time}}'
};
var formatLong = {
date: Object(_lib_buildFormatLongFn_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])({
formats: dateFormats,
defaultWidth: 'full'
}),
time: Object(_lib_buildFormatLongFn_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])({
formats: timeFormats,
defaultWidth: 'full'
}),
dateTime: Object(_lib_buildFormatLongFn_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])({
formats: dateTimeFormats,
defaultWidth: 'full'
})
};
/* harmony default export */ __webpack_exports__["default"] = (formatLong);
/***/ }),
/***/ "./node_modules/date-fns/esm/locale/en-US/_lib/formatRelative/index.js":
/*!*****************************************************************************!*\
!*** ./node_modules/date-fns/esm/locale/en-US/_lib/formatRelative/index.js ***!
\*****************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return formatRelative; });
var formatRelativeLocale = {
lastWeek: "'last' eeee 'at' p",
yesterday: "'yesterday at' p",
today: "'today at' p",
tomorrow: "'tomorrow at' p",
nextWeek: "eeee 'at' p",
other: 'P'
};
function formatRelative(token, date, baseDate, options) {
return formatRelativeLocale[token];
}
/***/ }),
/***/ "./node_modules/date-fns/esm/locale/en-US/_lib/localize/index.js":
/*!***********************************************************************!*\
!*** ./node_modules/date-fns/esm/locale/en-US/_lib/localize/index.js ***!
\***********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_buildLocalizeFn_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../_lib/buildLocalizeFn/index.js */ "./node_modules/date-fns/esm/locale/_lib/buildLocalizeFn/index.js");
var eraValues = {
narrow: ['B', 'A'],
abbreviated: ['BC', 'AD'],
wide: ['Before Christ', 'Anno Domini']
};
var quarterValues = {
narrow: ['1', '2', '3', '4'],
abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'],
wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter']
}; // Note: in English, the names of days of the week and months are capitalized.
// If you are making a new locale based on this one, check if the same is true for the language you're working on.
// Generally, formatted dates should look like they are in the middle of a sentence,
// e.g. in Spanish language the weekdays and months should be in the lowercase.
var monthValues = {
narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
};
var dayValues = {
narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
};
var dayPeriodValues = {
narrow: {
am: 'a',
pm: 'p',
midnight: 'mi',
noon: 'n',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
},
abbreviated: {
am: 'AM',
pm: 'PM',
midnight: 'midnight',
noon: 'noon',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
},
wide: {
am: 'a.m.',
pm: 'p.m.',
midnight: 'midnight',
noon: 'noon',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
}
};
var formattingDayPeriodValues = {
narrow: {
am: 'a',
pm: 'p',
midnight: 'mi',
noon: 'n',
morning: 'in the morning',
afternoon: 'in the afternoon',
evening: 'in the evening',
night: 'at night'
},
abbreviated: {
am: 'AM',
pm: 'PM',
midnight: 'midnight',
noon: 'noon',
morning: 'in the morning',
afternoon: 'in the afternoon',
evening: 'in the evening',
night: 'at night'
},
wide: {
am: 'a.m.',
pm: 'p.m.',
midnight: 'midnight',
noon: 'noon',
morning: 'in the morning',
afternoon: 'in the afternoon',
evening: 'in the evening',
night: 'at night'
}
};
function ordinalNumber(dirtyNumber, dirtyOptions) {
var number = Number(dirtyNumber); // If ordinal numbers depend on context, for example,
// if they are different for different grammatical genders,
// use `options.unit`:
//
// var options = dirtyOptions || {}
// var unit = String(options.unit)
//
// where `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',
// 'day', 'hour', 'minute', 'second'
var rem100 = number % 100;
if (rem100 > 20 || rem100 < 10) {
switch (rem100 % 10) {
case 1:
return number + 'st';
case 2:
return number + 'nd';
case 3:
return number + 'rd';
}
}
return number + 'th';
}
var localize = {
ordinalNumber: ordinalNumber,
era: Object(_lib_buildLocalizeFn_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])({
values: eraValues,
defaultWidth: 'wide'
}),
quarter: Object(_lib_buildLocalizeFn_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])({
values: quarterValues,
defaultWidth: 'wide',
argumentCallback: function (quarter) {
return Number(quarter) - 1;
}
}),
month: Object(_lib_buildLocalizeFn_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])({
values: monthValues,
defaultWidth: 'wide'
}),
day: Object(_lib_buildLocalizeFn_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])({
values: dayValues,
defaultWidth: 'wide'
}),
dayPeriod: Object(_lib_buildLocalizeFn_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])({
values: dayPeriodValues,
defaultWidth: 'wide',
formattingValues: formattingDayPeriodValues,
defaultFormattingWidth: 'wide'
})
};
/* harmony default export */ __webpack_exports__["default"] = (localize);
/***/ }),
/***/ "./node_modules/date-fns/esm/locale/en-US/_lib/match/index.js":
/*!********************************************************************!*\
!*** ./node_modules/date-fns/esm/locale/en-US/_lib/match/index.js ***!
\********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_buildMatchPatternFn_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../_lib/buildMatchPatternFn/index.js */ "./node_modules/date-fns/esm/locale/_lib/buildMatchPatternFn/index.js");
/* harmony import */ var _lib_buildMatchFn_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../_lib/buildMatchFn/index.js */ "./node_modules/date-fns/esm/locale/_lib/buildMatchFn/index.js");
var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
var parseOrdinalNumberPattern = /\d+/i;
var matchEraPatterns = {
narrow: /^(b|a)/i,
abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
wide: /^(before christ|before common era|anno domini|common era)/i
};
var parseEraPatterns = {
any: [/^b/i, /^(a|c)/i]
};
var matchQuarterPatterns = {
narrow: /^[1234]/i,
abbreviated: /^q[1234]/i,
wide: /^[1234](th|st|nd|rd)? quarter/i
};
var parseQuarterPatterns = {
any: [/1/i, /2/i, /3/i, /4/i]
};
var matchMonthPatterns = {
narrow: /^[jfmasond]/i,
abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
};
var parseMonthPatterns = {
narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i],
any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i]
};
var matchDayPatterns = {
narrow: /^[smtwf]/i,
short: /^(su|mo|tu|we|th|fr|sa)/i,
abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
};
var parseDayPatterns = {
narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
};
var matchDayPeriodPatterns = {
narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
};
var parseDayPeriodPatterns = {
any: {
am: /^a/i,
pm: /^p/i,
midnight: /^mi/i,
noon: /^no/i,
morning: /morning/i,
afternoon: /afternoon/i,
evening: /evening/i,
night: /night/i
}
};
var match = {
ordinalNumber: Object(_lib_buildMatchPatternFn_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])({
matchPattern: matchOrdinalNumberPattern,
parsePattern: parseOrdinalNumberPattern,
valueCallback: function (value) {
return parseInt(value, 10);
}
}),
era: Object(_lib_buildMatchFn_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])({
matchPatterns: matchEraPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseEraPatterns,
defaultParseWidth: 'any'
}),
quarter: Object(_lib_buildMatchFn_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])({
matchPatterns: matchQuarterPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseQuarterPatterns,
defaultParseWidth: 'any',
valueCallback: function (index) {
return index + 1;
}
}),
month: Object(_lib_buildMatchFn_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])({
matchPatterns: matchMonthPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseMonthPatterns,
defaultParseWidth: 'any'
}),
day: Object(_lib_buildMatchFn_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])({
matchPatterns: matchDayPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseDayPatterns,
defaultParseWidth: 'any'
}),
dayPeriod: Object(_lib_buildMatchFn_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])({
matchPatterns: matchDayPeriodPatterns,
defaultMatchWidth: 'any',
parsePatterns: parseDayPeriodPatterns,
defaultParseWidth: 'any'
})
};
/* harmony default export */ __webpack_exports__["default"] = (match);
/***/ }),
/***/ "./node_modules/date-fns/esm/locale/en-US/index.js":
/*!*********************************************************!*\
!*** ./node_modules/date-fns/esm/locale/en-US/index.js ***!
\*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_formatDistance_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_lib/formatDistance/index.js */ "./node_modules/date-fns/esm/locale/en-US/_lib/formatDistance/index.js");
/* harmony import */ var _lib_formatLong_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_lib/formatLong/index.js */ "./node_modules/date-fns/esm/locale/en-US/_lib/formatLong/index.js");
/* harmony import */ var _lib_formatRelative_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./_lib/formatRelative/index.js */ "./node_modules/date-fns/esm/locale/en-US/_lib/formatRelative/index.js");
/* harmony import */ var _lib_localize_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./_lib/localize/index.js */ "./node_modules/date-fns/esm/locale/en-US/_lib/localize/index.js");
/* harmony import */ var _lib_match_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./_lib/match/index.js */ "./node_modules/date-fns/esm/locale/en-US/_lib/match/index.js");
/**
* @type {Locale}
* @category Locales
* @summary English locale (United States).
* @language English
* @iso-639-2 eng
* @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp}
* @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss}
*/
var locale = {
formatDistance: _lib_formatDistance_index_js__WEBPACK_IMPORTED_MODULE_0__["default"],
formatLong: _lib_formatLong_index_js__WEBPACK_IMPORTED_MODULE_1__["default"],
formatRelative: _lib_formatRelative_index_js__WEBPACK_IMPORTED_MODULE_2__["default"],
localize: _lib_localize_index_js__WEBPACK_IMPORTED_MODULE_3__["default"],
match: _lib_match_index_js__WEBPACK_IMPORTED_MODULE_4__["default"],
options: {
weekStartsOn: 0
/* Sunday */
,
firstWeekContainsDate: 1
}
};
/* harmony default export */ __webpack_exports__["default"] = (locale);
/***/ }),
/***/ "./node_modules/date-fns/esm/max/index.js":
/*!************************************************!*\
!*** ./node_modules/date-fns/esm/max/index.js ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return max; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name max
* @category Common Helpers
* @summary Return the latest of the given dates.
*
* @description
* Return the latest of the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - `max` function now accepts an array of dates rather than spread arguments.
*
* ```javascript
* // Before v2.0.0
* var date1 = new Date(1989, 6, 10)
* var date2 = new Date(1987, 1, 11)
* var maxDate = max(date1, date2)
*
* // v2.0.0 onward:
* var dates = [new Date(1989, 6, 10), new Date(1987, 1, 11)]
* var maxDate = max(dates)
* ```
*
* @param {Date[]|Number[]} datesArray - the dates to compare
* @returns {Date} the latest of the dates
* @throws {TypeError} 1 argument required
*
* @example
* // Which of these dates is the latest?
* var result = max([
* new Date(1989, 6, 10),
* new Date(1987, 1, 11),
* new Date(1995, 6, 2),
* new Date(1990, 0, 1)
* ])
* //=> Sun Jul 02 1995 00:00:00
*/
function max(dirtyDatesArray) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var datesArray; // `dirtyDatesArray` is undefined or null
if (dirtyDatesArray == null) {
datesArray = []; // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method
} else if (typeof dirtyDatesArray.forEach === 'function') {
datesArray = dirtyDatesArray; // If `dirtyDatesArray` is Array-like Object, convert to Array. Otherwise, make it empty Array
} else {
datesArray = Array.prototype.slice.call(dirtyDatesArray);
}
var result;
datesArray.forEach(function (dirtyDate) {
var currentDate = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
if (result === undefined || result < currentDate || isNaN(currentDate)) {
result = currentDate;
}
});
return result;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/min/index.js":
/*!************************************************!*\
!*** ./node_modules/date-fns/esm/min/index.js ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return min; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name min
* @category Common Helpers
* @summary Return the earliest of the given dates.
*
* @description
* Return the earliest of the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - `min` function now accepts an array of dates rather than spread arguments.
*
* ```javascript
* // Before v2.0.0
* var date1 = new Date(1989, 6, 10)
* var date2 = new Date(1987, 1, 11)
* var minDate = min(date1, date2)
*
* // v2.0.0 onward:
* var dates = [new Date(1989, 6, 10), new Date(1987, 1, 11)]
* var minDate = min(dates)
* ```
*
* @param {Date[]|Number[]} datesArray - the dates to compare
* @returns {Date} the earliest of the dates
* @throws {TypeError} 1 argument required
*
* @example
* // Which of these dates is the earliest?
* var result = min([
* new Date(1989, 6, 10),
* new Date(1987, 1, 11),
* new Date(1995, 6, 2),
* new Date(1990, 0, 1)
* ])
* //=> Wed Feb 11 1987 00:00:00
*/
function min(dirtyDatesArray) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var datesArray; // `dirtyDatesArray` is undefined or null
if (dirtyDatesArray == null) {
datesArray = []; // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method
} else if (typeof dirtyDatesArray.forEach === 'function') {
datesArray = dirtyDatesArray; // If `dirtyDatesArray` is Array-like Object, convert to Array. Otherwise, make it empty Array
} else {
datesArray = Array.prototype.slice.call(dirtyDatesArray);
}
var result;
datesArray.forEach(function (dirtyDate) {
var currentDate = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
if (result === undefined || result > currentDate || isNaN(currentDate)) {
result = currentDate;
}
});
return result;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/parse/_lib/parsers/index.js":
/*!***************************************************************!*\
!*** ./node_modules/date-fns/esm/parse/_lib/parsers/index.js ***!
\***************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lib_getUTCWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../_lib/getUTCWeekYear/index.js */ "./node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js");
/* harmony import */ var _lib_setUTCDay_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../_lib/setUTCDay/index.js */ "./node_modules/date-fns/esm/_lib/setUTCDay/index.js");
/* harmony import */ var _lib_setUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../_lib/setUTCWeek/index.js */ "./node_modules/date-fns/esm/_lib/setUTCWeek/index.js");
/* harmony import */ var _lib_startOfUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../_lib/startOfUTCWeek/index.js */ "./node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js");
/* harmony import */ var _lib_setUTCISODay_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../_lib/setUTCISODay/index.js */ "./node_modules/date-fns/esm/_lib/setUTCISODay/index.js");
/* harmony import */ var _lib_setUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../_lib/setUTCISOWeek/index.js */ "./node_modules/date-fns/esm/_lib/setUTCISOWeek/index.js");
/* harmony import */ var _lib_startOfUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../_lib/startOfUTCISOWeek/index.js */ "./node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js");
var MILLISECONDS_IN_HOUR = 3600000;
var MILLISECONDS_IN_MINUTE = 60000;
var MILLISECONDS_IN_SECOND = 1000;
var numericPatterns = {
month: /^(1[0-2]|0?\d)/,
// 0 to 12
date: /^(3[0-1]|[0-2]?\d)/,
// 0 to 31
dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,
// 0 to 366
week: /^(5[0-3]|[0-4]?\d)/,
// 0 to 53
hour23h: /^(2[0-3]|[0-1]?\d)/,
// 0 to 23
hour24h: /^(2[0-4]|[0-1]?\d)/,
// 0 to 24
hour11h: /^(1[0-1]|0?\d)/,
// 0 to 11
hour12h: /^(1[0-2]|0?\d)/,
// 0 to 12
minute: /^[0-5]?\d/,
// 0 to 59
second: /^[0-5]?\d/,
// 0 to 59
singleDigit: /^\d/,
// 0 to 9
twoDigits: /^\d{1,2}/,
// 0 to 99
threeDigits: /^\d{1,3}/,
// 0 to 999
fourDigits: /^\d{1,4}/,
// 0 to 9999
anyDigitsSigned: /^-?\d+/,
singleDigitSigned: /^-?\d/,
// 0 to 9, -0 to -9
twoDigitsSigned: /^-?\d{1,2}/,
// 0 to 99, -0 to -99
threeDigitsSigned: /^-?\d{1,3}/,
// 0 to 999, -0 to -999
fourDigitsSigned: /^-?\d{1,4}/ // 0 to 9999, -0 to -9999
};
var timezonePatterns = {
basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/,
basic: /^([+-])(\d{2})(\d{2})|Z/,
basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,
extended: /^([+-])(\d{2}):(\d{2})|Z/,
extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/
};
function parseNumericPattern(pattern, string, valueCallback) {
var matchResult = string.match(pattern);
if (!matchResult) {
return null;
}
var value = parseInt(matchResult[0], 10);
return {
value: valueCallback ? valueCallback(value) : value,
rest: string.slice(matchResult[0].length)
};
}
function parseTimezonePattern(pattern, string) {
var matchResult = string.match(pattern);
if (!matchResult) {
return null;
} // Input is 'Z'
if (matchResult[0] === 'Z') {
return {
value: 0,
rest: string.slice(1)
};
}
var sign = matchResult[1] === '+' ? 1 : -1;
var hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0;
var minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0;
var seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0;
return {
value: sign * (hours * MILLISECONDS_IN_HOUR + minutes * MILLISECONDS_IN_MINUTE + seconds * MILLISECONDS_IN_SECOND),
rest: string.slice(matchResult[0].length)
};
}
function parseAnyDigitsSigned(string, valueCallback) {
return parseNumericPattern(numericPatterns.anyDigitsSigned, string, valueCallback);
}
function parseNDigits(n, string, valueCallback) {
switch (n) {
case 1:
return parseNumericPattern(numericPatterns.singleDigit, string, valueCallback);
case 2:
return parseNumericPattern(numericPatterns.twoDigits, string, valueCallback);
case 3:
return parseNumericPattern(numericPatterns.threeDigits, string, valueCallback);
case 4:
return parseNumericPattern(numericPatterns.fourDigits, string, valueCallback);
default:
return parseNumericPattern(new RegExp('^\\d{1,' + n + '}'), string, valueCallback);
}
}
function parseNDigitsSigned(n, string, valueCallback) {
switch (n) {
case 1:
return parseNumericPattern(numericPatterns.singleDigitSigned, string, valueCallback);
case 2:
return parseNumericPattern(numericPatterns.twoDigitsSigned, string, valueCallback);
case 3:
return parseNumericPattern(numericPatterns.threeDigitsSigned, string, valueCallback);
case 4:
return parseNumericPattern(numericPatterns.fourDigitsSigned, string, valueCallback);
default:
return parseNumericPattern(new RegExp('^-?\\d{1,' + n + '}'), string, valueCallback);
}
}
function dayPeriodEnumToHours(enumValue) {
switch (enumValue) {
case 'morning':
return 4;
case 'evening':
return 17;
case 'pm':
case 'noon':
case 'afternoon':
return 12;
case 'am':
case 'midnight':
case 'night':
default:
return 0;
}
}
function normalizeTwoDigitYear(twoDigitYear, currentYear) {
var isCommonEra = currentYear > 0; // Absolute number of the current year:
// 1 -> 1 AC
// 0 -> 1 BC
// -1 -> 2 BC
var absCurrentYear = isCommonEra ? currentYear : 1 - currentYear;
var result;
if (absCurrentYear <= 50) {
result = twoDigitYear || 100;
} else {
var rangeEnd = absCurrentYear + 50;
var rangeEndCentury = Math.floor(rangeEnd / 100) * 100;
var isPreviousCentury = twoDigitYear >= rangeEnd % 100;
result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0);
}
return isCommonEra ? result : 1 - result;
}
var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var DAYS_IN_MONTH_LEAP_YEAR = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // User for validation
function isLeapYearIndex(year) {
return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
}
/*
* | | Unit | | Unit |
* |-----|--------------------------------|-----|--------------------------------|
* | a | AM, PM | A* | Milliseconds in day |
* | b | AM, PM, noon, midnight | B | Flexible day period |
* | c | Stand-alone local day of week | C* | Localized hour w/ day period |
* | d | Day of month | D | Day of year |
* | e | Local day of week | E | Day of week |
* | f | | F* | Day of week in month |
* | g* | Modified Julian day | G | Era |
* | h | Hour [1-12] | H | Hour [0-23] |
* | i! | ISO day of week | I! | ISO week of year |
* | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
* | k | Hour [1-24] | K | Hour [0-11] |
* | l* | (deprecated) | L | Stand-alone month |
* | m | Minute | M | Month |
* | n | | N | |
* | o! | Ordinal number modifier | O* | Timezone (GMT) |
* | p | | P | |
* | q | Stand-alone quarter | Q | Quarter |
* | r* | Related Gregorian year | R! | ISO week-numbering year |
* | s | Second | S | Fraction of second |
* | t! | Seconds timestamp | T! | Milliseconds timestamp |
* | u | Extended year | U* | Cyclic year |
* | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
* | w | Local week of year | W* | Week of month |
* | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
* | y | Year (abs) | Y | Local week-numbering year |
* | z* | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
*
* Letters marked by * are not implemented but reserved by Unicode standard.
*
* Letters marked by ! are non-standard, but implemented by date-fns:
* - `o` modifies the previous token to turn it into an ordinal (see `parse` docs)
* - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
* i.e. 7 for Sunday, 1 for Monday, etc.
* - `I` is ISO week of year, as opposed to `w` which is local week of year.
* - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
* `R` is supposed to be used in conjunction with `I` and `i`
* for universal ISO week-numbering date, whereas
* `Y` is supposed to be used in conjunction with `w` and `e`
* for week-numbering date specific to the locale.
*/
var parsers = {
// Era
G: {
priority: 140,
parse: function (string, token, match, options) {
switch (token) {
// AD, BC
case 'G':
case 'GG':
case 'GGG':
return match.era(string, {
width: 'abbreviated'
}) || match.era(string, {
width: 'narrow'
});
// A, B
case 'GGGGG':
return match.era(string, {
width: 'narrow'
});
// Anno Domini, Before Christ
case 'GGGG':
default:
return match.era(string, {
width: 'wide'
}) || match.era(string, {
width: 'abbreviated'
}) || match.era(string, {
width: 'narrow'
});
}
},
set: function (date, flags, value, options) {
// Sets year 10 BC if BC, or 10 AC if AC
date.setUTCFullYear(value === 1 ? 10 : -9, 0, 1);
date.setUTCHours(0, 0, 0, 0);
return date;
}
},
// Year
y: {
// From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
// | Year | y | yy | yyy | yyyy | yyyyy |
// |----------|-------|----|-------|-------|-------|
// | AD 1 | 1 | 01 | 001 | 0001 | 00001 |
// | AD 12 | 12 | 12 | 012 | 0012 | 00012 |
// | AD 123 | 123 | 23 | 123 | 0123 | 00123 |
// | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |
// | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
priority: 130,
parse: function (string, token, match, options) {
var valueCallback = function (year) {
return {
year: year,
isTwoDigitYear: token === 'yy'
};
};
switch (token) {
case 'y':
return parseNDigits(4, string, valueCallback);
case 'yo':
return match.ordinalNumber(string, {
unit: 'year',
valueCallback: valueCallback
});
default:
return parseNDigits(token.length, string, valueCallback);
}
},
validate: function (date, value, options) {
return value.isTwoDigitYear || value.year > 0;
},
set: function (date, flags, value, options) {
var currentYear = Object(_lib_getUTCWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(date, options);
if (value.isTwoDigitYear) {
var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear);
date.setUTCFullYear(normalizedTwoDigitYear, 0, 1);
date.setUTCHours(0, 0, 0, 0);
return date;
}
var year = currentYear > 0 ? value.year : 1 - value.year;
date.setUTCFullYear(year, 0, 1);
date.setUTCHours(0, 0, 0, 0);
return date;
}
},
// Local week-numbering year
Y: {
priority: 130,
parse: function (string, token, match, options) {
var valueCallback = function (year) {
return {
year: year,
isTwoDigitYear: token === 'YY'
};
};
switch (token) {
case 'Y':
return parseNDigits(4, string, valueCallback);
case 'Yo':
return match.ordinalNumber(string, {
unit: 'year',
valueCallback: valueCallback
});
default:
return parseNDigits(token.length, string, valueCallback);
}
},
validate: function (date, value, options) {
return value.isTwoDigitYear || value.year > 0;
},
set: function (date, flags, value, options) {
var currentYear = date.getUTCFullYear();
if (value.isTwoDigitYear) {
var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear);
date.setUTCFullYear(normalizedTwoDigitYear, 0, options.firstWeekContainsDate);
date.setUTCHours(0, 0, 0, 0);
return Object(_lib_startOfUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(date, options);
}
var year = currentYear > 0 ? value.year : 1 - value.year;
date.setUTCFullYear(year, 0, options.firstWeekContainsDate);
date.setUTCHours(0, 0, 0, 0);
return Object(_lib_startOfUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(date, options);
}
},
// ISO week-numbering year
R: {
priority: 130,
parse: function (string, token, match, options) {
if (token === 'R') {
return parseNDigitsSigned(4, string);
}
return parseNDigitsSigned(token.length, string);
},
set: function (date, flags, value, options) {
var firstWeekOfYear = new Date(0);
firstWeekOfYear.setUTCFullYear(value, 0, 4);
firstWeekOfYear.setUTCHours(0, 0, 0, 0);
return Object(_lib_startOfUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(firstWeekOfYear);
}
},
// Extended year
u: {
priority: 130,
parse: function (string, token, match, options) {
if (token === 'u') {
return parseNDigitsSigned(4, string);
}
return parseNDigitsSigned(token.length, string);
},
set: function (date, flags, value, options) {
date.setUTCFullYear(value, 0, 1);
date.setUTCHours(0, 0, 0, 0);
return date;
}
},
// Quarter
Q: {
priority: 120,
parse: function (string, token, match, options) {
switch (token) {
// 1, 2, 3, 4
case 'Q':
case 'QQ':
// 01, 02, 03, 04
return parseNDigits(token.length, string);
// 1st, 2nd, 3rd, 4th
case 'Qo':
return match.ordinalNumber(string, {
unit: 'quarter'
});
// Q1, Q2, Q3, Q4
case 'QQQ':
return match.quarter(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.quarter(string, {
width: 'narrow',
context: 'formatting'
});
// 1, 2, 3, 4 (narrow quarter; could be not numerical)
case 'QQQQQ':
return match.quarter(string, {
width: 'narrow',
context: 'formatting'
});
// 1st quarter, 2nd quarter, ...
case 'QQQQ':
default:
return match.quarter(string, {
width: 'wide',
context: 'formatting'
}) || match.quarter(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.quarter(string, {
width: 'narrow',
context: 'formatting'
});
}
},
validate: function (date, value, options) {
return value >= 1 && value <= 4;
},
set: function (date, flags, value, options) {
date.setUTCMonth((value - 1) * 3, 1);
date.setUTCHours(0, 0, 0, 0);
return date;
}
},
// Stand-alone quarter
q: {
priority: 120,
parse: function (string, token, match, options) {
switch (token) {
// 1, 2, 3, 4
case 'q':
case 'qq':
// 01, 02, 03, 04
return parseNDigits(token.length, string);
// 1st, 2nd, 3rd, 4th
case 'qo':
return match.ordinalNumber(string, {
unit: 'quarter'
});
// Q1, Q2, Q3, Q4
case 'qqq':
return match.quarter(string, {
width: 'abbreviated',
context: 'standalone'
}) || match.quarter(string, {
width: 'narrow',
context: 'standalone'
});
// 1, 2, 3, 4 (narrow quarter; could be not numerical)
case 'qqqqq':
return match.quarter(string, {
width: 'narrow',
context: 'standalone'
});
// 1st quarter, 2nd quarter, ...
case 'qqqq':
default:
return match.quarter(string, {
width: 'wide',
context: 'standalone'
}) || match.quarter(string, {
width: 'abbreviated',
context: 'standalone'
}) || match.quarter(string, {
width: 'narrow',
context: 'standalone'
});
}
},
validate: function (date, value, options) {
return value >= 1 && value <= 4;
},
set: function (date, flags, value, options) {
date.setUTCMonth((value - 1) * 3, 1);
date.setUTCHours(0, 0, 0, 0);
return date;
}
},
// Month
M: {
priority: 110,
parse: function (string, token, match, options) {
var valueCallback = function (value) {
return value - 1;
};
switch (token) {
// 1, 2, ..., 12
case 'M':
return parseNumericPattern(numericPatterns.month, string, valueCallback);
// 01, 02, ..., 12
case 'MM':
return parseNDigits(2, string, valueCallback);
// 1st, 2nd, ..., 12th
case 'Mo':
return match.ordinalNumber(string, {
unit: 'month',
valueCallback: valueCallback
});
// Jan, Feb, ..., Dec
case 'MMM':
return match.month(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.month(string, {
width: 'narrow',
context: 'formatting'
});
// J, F, ..., D
case 'MMMMM':
return match.month(string, {
width: 'narrow',
context: 'formatting'
});
// January, February, ..., December
case 'MMMM':
default:
return match.month(string, {
width: 'wide',
context: 'formatting'
}) || match.month(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.month(string, {
width: 'narrow',
context: 'formatting'
});
}
},
validate: function (date, value, options) {
return value >= 0 && value <= 11;
},
set: function (date, flags, value, options) {
date.setUTCMonth(value, 1);
date.setUTCHours(0, 0, 0, 0);
return date;
}
},
// Stand-alone month
L: {
priority: 110,
parse: function (string, token, match, options) {
var valueCallback = function (value) {
return value - 1;
};
switch (token) {
// 1, 2, ..., 12
case 'L':
return parseNumericPattern(numericPatterns.month, string, valueCallback);
// 01, 02, ..., 12
case 'LL':
return parseNDigits(2, string, valueCallback);
// 1st, 2nd, ..., 12th
case 'Lo':
return match.ordinalNumber(string, {
unit: 'month',
valueCallback: valueCallback
});
// Jan, Feb, ..., Dec
case 'LLL':
return match.month(string, {
width: 'abbreviated',
context: 'standalone'
}) || match.month(string, {
width: 'narrow',
context: 'standalone'
});
// J, F, ..., D
case 'LLLLL':
return match.month(string, {
width: 'narrow',
context: 'standalone'
});
// January, February, ..., December
case 'LLLL':
default:
return match.month(string, {
width: 'wide',
context: 'standalone'
}) || match.month(string, {
width: 'abbreviated',
context: 'standalone'
}) || match.month(string, {
width: 'narrow',
context: 'standalone'
});
}
},
validate: function (date, value, options) {
return value >= 0 && value <= 11;
},
set: function (date, flags, value, options) {
date.setUTCMonth(value, 1);
date.setUTCHours(0, 0, 0, 0);
return date;
}
},
// Local week of year
w: {
priority: 100,
parse: function (string, token, match, options) {
switch (token) {
case 'w':
return parseNumericPattern(numericPatterns.week, string);
case 'wo':
return match.ordinalNumber(string, {
unit: 'week'
});
default:
return parseNDigits(token.length, string);
}
},
validate: function (date, value, options) {
return value >= 1 && value <= 53;
},
set: function (date, flags, value, options) {
return Object(_lib_startOfUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(Object(_lib_setUTCWeek_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date, value, options), options);
}
},
// ISO week of year
I: {
priority: 100,
parse: function (string, token, match, options) {
switch (token) {
case 'I':
return parseNumericPattern(numericPatterns.week, string);
case 'Io':
return match.ordinalNumber(string, {
unit: 'week'
});
default:
return parseNDigits(token.length, string);
}
},
validate: function (date, value, options) {
return value >= 1 && value <= 53;
},
set: function (date, flags, value, options) {
return Object(_lib_startOfUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_6__["default"])(Object(_lib_setUTCISOWeek_index_js__WEBPACK_IMPORTED_MODULE_5__["default"])(date, value, options), options);
}
},
// Day of the month
d: {
priority: 90,
parse: function (string, token, match, options) {
switch (token) {
case 'd':
return parseNumericPattern(numericPatterns.date, string);
case 'do':
return match.ordinalNumber(string, {
unit: 'date'
});
default:
return parseNDigits(token.length, string);
}
},
validate: function (date, value, options) {
var year = date.getUTCFullYear();
var isLeapYear = isLeapYearIndex(year);
var month = date.getUTCMonth();
if (isLeapYear) {
return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month];
} else {
return value >= 1 && value <= DAYS_IN_MONTH[month];
}
},
set: function (date, flags, value, options) {
date.setUTCDate(value);
date.setUTCHours(0, 0, 0, 0);
return date;
}
},
// Day of year
D: {
priority: 90,
parse: function (string, token, match, options) {
switch (token) {
case 'D':
case 'DD':
return parseNumericPattern(numericPatterns.dayOfYear, string);
case 'Do':
return match.ordinalNumber(string, {
unit: 'date'
});
default:
return parseNDigits(token.length, string);
}
},
validate: function (date, value, options) {
var year = date.getUTCFullYear();
var isLeapYear = isLeapYearIndex(year);
if (isLeapYear) {
return value >= 1 && value <= 366;
} else {
return value >= 1 && value <= 365;
}
},
set: function (date, flags, value, options) {
date.setUTCMonth(0, value);
date.setUTCHours(0, 0, 0, 0);
return date;
}
},
// Day of week
E: {
priority: 90,
parse: function (string, token, match, options) {
switch (token) {
// Tue
case 'E':
case 'EE':
case 'EEE':
return match.day(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.day(string, {
width: 'short',
context: 'formatting'
}) || match.day(string, {
width: 'narrow',
context: 'formatting'
});
// T
case 'EEEEE':
return match.day(string, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'EEEEEE':
return match.day(string, {
width: 'short',
context: 'formatting'
}) || match.day(string, {
width: 'narrow',
context: 'formatting'
});
// Tuesday
case 'EEEE':
default:
return match.day(string, {
width: 'wide',
context: 'formatting'
}) || match.day(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.day(string, {
width: 'short',
context: 'formatting'
}) || match.day(string, {
width: 'narrow',
context: 'formatting'
});
}
},
validate: function (date, value, options) {
return value >= 0 && value <= 6;
},
set: function (date, flags, value, options) {
date = Object(_lib_setUTCDay_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date, value, options);
date.setUTCHours(0, 0, 0, 0);
return date;
}
},
// Local day of week
e: {
priority: 90,
parse: function (string, token, match, options) {
var valueCallback = function (value) {
var wholeWeekDays = Math.floor((value - 1) / 7) * 7;
return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays;
};
switch (token) {
// 3
case 'e':
case 'ee':
// 03
return parseNDigits(token.length, string, valueCallback);
// 3rd
case 'eo':
return match.ordinalNumber(string, {
unit: 'day',
valueCallback: valueCallback
});
// Tue
case 'eee':
return match.day(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.day(string, {
width: 'short',
context: 'formatting'
}) || match.day(string, {
width: 'narrow',
context: 'formatting'
});
// T
case 'eeeee':
return match.day(string, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'eeeeee':
return match.day(string, {
width: 'short',
context: 'formatting'
}) || match.day(string, {
width: 'narrow',
context: 'formatting'
});
// Tuesday
case 'eeee':
default:
return match.day(string, {
width: 'wide',
context: 'formatting'
}) || match.day(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.day(string, {
width: 'short',
context: 'formatting'
}) || match.day(string, {
width: 'narrow',
context: 'formatting'
});
}
},
validate: function (date, value, options) {
return value >= 0 && value <= 6;
},
set: function (date, flags, value, options) {
date = Object(_lib_setUTCDay_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date, value, options);
date.setUTCHours(0, 0, 0, 0);
return date;
}
},
// Stand-alone local day of week
c: {
priority: 90,
parse: function (string, token, match, options) {
var valueCallback = function (value) {
var wholeWeekDays = Math.floor((value - 1) / 7) * 7;
return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays;
};
switch (token) {
// 3
case 'c':
case 'cc':
// 03
return parseNDigits(token.length, string, valueCallback);
// 3rd
case 'co':
return match.ordinalNumber(string, {
unit: 'day',
valueCallback: valueCallback
});
// Tue
case 'ccc':
return match.day(string, {
width: 'abbreviated',
context: 'standalone'
}) || match.day(string, {
width: 'short',
context: 'standalone'
}) || match.day(string, {
width: 'narrow',
context: 'standalone'
});
// T
case 'ccccc':
return match.day(string, {
width: 'narrow',
context: 'standalone'
});
// Tu
case 'cccccc':
return match.day(string, {
width: 'short',
context: 'standalone'
}) || match.day(string, {
width: 'narrow',
context: 'standalone'
});
// Tuesday
case 'cccc':
default:
return match.day(string, {
width: 'wide',
context: 'standalone'
}) || match.day(string, {
width: 'abbreviated',
context: 'standalone'
}) || match.day(string, {
width: 'short',
context: 'standalone'
}) || match.day(string, {
width: 'narrow',
context: 'standalone'
});
}
},
validate: function (date, value, options) {
return value >= 0 && value <= 6;
},
set: function (date, flags, value, options) {
date = Object(_lib_setUTCDay_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(date, value, options);
date.setUTCHours(0, 0, 0, 0);
return date;
}
},
// ISO day of week
i: {
priority: 90,
parse: function (string, token, match, options) {
var valueCallback = function (value) {
if (value === 0) {
return 7;
}
return value;
};
switch (token) {
// 2
case 'i':
case 'ii':
// 02
return parseNDigits(token.length, string);
// 2nd
case 'io':
return match.ordinalNumber(string, {
unit: 'day'
});
// Tue
case 'iii':
return match.day(string, {
width: 'abbreviated',
context: 'formatting',
valueCallback: valueCallback
}) || match.day(string, {
width: 'short',
context: 'formatting',
valueCallback: valueCallback
}) || match.day(string, {
width: 'narrow',
context: 'formatting',
valueCallback: valueCallback
});
// T
case 'iiiii':
return match.day(string, {
width: 'narrow',
context: 'formatting',
valueCallback: valueCallback
});
// Tu
case 'iiiiii':
return match.day(string, {
width: 'short',
context: 'formatting',
valueCallback: valueCallback
}) || match.day(string, {
width: 'narrow',
context: 'formatting',
valueCallback: valueCallback
});
// Tuesday
case 'iiii':
default:
return match.day(string, {
width: 'wide',
context: 'formatting',
valueCallback: valueCallback
}) || match.day(string, {
width: 'abbreviated',
context: 'formatting',
valueCallback: valueCallback
}) || match.day(string, {
width: 'short',
context: 'formatting',
valueCallback: valueCallback
}) || match.day(string, {
width: 'narrow',
context: 'formatting',
valueCallback: valueCallback
});
}
},
validate: function (date, value, options) {
return value >= 1 && value <= 7;
},
set: function (date, flags, value, options) {
date = Object(_lib_setUTCISODay_index_js__WEBPACK_IMPORTED_MODULE_4__["default"])(date, value, options);
date.setUTCHours(0, 0, 0, 0);
return date;
}
},
// AM or PM
a: {
priority: 80,
parse: function (string, token, match, options) {
switch (token) {
case 'a':
case 'aa':
case 'aaa':
return match.dayPeriod(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.dayPeriod(string, {
width: 'narrow',
context: 'formatting'
});
case 'aaaaa':
return match.dayPeriod(string, {
width: 'narrow',
context: 'formatting'
});
case 'aaaa':
default:
return match.dayPeriod(string, {
width: 'wide',
context: 'formatting'
}) || match.dayPeriod(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.dayPeriod(string, {
width: 'narrow',
context: 'formatting'
});
}
},
set: function (date, flags, value, options) {
date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0);
return date;
}
},
// AM, PM, midnight
b: {
priority: 80,
parse: function (string, token, match, options) {
switch (token) {
case 'b':
case 'bb':
case 'bbb':
return match.dayPeriod(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.dayPeriod(string, {
width: 'narrow',
context: 'formatting'
});
case 'bbbbb':
return match.dayPeriod(string, {
width: 'narrow',
context: 'formatting'
});
case 'bbbb':
default:
return match.dayPeriod(string, {
width: 'wide',
context: 'formatting'
}) || match.dayPeriod(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.dayPeriod(string, {
width: 'narrow',
context: 'formatting'
});
}
},
set: function (date, flags, value, options) {
date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0);
return date;
}
},
// in the morning, in the afternoon, in the evening, at night
B: {
priority: 80,
parse: function (string, token, match, options) {
switch (token) {
case 'B':
case 'BB':
case 'BBB':
return match.dayPeriod(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.dayPeriod(string, {
width: 'narrow',
context: 'formatting'
});
case 'BBBBB':
return match.dayPeriod(string, {
width: 'narrow',
context: 'formatting'
});
case 'BBBB':
default:
return match.dayPeriod(string, {
width: 'wide',
context: 'formatting'
}) || match.dayPeriod(string, {
width: 'abbreviated',
context: 'formatting'
}) || match.dayPeriod(string, {
width: 'narrow',
context: 'formatting'
});
}
},
set: function (date, flags, value, options) {
date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0);
return date;
}
},
// Hour [1-12]
h: {
priority: 70,
parse: function (string, token, match, options) {
switch (token) {
case 'h':
return parseNumericPattern(numericPatterns.hour12h, string);
case 'ho':
return match.ordinalNumber(string, {
unit: 'hour'
});
default:
return parseNDigits(token.length, string);
}
},
validate: function (date, value, options) {
return value >= 1 && value <= 12;
},
set: function (date, flags, value, options) {
var isPM = date.getUTCHours() >= 12;
if (isPM && value < 12) {
date.setUTCHours(value + 12, 0, 0, 0);
} else if (!isPM && value === 12) {
date.setUTCHours(0, 0, 0, 0);
} else {
date.setUTCHours(value, 0, 0, 0);
}
return date;
}
},
// Hour [0-23]
H: {
priority: 70,
parse: function (string, token, match, options) {
switch (token) {
case 'H':
return parseNumericPattern(numericPatterns.hour23h, string);
case 'Ho':
return match.ordinalNumber(string, {
unit: 'hour'
});
default:
return parseNDigits(token.length, string);
}
},
validate: function (date, value, options) {
return value >= 0 && value <= 23;
},
set: function (date, flags, value, options) {
date.setUTCHours(value, 0, 0, 0);
return date;
}
},
// Hour [0-11]
K: {
priority: 70,
parse: function (string, token, match, options) {
switch (token) {
case 'K':
return parseNumericPattern(numericPatterns.hour11h, string);
case 'Ko':
return match.ordinalNumber(string, {
unit: 'hour'
});
default:
return parseNDigits(token.length, string);
}
},
validate: function (date, value, options) {
return value >= 0 && value <= 11;
},
set: function (date, flags, value, options) {
var isPM = date.getUTCHours() >= 12;
if (isPM && value < 12) {
date.setUTCHours(value + 12, 0, 0, 0);
} else {
date.setUTCHours(value, 0, 0, 0);
}
return date;
}
},
// Hour [1-24]
k: {
priority: 70,
parse: function (string, token, match, options) {
switch (token) {
case 'k':
return parseNumericPattern(numericPatterns.hour24h, string);
case 'ko':
return match.ordinalNumber(string, {
unit: 'hour'
});
default:
return parseNDigits(token.length, string);
}
},
validate: function (date, value, options) {
return value >= 1 && value <= 24;
},
set: function (date, flags, value, options) {
var hours = value <= 24 ? value % 24 : value;
date.setUTCHours(hours, 0, 0, 0);
return date;
}
},
// Minute
m: {
priority: 60,
parse: function (string, token, match, options) {
switch (token) {
case 'm':
return parseNumericPattern(numericPatterns.minute, string);
case 'mo':
return match.ordinalNumber(string, {
unit: 'minute'
});
default:
return parseNDigits(token.length, string);
}
},
validate: function (date, value, options) {
return value >= 0 && value <= 59;
},
set: function (date, flags, value, options) {
date.setUTCMinutes(value, 0, 0);
return date;
}
},
// Second
s: {
priority: 50,
parse: function (string, token, match, options) {
switch (token) {
case 's':
return parseNumericPattern(numericPatterns.second, string);
case 'so':
return match.ordinalNumber(string, {
unit: 'second'
});
default:
return parseNDigits(token.length, string);
}
},
validate: function (date, value, options) {
return value >= 0 && value <= 59;
},
set: function (date, flags, value, options) {
date.setUTCSeconds(value, 0);
return date;
}
},
// Fraction of second
S: {
priority: 30,
parse: function (string, token, match, options) {
var valueCallback = function (value) {
return Math.floor(value * Math.pow(10, -token.length + 3));
};
return parseNDigits(token.length, string, valueCallback);
},
set: function (date, flags, value, options) {
date.setUTCMilliseconds(value);
return date;
}
},
// Timezone (ISO-8601. +00:00 is `'Z'`)
X: {
priority: 10,
parse: function (string, token, match, options) {
switch (token) {
case 'X':
return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, string);
case 'XX':
return parseTimezonePattern(timezonePatterns.basic, string);
case 'XXXX':
return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, string);
case 'XXXXX':
return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, string);
case 'XXX':
default:
return parseTimezonePattern(timezonePatterns.extended, string);
}
},
set: function (date, flags, value, options) {
if (flags.timestampIsSet) {
return date;
}
return new Date(date.getTime() - value);
}
},
// Timezone (ISO-8601)
x: {
priority: 10,
parse: function (string, token, match, options) {
switch (token) {
case 'x':
return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, string);
case 'xx':
return parseTimezonePattern(timezonePatterns.basic, string);
case 'xxxx':
return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, string);
case 'xxxxx':
return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, string);
case 'xxx':
default:
return parseTimezonePattern(timezonePatterns.extended, string);
}
},
set: function (date, flags, value, options) {
if (flags.timestampIsSet) {
return date;
}
return new Date(date.getTime() - value);
}
},
// Seconds timestamp
t: {
priority: 40,
parse: function (string, token, match, options) {
return parseAnyDigitsSigned(string);
},
set: function (date, flags, value, options) {
return [new Date(value * 1000), {
timestampIsSet: true
}];
}
},
// Milliseconds timestamp
T: {
priority: 20,
parse: function (string, token, match, options) {
return parseAnyDigitsSigned(string);
},
set: function (date, flags, value, options) {
return [new Date(value), {
timestampIsSet: true
}];
}
}
};
/* harmony default export */ __webpack_exports__["default"] = (parsers);
/***/ }),
/***/ "./node_modules/date-fns/esm/parse/index.js":
/*!**************************************************!*\
!*** ./node_modules/date-fns/esm/parse/index.js ***!
\**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return parse; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _lib_assign_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../_lib/assign/index.js */ "./node_modules/date-fns/esm/_lib/assign/index.js");
/* harmony import */ var _lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../_lib/getTimezoneOffsetInMilliseconds/index.js */ "./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _subMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../subMilliseconds/index.js */ "./node_modules/date-fns/esm/subMilliseconds/index.js");
/* harmony import */ var _locale_en_US_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../locale/en-US/index.js */ "./node_modules/date-fns/esm/locale/en-US/index.js");
/* harmony import */ var _lib_parsers_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./_lib/parsers/index.js */ "./node_modules/date-fns/esm/parse/_lib/parsers/index.js");
/* harmony import */ var _lib_protectedTokens_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../_lib/protectedTokens/index.js */ "./node_modules/date-fns/esm/_lib/protectedTokens/index.js");
var TIMEZONE_UNIT_PRIORITY = 10; // This RegExp consists of three parts separated by `|`:
// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
// (one of the certain letters followed by `o`)
// - (\w)\1* matches any sequences of the same letter
// - '' matches two quote characters in a row
// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
// except a single quote symbol, which ends the sequence.
// Two quote characters do not end the sequence.
// If there is no matching single quote
// then the sequence will continue until the end of the string.
// - . matches any single character unmatched by previous parts of the RegExps
var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
var escapedStringRegExp = /^'(.*?)'?$/;
var doubleQuoteRegExp = /''/g;
var notWhitespaceRegExp = /\S/;
/**
* @name parse
* @category Common Helpers
* @summary Parse the date.
*
* @description
* Return the date parsed from string using the given format string.
*
* > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
* > See: https://git.io/fxCyr
*
* The characters in the format string wrapped between two single quotes characters (') are escaped.
* Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
*
* Format of the format string is based on Unicode Technical Standard #35:
* https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
* with a few additions (see note 5 below the table).
*
* Accepted format string patterns:
* | Unit |Prior| Pattern | Result examples | Notes |
* |---------------------------------|-----|---------|-----------------------------------|-------|
* | Era | 140 | G..GGG | AD, BC | |
* | | | GGGG | Anno Domini, Before Christ | 2 |
* | | | GGGGG | A, B | |
* | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 |
* | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 |
* | | | yy | 44, 01, 00, 17 | 4 |
* | | | yyy | 044, 001, 123, 999 | 4 |
* | | | yyyy | 0044, 0001, 1900, 2017 | 4 |
* | | | yyyyy | ... | 2,4 |
* | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 |
* | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 |
* | | | YY | 44, 01, 00, 17 | 4,6 |
* | | | YYY | 044, 001, 123, 999 | 4 |
* | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 |
* | | | YYYYY | ... | 2,4 |
* | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 |
* | | | RR | -43, 01, 00, 17 | 4,5 |
* | | | RRR | -043, 001, 123, 999, -999 | 4,5 |
* | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 |
* | | | RRRRR | ... | 2,4,5 |
* | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 |
* | | | uu | -43, 01, 99, -99 | 4 |
* | | | uuu | -043, 001, 123, 999, -999 | 4 |
* | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 |
* | | | uuuuu | ... | 2,4 |
* | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | |
* | | | Qo | 1st, 2nd, 3rd, 4th | 5 |
* | | | QQ | 01, 02, 03, 04 | |
* | | | QQQ | Q1, Q2, Q3, Q4 | |
* | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
* | | | QQQQQ | 1, 2, 3, 4 | 4 |
* | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | |
* | | | qo | 1st, 2nd, 3rd, 4th | 5 |
* | | | qq | 01, 02, 03, 04 | |
* | | | qqq | Q1, Q2, Q3, Q4 | |
* | | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
* | | | qqqqq | 1, 2, 3, 4 | 3 |
* | Month (formatting) | 110 | M | 1, 2, ..., 12 | |
* | | | Mo | 1st, 2nd, ..., 12th | 5 |
* | | | MM | 01, 02, ..., 12 | |
* | | | MMM | Jan, Feb, ..., Dec | |
* | | | MMMM | January, February, ..., December | 2 |
* | | | MMMMM | J, F, ..., D | |
* | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | |
* | | | Lo | 1st, 2nd, ..., 12th | 5 |
* | | | LL | 01, 02, ..., 12 | |
* | | | LLL | Jan, Feb, ..., Dec | |
* | | | LLLL | January, February, ..., December | 2 |
* | | | LLLLL | J, F, ..., D | |
* | Local week of year | 100 | w | 1, 2, ..., 53 | |
* | | | wo | 1st, 2nd, ..., 53th | 5 |
* | | | ww | 01, 02, ..., 53 | |
* | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 |
* | | | Io | 1st, 2nd, ..., 53th | 5 |
* | | | II | 01, 02, ..., 53 | 5 |
* | Day of month | 90 | d | 1, 2, ..., 31 | |
* | | | do | 1st, 2nd, ..., 31st | 5 |
* | | | dd | 01, 02, ..., 31 | |
* | Day of year | 90 | D | 1, 2, ..., 365, 366 | 6 |
* | | | Do | 1st, 2nd, ..., 365th, 366th | 5 |
* | | | DD | 01, 02, ..., 365, 366 | 6 |
* | | | DDD | 001, 002, ..., 365, 366 | |
* | | | DDDD | ... | 2 |
* | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Su | |
* | | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
* | | | EEEEE | M, T, W, T, F, S, S | |
* | | | EEEEEE | Mo, Tu, We, Th, Fr, Su, Sa | |
* | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 |
* | | | io | 1st, 2nd, ..., 7th | 5 |
* | | | ii | 01, 02, ..., 07 | 5 |
* | | | iii | Mon, Tue, Wed, ..., Su | 5 |
* | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 |
* | | | iiiii | M, T, W, T, F, S, S | 5 |
* | | | iiiiii | Mo, Tu, We, Th, Fr, Su, Sa | 5 |
* | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | |
* | | | eo | 2nd, 3rd, ..., 1st | 5 |
* | | | ee | 02, 03, ..., 01 | |
* | | | eee | Mon, Tue, Wed, ..., Su | |
* | | | eeee | Monday, Tuesday, ..., Sunday | 2 |
* | | | eeeee | M, T, W, T, F, S, S | |
* | | | eeeeee | Mo, Tu, We, Th, Fr, Su, Sa | |
* | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | |
* | | | co | 2nd, 3rd, ..., 1st | 5 |
* | | | cc | 02, 03, ..., 01 | |
* | | | ccc | Mon, Tue, Wed, ..., Su | |
* | | | cccc | Monday, Tuesday, ..., Sunday | 2 |
* | | | ccccc | M, T, W, T, F, S, S | |
* | | | cccccc | Mo, Tu, We, Th, Fr, Su, Sa | |
* | AM, PM | 80 | a..aaa | AM, PM | |
* | | | aaaa | a.m., p.m. | 2 |
* | | | aaaaa | a, p | |
* | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | |
* | | | bbbb | a.m., p.m., noon, midnight | 2 |
* | | | bbbbb | a, p, n, mi | |
* | Flexible day period | 80 | B..BBB | at night, in the morning, ... | |
* | | | BBBB | at night, in the morning, ... | 2 |
* | | | BBBBB | at night, in the morning, ... | |
* | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | |
* | | | ho | 1st, 2nd, ..., 11th, 12th | 5 |
* | | | hh | 01, 02, ..., 11, 12 | |
* | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | |
* | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 |
* | | | HH | 00, 01, 02, ..., 23 | |
* | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | |
* | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 |
* | | | KK | 1, 2, ..., 11, 0 | |
* | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | |
* | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 |
* | | | kk | 24, 01, 02, ..., 23 | |
* | Minute | 60 | m | 0, 1, ..., 59 | |
* | | | mo | 0th, 1st, ..., 59th | 5 |
* | | | mm | 00, 01, ..., 59 | |
* | Second | 50 | s | 0, 1, ..., 59 | |
* | | | so | 0th, 1st, ..., 59th | 5 |
* | | | ss | 00, 01, ..., 59 | |
* | Seconds timestamp | 40 | t | 512969520 | |
* | | | tt | ... | 2 |
* | Fraction of second | 30 | S | 0, 1, ..., 9 | |
* | | | SS | 00, 01, ..., 99 | |
* | | | SSS | 000, 0001, ..., 999 | |
* | | | SSSS | ... | 2 |
* | Milliseconds timestamp | 20 | T | 512969520900 | |
* | | | TT | ... | 2 |
* | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | |
* | | | XX | -0800, +0530, Z | |
* | | | XXX | -08:00, +05:30, Z | |
* | | | XXXX | -0800, +0530, Z, +123456 | 2 |
* | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
* | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | |
* | | | xx | -0800, +0530, +0000 | |
* | | | xxx | -08:00, +05:30, +00:00 | 2 |
* | | | xxxx | -0800, +0530, +0000, +123456 | |
* | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
* Notes:
* 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
* are the same as "stand-alone" units, but are different in some languages.
* "Formatting" units are declined according to the rules of the language
* in the context of a date. "Stand-alone" units are always nominative singular.
* In `format` function, they will produce different result:
*
* `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
*
* `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
*
* `parse` will try to match both formatting and stand-alone units interchangably.
*
* 2. Any sequence of the identical letters is a pattern, unless it is escaped by
* the single quote characters (see below).
* If the sequence is longer than listed in table:
* - for numerical units (`yyyyyyyy`) `parse` will try to match a number
* as wide as the sequence
* - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit.
* These variations are marked with "2" in the last column of the table.
*
* 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
* These tokens represent the shortest form of the quarter.
*
* 4. The main difference between `y` and `u` patterns are B.C. years:
*
* | Year | `y` | `u` |
* |------|-----|-----|
* | AC 1 | 1 | 1 |
* | BC 1 | 1 | 0 |
* | BC 2 | 2 | -1 |
*
* Also `yy` will try to guess the century of two digit year by proximity with `baseDate`:
*
* `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00`
*
* `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00`
*
* while `uu` will just assign the year as is:
*
* `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00`
*
* `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00`
*
* The same difference is true for local and ISO week-numbering years (`Y` and `R`),
* except local week-numbering years are dependent on `options.weekStartsOn`
* and `options.firstWeekContainsDate` (compare [setISOWeekYear]{@link https://date-fns.org/docs/setISOWeekYear}
* and [setWeekYear]{@link https://date-fns.org/docs/setWeekYear}).
*
* 5. These patterns are not in the Unicode Technical Standard #35:
* - `i`: ISO day of week
* - `I`: ISO week of year
* - `R`: ISO week-numbering year
* - `o`: ordinal number modifier
*
* 6. These tokens are often confused with others. See: https://git.io/fxCyr
*
* Values will be assigned to the date in the descending order of its unit's priority.
* Units of an equal priority overwrite each other in the order of appearance.
*
* If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year),
* the values will be taken from 3rd argument `baseDate` which works as a context of parsing.
*
* `baseDate` must be passed for correct work of the function.
* If you're not sure which `baseDate` to supply, create a new instance of Date:
* `parse('02/11/2014', 'MM/dd/yyyy', new Date())`
* In this case parsing will be done in the context of the current date.
* If `baseDate` is `Invalid Date` or a value not convertible to valid `Date`,
* then `Invalid Date` will be returned.
*
* The result may vary by locale.
*
* If `formatString` matches with `dateString` but does not provides tokens, `baseDate` will be returned.
*
* If parsing failed, `Invalid Date` will be returned.
* Invalid Date is a Date, whose time value is NaN.
* Time value of Date: http://es5.github.io/#x15.9.1.1
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - Old `parse` was renamed to `toDate`.
* Now `parse` is a new function which parses a string using a provided format.
*
* ```javascript
* // Before v2.0.0
* parse('2016-01-01')
*
* // v2.0.0 onward
* toDate('2016-01-01')
* parse('2016-01-01', 'yyyy-MM-dd', new Date())
* ```
*
* @param {String} dateString - the string to parse
* @param {String} formatString - the string of tokens
* @param {Date|Number} baseDate - defines values missing from the parsed dateString
* @param {Object} [options] - an object with options.
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year
* @param {Boolean} [options.awareOfUnicodeTokens=false] - if true, allows usage of Unicode tokens causes confusion:
* - Some of the day of year tokens (`D`, `DD`) that are confused with the day of month tokens (`d`, `dd`).
* - Some of the local week-numbering year tokens (`YY`, `YYYY`) that are confused with the calendar year tokens (`yy`, `yyyy`).
* See: https://git.io/fxCyr
* @returns {Date} the parsed date
* @throws {TypeError} 3 arguments required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
* @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
* @throws {RangeError} `options.locale` must contain `match` property
* @throws {RangeError} `options.awareOfUnicodeTokens` must be set to `true` to use `XX` token; see: https://git.io/fxCyr
*
* @example
* // Parse 11 February 2014 from middle-endian format:
* var result = parse('02/11/2014', 'MM/dd/yyyy', new Date())
* //=> Tue Feb 11 2014 00:00:00
*
* @example
* // Parse 28th of February in Esperanto locale in the context of 2010 year:
* import eo from 'date-fns/locale/eo'
* var result = parse('28-a de februaro', "do 'de' MMMM", new Date(2010, 0, 1), {
* locale: eo
* })
* //=> Sun Feb 28 2010 00:00:00
*/
function parse(dirtyDateString, dirtyFormatString, dirtyBaseDate, dirtyOptions) {
if (arguments.length < 3) {
throw new TypeError('3 arguments required, but only ' + arguments.length + ' present');
}
var dateString = String(dirtyDateString);
var formatString = String(dirtyFormatString);
var options = dirtyOptions || {};
var locale = options.locale || _locale_en_US_index_js__WEBPACK_IMPORTED_MODULE_5__["default"];
if (!locale.match) {
throw new RangeError('locale must contain match property');
}
var localeFirstWeekContainsDate = locale.options && locale.options.firstWeekContainsDate;
var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeFirstWeekContainsDate);
var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.firstWeekContainsDate); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
}
var localeWeekStartsOn = locale.options && locale.options.weekStartsOn;
var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeWeekStartsOn);
var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
if (formatString === '') {
if (dateString === '') {
return Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(dirtyBaseDate);
} else {
return new Date(NaN);
}
}
var subFnOptions = {
firstWeekContainsDate: firstWeekContainsDate,
weekStartsOn: weekStartsOn,
locale: locale
}; // If timezone isn't specified, it will be set to the system timezone
var setters = [{
priority: TIMEZONE_UNIT_PRIORITY,
set: dateToSystemTimezone,
index: 0
}];
var i;
var tokens = formatString.match(formattingTokensRegExp);
for (i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (!options.awareOfUnicodeTokens && Object(_lib_protectedTokens_index_js__WEBPACK_IMPORTED_MODULE_7__["isProtectedToken"])(token)) {
Object(_lib_protectedTokens_index_js__WEBPACK_IMPORTED_MODULE_7__["throwProtectedError"])(token);
}
var firstCharacter = token[0];
var parser = _lib_parsers_index_js__WEBPACK_IMPORTED_MODULE_6__["default"][firstCharacter];
if (parser) {
var parseResult = parser.parse(dateString, token, locale.match, subFnOptions);
if (!parseResult) {
return new Date(NaN);
}
setters.push({
priority: parser.priority,
set: parser.set,
validate: parser.validate,
value: parseResult.value,
index: setters.length
});
dateString = parseResult.rest;
} else {
// Replace two single quote characters with one single quote character
if (token === "''") {
token = "'";
} else if (firstCharacter === "'") {
token = cleanEscapedString(token);
} // Cut token from string, or, if string doesn't match the token, return Invalid Date
if (dateString.indexOf(token) === 0) {
dateString = dateString.slice(token.length);
} else {
return new Date(NaN);
}
}
} // Check if the remaining input contains something other than whitespace
if (dateString.length > 0 && notWhitespaceRegExp.test(dateString)) {
return new Date(NaN);
}
var uniquePrioritySetters = setters.map(function (setter) {
return setter.priority;
}).sort(function (a, b) {
return b - a;
}).filter(function (priority, index, array) {
return array.indexOf(priority) === index;
}).map(function (priority) {
return setters.filter(function (setter) {
return setter.priority === priority;
}).reverse();
}).map(function (setterArray) {
return setterArray[0];
});
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(dirtyBaseDate);
if (isNaN(date)) {
return new Date(NaN);
} // Convert the date in system timezone to the same date in UTC+00:00 timezone.
// This ensures that when UTC functions will be implemented, locales will be compatible with them.
// See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/37
var utcDate = Object(_subMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_4__["default"])(date, Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date));
var flags = {};
for (i = 0; i < uniquePrioritySetters.length; i++) {
var setter = uniquePrioritySetters[i];
if (setter.validate && !setter.validate(utcDate, setter.value, subFnOptions)) {
return new Date(NaN);
}
var result = setter.set(utcDate, flags, setter.value, subFnOptions); // Result is tuple (date, flags)
if (result[0]) {
utcDate = result[0];
Object(_lib_assign_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(flags, result[1]); // Result is date
} else {
utcDate = result;
}
}
return utcDate;
}
function dateToSystemTimezone(date, flags) {
if (flags.timestampIsSet) {
return date;
}
var convertedDate = new Date(0);
convertedDate.setFullYear(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
convertedDate.setHours(date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
return convertedDate;
}
function cleanEscapedString(input) {
return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'");
}
/***/ }),
/***/ "./node_modules/date-fns/esm/parseISO/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/parseISO/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return parseISO; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../_lib/getTimezoneOffsetInMilliseconds/index.js */ "./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js");
var MILLISECONDS_IN_HOUR = 3600000;
var MILLISECONDS_IN_MINUTE = 60000;
var DEFAULT_ADDITIONAL_DIGITS = 2;
var patterns = {
dateTimeDelimiter: /[T ]/,
timeZoneDelimiter: /[Z ]/i,
timezone: /([Z+-].*)$/
};
var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/;
var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/;
var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/;
/**
* @name parseISO
* @category Common Helpers
* @summary Parse ISO string
*
* @description
* Parse the given string in ISO 8601 format and return an instance of Date.
*
* Function accepts complete ISO 8601 formats as well as partial implementations.
* ISO 8601: http://en.wikipedia.org/wiki/ISO_8601
*
* If the argument isn't a string, the function cannot parse the string or
* the values are invalid, it returns Invalid Date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The previous `parse` implementation was renamed to `parseISO`.
*
* ```javascript
* // Before v2.0.0
* parse('2016-01-01')
*
* // v2.0.0 onward
* parseISO('2016-01-01')
* ```
*
* - `parseISO` now validates separate date and time values in ISO-8601 strings
* and returns `Invalid Date` if the date is invalid.
*
* ```javascript
* parseISO('2018-13-32')
* //=> Invalid Date
* ```
*
* - `parseISO` now doesn't fall back to `new Date` constructor
* if it fails to parse a string argument. Instead, it returns `Invalid Date`.
*
* @param {String} argument - the value to convert
* @param {Object} [options] - an object with options.
* @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format
* @returns {Date} the parsed date in the local time zone
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2
*
* @example
* // Convert string '2014-02-11T11:30:30' to date:
* var result = parseISO('2014-02-11T11:30:30')
* //=> Tue Feb 11 2014 11:30:30
*
* @example
* // Convert string '+02014101' to date,
* // if the additional number of digits in the extended year format is 1:
* var result = parseISO('+02014101', { additionalDigits: 1 })
* //=> Fri Apr 11 2014 00:00:00
*/
function parseISO(argument, dirtyOptions) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var options = dirtyOptions || {};
var additionalDigits = options.additionalDigits == null ? DEFAULT_ADDITIONAL_DIGITS : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.additionalDigits);
if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) {
throw new RangeError('additionalDigits must be 0, 1 or 2');
}
if (!(typeof argument === 'string' || Object.prototype.toString.call(argument) === '[object String]')) {
return new Date(NaN);
}
var dateStrings = splitDateString(argument);
var parseYearResult = parseYear(dateStrings.date, additionalDigits);
var date = parseDate(parseYearResult.restDateString, parseYearResult.year);
if (isNaN(date) || !date) {
return new Date(NaN);
}
var timestamp = date.getTime();
var time = 0;
var offset;
if (dateStrings.time) {
time = parseTime(dateStrings.time);
if (isNaN(time)) {
return new Date(NaN);
}
}
if (dateStrings.timezone) {
offset = parseTimezone(dateStrings.timezone);
if (isNaN(offset)) {
return new Date(NaN);
}
} else {
var fullTime = timestamp + time;
var fullTimeDate = new Date(fullTime);
offset = Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(fullTimeDate); // Adjust time when it's coming from DST
var fullTimeDateNextDay = new Date(fullTime);
fullTimeDateNextDay.setDate(fullTimeDate.getDate() + 1);
var offsetDiff = Object(_lib_getTimezoneOffsetInMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(fullTimeDateNextDay) - offset;
if (offsetDiff > 0) {
offset += offsetDiff;
}
}
return new Date(timestamp + time + offset);
}
function splitDateString(dateString) {
var dateStrings = {};
var array = dateString.split(patterns.dateTimeDelimiter);
var timeString;
if (/:/.test(array[0])) {
dateStrings.date = null;
timeString = array[0];
} else {
dateStrings.date = array[0];
timeString = array[1];
if (patterns.timeZoneDelimiter.test(dateStrings.date)) {
dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];
timeString = dateString.substr(dateStrings.date.length, dateString.length);
}
}
if (timeString) {
var token = patterns.timezone.exec(timeString);
if (token) {
dateStrings.time = timeString.replace(token[1], '');
dateStrings.timezone = token[1];
} else {
dateStrings.time = timeString;
}
}
return dateStrings;
}
function parseYear(dateString, additionalDigits) {
var regex = new RegExp('^(?:(\\d{4}|[+-]\\d{' + (4 + additionalDigits) + '})|(\\d{2}|[+-]\\d{' + (2 + additionalDigits) + '})$)');
var captures = dateString.match(regex); // Invalid ISO-formatted year
if (!captures) return {
year: null
};
var year = captures[1] && parseInt(captures[1]);
var century = captures[2] && parseInt(captures[2]);
return {
year: century == null ? year : century * 100,
restDateString: dateString.slice((captures[1] || captures[2]).length)
};
}
function parseDate(dateString, year) {
// Invalid ISO-formatted year
if (year === null) return null;
var captures = dateString.match(dateRegex); // Invalid ISO-formatted string
if (!captures) return null;
var isWeekDate = !!captures[4];
var dayOfYear = parseDateUnit(captures[1]);
var month = parseDateUnit(captures[2]) - 1;
var day = parseDateUnit(captures[3]);
var week = parseDateUnit(captures[4]) - 1;
var dayOfWeek = parseDateUnit(captures[5]) - 1;
if (isWeekDate) {
if (!validateWeekDate(year, week, dayOfWeek)) {
return new Date(NaN);
}
return dayOfISOWeekYear(year, week, dayOfWeek);
} else {
var date = new Date(0);
if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) {
return new Date(NaN);
}
date.setUTCFullYear(year, month, Math.max(dayOfYear, day));
return date;
}
}
function parseDateUnit(value) {
return value ? parseInt(value) : 1;
}
function parseTime(timeString) {
var captures = timeString.match(timeRegex);
if (!captures) return null; // Invalid ISO-formatted time
var hours = parseTimeUnit(captures[1]);
var minutes = parseTimeUnit(captures[2]);
var seconds = parseTimeUnit(captures[3]);
if (!validateTime(hours, minutes, seconds)) {
return NaN;
}
return hours % 24 * MILLISECONDS_IN_HOUR + minutes * MILLISECONDS_IN_MINUTE + seconds * 1000;
}
function parseTimeUnit(value) {
return value && parseFloat(value.replace(',', '.')) || 0;
}
function parseTimezone(timezoneString) {
if (timezoneString === 'Z') return 0;
var captures = timezoneString.match(timezoneRegex);
if (!captures) return 0;
var sign = captures[1] === '+' ? -1 : 1;
var hours = parseInt(captures[2]);
var minutes = captures[3] && parseInt(captures[3]) || 0;
if (!validateTimezone(hours, minutes)) {
return NaN;
}
return sign * (hours * MILLISECONDS_IN_HOUR + minutes * MILLISECONDS_IN_MINUTE);
}
function dayOfISOWeekYear(isoWeekYear, week, day) {
var date = new Date(0);
date.setUTCFullYear(isoWeekYear, 0, 4);
var fourthOfJanuaryDay = date.getUTCDay() || 7;
var diff = (week || 0) * 7 + (day || 0) + 1 - fourthOfJanuaryDay;
date.setUTCDate(date.getUTCDate() + diff);
return date;
} // Validation functions
// February is null to handle the leap year (using ||)
var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function isLeapYearIndex(year) {
return year % 400 === 0 || year % 4 === 0 && year % 100;
}
function validateDate(year, month, date) {
return !(month < 0 || month > 11 || date < 1 || date > (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28)));
}
function validateDayOfYearDate(year, dayOfYear) {
return !(dayOfYear < 1 || dayOfYear > (isLeapYearIndex(year) ? 366 : 365));
}
function validateWeekDate(_year, week, day) {
return !(week < 0 || week > 52 || day < 0 || day > 6);
}
function validateTime(hours, minutes, seconds) {
return !(seconds < 0 || seconds >= 60 || minutes < 0 || minutes >= 60 || hours < 0 || hours >= 25);
}
function validateTimezone(_hours, minutes) {
return !(minutes < 0 || minutes > 59);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/roundToNearestMinutes/index.js":
/*!******************************************************************!*\
!*** ./node_modules/date-fns/esm/roundToNearestMinutes/index.js ***!
\******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return roundToNearestMinutes; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/**
* @name roundToNearestMinutes
* @category Minute Helpers
* @summary Rounds the given date to the nearest minute
*
* @description
* Rounds the given date to the nearest minute
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to round
* @param {Object} [options] - an object with options.
* @param {Number} [options.nearestTo=1] - passed to `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
* @returns {Date} the new date rounded to the closest minute
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.nearestTo` must be between 1 and 30
*
* @example
* // Round 10 July 2014 12:12:34 to nearest minute:
* var result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34))
* //=> Thu Jul 10 2014 12:13:00
*/
function roundToNearestMinutes(dirtyDate, options) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only none provided present');
}
var nearestTo = options && 'nearestTo' in options ? Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(options.nearestTo) : 1;
if (nearestTo < 1 || nearestTo > 30) {
throw new RangeError('`options.nearestTo` must be between 1 and 30');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var seconds = date.getSeconds(); // relevant if nearestTo is 1, which is the default case
var minutes = date.getMinutes() + seconds / 60;
var roundedMinutes = Math.floor(minutes / nearestTo) * nearestTo;
var remainderMinutes = minutes % nearestTo;
var addedMinutes = Math.round(remainderMinutes / nearestTo) * nearestTo;
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), roundedMinutes + addedMinutes);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setDate/index.js":
/*!****************************************************!*\
!*** ./node_modules/date-fns/esm/setDate/index.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setDate; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name setDate
* @category Day Helpers
* @summary Set the day of the month to the given date.
*
* @description
* Set the day of the month to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} dayOfMonth - the day of the month of the new date
* @returns {Date} the new date with the day of the month set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set the 30th day of the month to 1 September 2014:
* var result = setDate(new Date(2014, 8, 1), 30)
* //=> Tue Sep 30 2014 00:00:00
*/
function setDate(dirtyDate, dirtyDayOfMonth) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var dayOfMonth = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDayOfMonth);
date.setDate(dayOfMonth);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setDay/index.js":
/*!***************************************************!*\
!*** ./node_modules/date-fns/esm/setDay/index.js ***!
\***************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setDay; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _addDays_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../addDays/index.js */ "./node_modules/date-fns/esm/addDays/index.js");
/**
* @name setDay
* @category Weekday Helpers
* @summary Set the day of the week to the given date.
*
* @description
* Set the day of the week to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} day - the day of the week of the new date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {Date} the new date with the day of the week set
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // Set Sunday to 1 September 2014:
* var result = setDay(new Date(2014, 8, 1), 0)
* //=> Sun Aug 31 2014 00:00:00
*
* @example
* // If week starts with Monday, set Sunday to 1 September 2014:
* var result = setDay(new Date(2014, 8, 1), 0, { weekStartsOn: 1 })
* //=> Sun Sep 07 2014 00:00:00
*/
function setDay(dirtyDate, dirtyDay, dirtyOptions) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var options = dirtyOptions || {};
var locale = options.locale;
var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeWeekStartsOn);
var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, options);
var day = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDay);
var currentDay = date.getDay();
var remainder = day % 7;
var dayIndex = (remainder + 7) % 7;
var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay;
return Object(_addDays_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date, diff, options);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setDayOfYear/index.js":
/*!*********************************************************!*\
!*** ./node_modules/date-fns/esm/setDayOfYear/index.js ***!
\*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setDayOfYear; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name setDayOfYear
* @category Day Helpers
* @summary Set the day of the year to the given date.
*
* @description
* Set the day of the year to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} dayOfYear - the day of the year of the new date
* @returns {Date} the new date with the day of the year set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set the 2nd day of the year to 2 July 2014:
* var result = setDayOfYear(new Date(2014, 6, 2), 2)
* //=> Thu Jan 02 2014 00:00:00
*/
function setDayOfYear(dirtyDate, dirtyDayOfYear) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var dayOfYear = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDayOfYear);
date.setMonth(0);
date.setDate(dayOfYear);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setHours/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/setHours/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setHours; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name setHours
* @category Hour Helpers
* @summary Set the hours to the given date.
*
* @description
* Set the hours to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} hours - the hours of the new date
* @returns {Date} the new date with the hours set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set 4 hours to 1 September 2014 11:30:00:
* var result = setHours(new Date(2014, 8, 1, 11, 30), 4)
* //=> Mon Sep 01 2014 04:30:00
*/
function setHours(dirtyDate, dirtyHours) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var hours = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyHours);
date.setHours(hours);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setISODay/index.js":
/*!******************************************************!*\
!*** ./node_modules/date-fns/esm/setISODay/index.js ***!
\******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setISODay; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _addDays_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../addDays/index.js */ "./node_modules/date-fns/esm/addDays/index.js");
/* harmony import */ var _getISODay_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../getISODay/index.js */ "./node_modules/date-fns/esm/getISODay/index.js");
/**
* @name setISODay
* @category Weekday Helpers
* @summary Set the day of the ISO week to the given date.
*
* @description
* Set the day of the ISO week to the given date.
* ISO week starts with Monday.
* 7 is the index of Sunday, 1 is the index of Monday etc.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} day - the day of the ISO week of the new date
* @returns {Date} the new date with the day of the ISO week set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set Sunday to 1 September 2014:
* var result = setISODay(new Date(2014, 8, 1), 7)
* //=> Sun Sep 07 2014 00:00:00
*/
function setISODay(dirtyDate, dirtyDay) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var day = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDay);
var currentDay = Object(_getISODay_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(date);
var diff = day - currentDay;
return Object(_addDays_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date, diff);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setISOWeek/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/setISOWeek/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setISOWeek; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _getISOWeek_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../getISOWeek/index.js */ "./node_modules/date-fns/esm/getISOWeek/index.js");
/**
* @name setISOWeek
* @category ISO Week Helpers
* @summary Set the ISO week to the given date.
*
* @description
* Set the ISO week to the given date, saving the weekday number.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} isoWeek - the ISO week of the new date
* @returns {Date} the new date with the ISO week set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set the 53rd ISO week to 7 August 2004:
* var result = setISOWeek(new Date(2004, 7, 7), 53)
* //=> Sat Jan 01 2005 00:00:00
*/
function setISOWeek(dirtyDate, dirtyISOWeek) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var isoWeek = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyISOWeek);
var diff = Object(_getISOWeek_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date) - isoWeek;
date.setDate(date.getDate() - diff * 7);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setISOWeekYear/index.js":
/*!***********************************************************!*\
!*** ./node_modules/date-fns/esm/setISOWeekYear/index.js ***!
\***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setISOWeekYear; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _startOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../startOfISOWeekYear/index.js */ "./node_modules/date-fns/esm/startOfISOWeekYear/index.js");
/* harmony import */ var _differenceInCalendarDays_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../differenceInCalendarDays/index.js */ "./node_modules/date-fns/esm/differenceInCalendarDays/index.js");
/**
* @name setISOWeekYear
* @category ISO Week-Numbering Year Helpers
* @summary Set the ISO week-numbering year to the given date.
*
* @description
* Set the ISO week-numbering year to the given date,
* saving the week number and the weekday number.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `setISOYear` to `setISOWeekYear`.
* "ISO week year" is short for [ISO week-numbering year](https://en.wikipedia.org/wiki/ISO_week_date).
* This change makes the name consistent with
* locale-dependent week-numbering year helpers, e.g., `setWeekYear`.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} isoWeekYear - the ISO week-numbering year of the new date
* @returns {Date} the new date with the ISO week-numbering year set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set ISO week-numbering year 2007 to 29 December 2008:
* var result = setISOWeekYear(new Date(2008, 11, 29), 2007)
* //=> Mon Jan 01 2007 00:00:00
*/
function setISOWeekYear(dirtyDate, dirtyISOWeekYear) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var isoWeekYear = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyISOWeekYear);
var diff = Object(_differenceInCalendarDays_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(date, Object(_startOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date));
var fourthOfJanuary = new Date(0);
fourthOfJanuary.setFullYear(isoWeekYear, 0, 4);
fourthOfJanuary.setHours(0, 0, 0, 0);
date = Object(_startOfISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(fourthOfJanuary);
date.setDate(date.getDate() + diff);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setMilliseconds/index.js":
/*!************************************************************!*\
!*** ./node_modules/date-fns/esm/setMilliseconds/index.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setMilliseconds; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name setMilliseconds
* @category Millisecond Helpers
* @summary Set the milliseconds to the given date.
*
* @description
* Set the milliseconds to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} milliseconds - the milliseconds of the new date
* @returns {Date} the new date with the milliseconds set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set 300 milliseconds to 1 September 2014 11:30:40.500:
* var result = setMilliseconds(new Date(2014, 8, 1, 11, 30, 40, 500), 300)
* //=> Mon Sep 01 2014 11:30:40.300
*/
function setMilliseconds(dirtyDate, dirtyMilliseconds) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var milliseconds = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyMilliseconds);
date.setMilliseconds(milliseconds);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setMinutes/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/setMinutes/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setMinutes; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name setMinutes
* @category Minute Helpers
* @summary Set the minutes to the given date.
*
* @description
* Set the minutes to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} minutes - the minutes of the new date
* @returns {Date} the new date with the minutes set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set 45 minutes to 1 September 2014 11:30:40:
* var result = setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45)
* //=> Mon Sep 01 2014 11:45:40
*/
function setMinutes(dirtyDate, dirtyMinutes) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var minutes = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyMinutes);
date.setMinutes(minutes);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setMonth/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/setMonth/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setMonth; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _getDaysInMonth_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../getDaysInMonth/index.js */ "./node_modules/date-fns/esm/getDaysInMonth/index.js");
/**
* @name setMonth
* @category Month Helpers
* @summary Set the month to the given date.
*
* @description
* Set the month to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} month - the month of the new date
* @returns {Date} the new date with the month set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set February to 1 September 2014:
* var result = setMonth(new Date(2014, 8, 1), 1)
* //=> Sat Feb 01 2014 00:00:00
*/
function setMonth(dirtyDate, dirtyMonth) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var month = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyMonth);
var year = date.getFullYear();
var day = date.getDate();
var dateWithDesiredMonth = new Date(0);
dateWithDesiredMonth.setFullYear(year, month, 15);
dateWithDesiredMonth.setHours(0, 0, 0, 0);
var daysInMonth = Object(_getDaysInMonth_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(dateWithDesiredMonth); // Set the last day of the new month
// if the original date was the last day of the longer month
date.setMonth(month, Math.min(day, daysInMonth));
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setQuarter/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/setQuarter/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setQuarter; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _setMonth_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../setMonth/index.js */ "./node_modules/date-fns/esm/setMonth/index.js");
/**
* @name setQuarter
* @category Quarter Helpers
* @summary Set the year quarter to the given date.
*
* @description
* Set the year quarter to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} quarter - the quarter of the new date
* @returns {Date} the new date with the quarter set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set the 2nd quarter to 2 July 2014:
* var result = setQuarter(new Date(2014, 6, 2), 2)
* //=> Wed Apr 02 2014 00:00:00
*/
function setQuarter(dirtyDate, dirtyQuarter) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var quarter = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyQuarter);
var oldQuarter = Math.floor(date.getMonth() / 3) + 1;
var diff = quarter - oldQuarter;
return Object(_setMonth_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date, date.getMonth() + diff * 3);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setSeconds/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/setSeconds/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setSeconds; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name setSeconds
* @category Second Helpers
* @summary Set the seconds to the given date.
*
* @description
* Set the seconds to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} seconds - the seconds of the new date
* @returns {Date} the new date with the seconds set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set 45 seconds to 1 September 2014 11:30:40:
* var result = setSeconds(new Date(2014, 8, 1, 11, 30, 40), 45)
* //=> Mon Sep 01 2014 11:30:45
*/
function setSeconds(dirtyDate, dirtySeconds) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var seconds = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtySeconds);
date.setSeconds(seconds);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setWeek/index.js":
/*!****************************************************!*\
!*** ./node_modules/date-fns/esm/setWeek/index.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setWeek; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _getWeek_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../getWeek/index.js */ "./node_modules/date-fns/esm/getWeek/index.js");
/**
* @name setWeek
* @category Week Helpers
* @summary Set the local week to the given date.
*
* @description
* Set the local week to the given date, saving the weekday number.
* The exact calculation depends on the values of
* `options.weekStartsOn` (which is the index of the first day of the week)
* and `options.firstWeekContainsDate` (which is the day of January, which is always in
* the first week of the week-numbering year)
*
* Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} week - the week of the new date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year
* @returns {Date} the new date with the local week set
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
* @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
*
* @example
* // Set the 1st week to 2 January 2005 with default options:
* var result = setWeek(new Date(2005, 0, 2), 1)
* //=> Sun Dec 26 2004 00:00:00
*
* @example
* // Set the 1st week to 2 January 2005,
* // if Monday is the first day of the week,
* // and the first week of the year always contains 4 January:
* var result = setWeek(new Date(2005, 0, 2), 1, {
* weekStartsOn: 1,
* firstWeekContainsDate: 4
* })
* //=> Sun Jan 4 2004 00:00:00
*/
function setWeek(dirtyDate, dirtyWeek, dirtyOptions) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var week = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyWeek);
var diff = Object(_getWeek_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date, dirtyOptions) - week;
date.setDate(date.getDate() - diff * 7);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setWeekYear/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/setWeekYear/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setWeekYear; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/* harmony import */ var _startOfWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../startOfWeekYear/index.js */ "./node_modules/date-fns/esm/startOfWeekYear/index.js");
/* harmony import */ var _differenceInCalendarDays_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../differenceInCalendarDays/index.js */ "./node_modules/date-fns/esm/differenceInCalendarDays/index.js");
/**
* @name setWeekYear
* @category Week-Numbering Year Helpers
* @summary Set the local week-numbering year to the given date.
*
* @description
* Set the local week-numbering year to the given date,
* saving the week number and the weekday number.
* The exact calculation depends on the values of
* `options.weekStartsOn` (which is the index of the first day of the week)
* and `options.firstWeekContainsDate` (which is the day of January, which is always in
* the first week of the week-numbering year)
*
* Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} weekYear - the local week-numbering year of the new date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year
* @returns {Date} the new date with the local week-numbering year set
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
* @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
*
* @example
* // Set the local week-numbering year 2004 to 2 January 2010 with default options:
* var result = setWeekYear(new Date(2010, 0, 2), 2004)
* //=> Sat Jan 03 2004 00:00:00
*
* @example
* // Set the local week-numbering year 2004 to 2 January 2010,
* // if Monday is the first day of week
* // and 4 January is always in the first week of the year:
* var result = setWeekYear(new Date(2010, 0, 2), 2004, {
* weekStartsOn: 1,
* firstWeekContainsDate: 4
* })
* //=> Sat Jan 01 2005 00:00:00
*/
function setWeekYear(dirtyDate, dirtyWeekYear, dirtyOptions) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var options = dirtyOptions || {};
var locale = options.locale;
var localeFirstWeekContainsDate = locale && locale.options && locale.options.firstWeekContainsDate;
var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeFirstWeekContainsDate);
var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.firstWeekContainsDate);
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var weekYear = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyWeekYear);
var diff = Object(_differenceInCalendarDays_index_js__WEBPACK_IMPORTED_MODULE_3__["default"])(date, Object(_startOfWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(date, dirtyOptions));
var firstWeek = new Date(0);
firstWeek.setFullYear(weekYear, 0, firstWeekContainsDate);
firstWeek.setHours(0, 0, 0, 0);
date = Object(_startOfWeekYear_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(firstWeek, dirtyOptions);
date.setDate(date.getDate() + diff);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/setYear/index.js":
/*!****************************************************!*\
!*** ./node_modules/date-fns/esm/setYear/index.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return setYear; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name setYear
* @category Year Helpers
* @summary Set the year to the given date.
*
* @description
* Set the year to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} year - the year of the new date
* @returns {Date} the new date with the year set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set year 2013 to 1 September 2014:
* var result = setYear(new Date(2014, 8, 1), 2013)
* //=> Sun Sep 01 2013 00:00:00
*/
function setYear(dirtyDate, dirtyYear) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var year = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyYear); // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
if (isNaN(date)) {
return new Date(NaN);
}
date.setFullYear(year);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/startOfDay/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/startOfDay/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfDay; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name startOfDay
* @category Day Helpers
* @summary Return the start of a day for the given date.
*
* @description
* Return the start of a day for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a day
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a day for 2 September 2014 11:55:00:
* var result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 02 2014 00:00:00
*/
function startOfDay(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
date.setHours(0, 0, 0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/startOfDecade/index.js":
/*!**********************************************************!*\
!*** ./node_modules/date-fns/esm/startOfDecade/index.js ***!
\**********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfDecade; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name startOfDecade
* @category Decade Helpers
* @summary Return the start of a decade for the given date.
*
* @description
* Return the start of a decade for the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a decade
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a decade for 21 October 2015 00:00:00:
* var result = startOfDecade(new Date(2015, 9, 21, 00, 00, 00))
* //=> Jan 01 2010 00:00:00
*/
function startOfDecade(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var year = date.getFullYear();
var decade = Math.floor(year / 10) * 10;
date.setFullYear(decade, 0, 1);
date.setHours(0, 0, 0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/startOfHour/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/startOfHour/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfHour; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name startOfHour
* @category Hour Helpers
* @summary Return the start of an hour for the given date.
*
* @description
* Return the start of an hour for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of an hour
* @throws {TypeError} 1 argument required
*
* @example
* // The start of an hour for 2 September 2014 11:55:00:
* var result = startOfHour(new Date(2014, 8, 2, 11, 55))
* //=> Tue Sep 02 2014 11:00:00
*/
function startOfHour(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
date.setMinutes(0, 0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/startOfISOWeek/index.js":
/*!***********************************************************!*\
!*** ./node_modules/date-fns/esm/startOfISOWeek/index.js ***!
\***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfISOWeek; });
/* harmony import */ var _startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../startOfWeek/index.js */ "./node_modules/date-fns/esm/startOfWeek/index.js");
/**
* @name startOfISOWeek
* @category ISO Week Helpers
* @summary Return the start of an ISO week for the given date.
*
* @description
* Return the start of an ISO week for the given date.
* The result will be in the local timezone.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of an ISO week
* @throws {TypeError} 1 argument required
*
* @example
* // The start of an ISO week for 2 September 2014 11:55:00:
* var result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Mon Sep 01 2014 00:00:00
*/
function startOfISOWeek(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
return Object(_startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate, {
weekStartsOn: 1
});
}
/***/ }),
/***/ "./node_modules/date-fns/esm/startOfISOWeekYear/index.js":
/*!***************************************************************!*\
!*** ./node_modules/date-fns/esm/startOfISOWeekYear/index.js ***!
\***************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfISOWeekYear; });
/* harmony import */ var _getISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../getISOWeekYear/index.js */ "./node_modules/date-fns/esm/getISOWeekYear/index.js");
/* harmony import */ var _startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../startOfISOWeek/index.js */ "./node_modules/date-fns/esm/startOfISOWeek/index.js");
/**
* @name startOfISOWeekYear
* @category ISO Week-Numbering Year Helpers
* @summary Return the start of an ISO week-numbering year for the given date.
*
* @description
* Return the start of an ISO week-numbering year,
* which always starts 3 days before the year's first Thursday.
* The result will be in the local timezone.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of an ISO week-numbering year
* @throws {TypeError} 1 argument required
*
* @example
* // The start of an ISO week-numbering year for 2 July 2005:
* var result = startOfISOWeekYear(new Date(2005, 6, 2))
* //=> Mon Jan 03 2005 00:00:00
*/
function startOfISOWeekYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var year = Object(_getISOWeekYear_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var fourthOfJanuary = new Date(0);
fourthOfJanuary.setFullYear(year, 0, 4);
fourthOfJanuary.setHours(0, 0, 0, 0);
var date = Object(_startOfISOWeek_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(fourthOfJanuary);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/startOfMinute/index.js":
/*!**********************************************************!*\
!*** ./node_modules/date-fns/esm/startOfMinute/index.js ***!
\**********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfMinute; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name startOfMinute
* @category Minute Helpers
* @summary Return the start of a minute for the given date.
*
* @description
* Return the start of a minute for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a minute
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a minute for 1 December 2014 22:15:45.400:
* var result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400))
* //=> Mon Dec 01 2014 22:15:00
*/
function startOfMinute(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
date.setSeconds(0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/startOfMonth/index.js":
/*!*********************************************************!*\
!*** ./node_modules/date-fns/esm/startOfMonth/index.js ***!
\*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfMonth; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name startOfMonth
* @category Month Helpers
* @summary Return the start of a month for the given date.
*
* @description
* Return the start of a month for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a month
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a month for 2 September 2014 11:55:00:
* var result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0))
* //=> Mon Sep 01 2014 00:00:00
*/
function startOfMonth(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
date.setDate(1);
date.setHours(0, 0, 0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/startOfQuarter/index.js":
/*!***********************************************************!*\
!*** ./node_modules/date-fns/esm/startOfQuarter/index.js ***!
\***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfQuarter; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name startOfQuarter
* @category Quarter Helpers
* @summary Return the start of a year quarter for the given date.
*
* @description
* Return the start of a year quarter for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a quarter
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a quarter for 2 September 2014 11:55:00:
* var result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Jul 01 2014 00:00:00
*/
function startOfQuarter(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var currentMonth = date.getMonth();
var month = currentMonth - currentMonth % 3;
date.setMonth(month, 1);
date.setHours(0, 0, 0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/startOfSecond/index.js":
/*!**********************************************************!*\
!*** ./node_modules/date-fns/esm/startOfSecond/index.js ***!
\**********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfSecond; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name startOfSecond
* @category Second Helpers
* @summary Return the start of a second for the given date.
*
* @description
* Return the start of a second for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a second
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a second for 1 December 2014 22:15:45.400:
* var result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400))
* //=> Mon Dec 01 2014 22:15:45.000
*/
function startOfSecond(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
date.setMilliseconds(0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/startOfWeek/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/startOfWeek/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfWeek; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name startOfWeek
* @category Week Helpers
* @summary Return the start of a week for the given date.
*
* @description
* Return the start of a week for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {Date} the start of a week
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // The start of a week for 2 September 2014 11:55:00:
* var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sun Aug 31 2014 00:00:00
*
* @example
* // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:
* var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
* //=> Mon Sep 01 2014 00:00:00
*/
function startOfWeek(dirtyDate, dirtyOptions) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var options = dirtyOptions || {};
var locale = options.locale;
var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeWeekStartsOn);
var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate);
var day = date.getDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setDate(date.getDate() - diff);
date.setHours(0, 0, 0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/startOfWeekYear/index.js":
/*!************************************************************!*\
!*** ./node_modules/date-fns/esm/startOfWeekYear/index.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfWeekYear; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _getWeekYear_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../getWeekYear/index.js */ "./node_modules/date-fns/esm/getWeekYear/index.js");
/* harmony import */ var _startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../startOfWeek/index.js */ "./node_modules/date-fns/esm/startOfWeek/index.js");
/**
* @name startOfWeekYear
* @category Week-Numbering Year Helpers
* @summary Return the start of a local week-numbering year for the given date.
*
* @description
* Return the start of a local week-numbering year.
* The exact calculation depends on the values of
* `options.weekStartsOn` (which is the index of the first day of the week)
* and `options.firstWeekContainsDate` (which is the day of January, which is always in
* the first week of the week-numbering year)
*
* Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year
* @returns {Date} the start of a week-numbering year
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
* @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
*
* @example
* // The start of an a week-numbering year for 2 July 2005 with default settings:
* var result = startOfWeekYear(new Date(2005, 6, 2))
* //=> Sun Dec 26 2004 00:00:00
*
* @example
* // The start of a week-numbering year for 2 July 2005
* // if Monday is the first day of week
* // and 4 January is always in the first week of the year:
* var result = startOfWeekYear(new Date(2005, 6, 2), {
* weekStartsOn: 1,
* firstWeekContainsDate: 4
* })
* //=> Mon Jan 03 2005 00:00:00
*/
function startOfWeekYear(dirtyDate, dirtyOptions) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var options = dirtyOptions || {};
var locale = options.locale;
var localeFirstWeekContainsDate = locale && locale.options && locale.options.firstWeekContainsDate;
var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(localeFirstWeekContainsDate);
var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(options.firstWeekContainsDate);
var year = Object(_getWeekYear_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, dirtyOptions);
var firstWeek = new Date(0);
firstWeek.setFullYear(year, 0, firstWeekContainsDate);
firstWeek.setHours(0, 0, 0, 0);
var date = Object(_startOfWeek_index_js__WEBPACK_IMPORTED_MODULE_2__["default"])(firstWeek, dirtyOptions);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/startOfYear/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/startOfYear/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return startOfYear; });
/* harmony import */ var _toDate_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../toDate/index.js */ "./node_modules/date-fns/esm/toDate/index.js");
/**
* @name startOfYear
* @category Year Helpers
* @summary Return the start of a year for the given date.
*
* @description
* Return the start of a year for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a year
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a year for 2 September 2014 11:55:00:
* var result = startOfYear(new Date(2014, 8, 2, 11, 55, 00))
* //=> Wed Jan 01 2014 00:00:00
*/
function startOfYear(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var cleanDate = Object(_toDate_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyDate);
var date = new Date(0);
date.setFullYear(cleanDate.getFullYear(), 0, 1);
date.setHours(0, 0, 0, 0);
return date;
}
/***/ }),
/***/ "./node_modules/date-fns/esm/subDays/index.js":
/*!****************************************************!*\
!*** ./node_modules/date-fns/esm/subDays/index.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return subDays; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addDays_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addDays/index.js */ "./node_modules/date-fns/esm/addDays/index.js");
/**
* @name subDays
* @category Day Helpers
* @summary Subtract the specified number of days from the given date.
*
* @description
* Subtract the specified number of days from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of days to be subtracted
* @returns {Date} the new date with the days subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 10 days from 1 September 2014:
* var result = subDays(new Date(2014, 8, 1), 10)
* //=> Fri Aug 22 2014 00:00:00
*/
function subDays(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addDays_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, -amount);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/subHours/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/subHours/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return subHours; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addHours_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addHours/index.js */ "./node_modules/date-fns/esm/addHours/index.js");
/**
* @name subHours
* @category Hour Helpers
* @summary Subtract the specified number of hours from the given date.
*
* @description
* Subtract the specified number of hours from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of hours to be subtracted
* @returns {Date} the new date with the hours subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 2 hours from 11 July 2014 01:00:00:
* var result = subHours(new Date(2014, 6, 11, 1, 0), 2)
* //=> Thu Jul 10 2014 23:00:00
*/
function subHours(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addHours_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, -amount);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/subISOWeekYears/index.js":
/*!************************************************************!*\
!*** ./node_modules/date-fns/esm/subISOWeekYears/index.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return subISOWeekYears; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addISOWeekYears/index.js */ "./node_modules/date-fns/esm/addISOWeekYears/index.js");
/**
* @name subISOWeekYears
* @category ISO Week-Numbering Year Helpers
* @summary Subtract the specified number of ISO week-numbering years from the given date.
*
* @description
* Subtract the specified number of ISO week-numbering years from the given date.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The function was renamed from `subISOYears` to `subISOWeekYears`.
* "ISO week year" is short for [ISO week-numbering year](https://en.wikipedia.org/wiki/ISO_week_date).
* This change makes the name consistent with
* locale-dependent week-numbering year helpers, e.g., `setWeekYear`.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of ISO week-numbering years to be subtracted
* @returns {Date} the new date with the ISO week-numbering years subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 5 ISO week-numbering years from 1 September 2014:
* var result = subISOWeekYears(new Date(2014, 8, 1), 5)
* //=> Mon Aug 31 2009 00:00:00
*/
function subISOWeekYears(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addISOWeekYears_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, -amount);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/subMilliseconds/index.js":
/*!************************************************************!*\
!*** ./node_modules/date-fns/esm/subMilliseconds/index.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return subMilliseconds; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addMilliseconds/index.js */ "./node_modules/date-fns/esm/addMilliseconds/index.js");
/**
* @name subMilliseconds
* @category Millisecond Helpers
* @summary Subtract the specified number of milliseconds from the given date.
*
* @description
* Subtract the specified number of milliseconds from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of milliseconds to be subtracted
* @returns {Date} the new date with the milliseconds subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 750 milliseconds from 10 July 2014 12:45:30.000:
* var result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
* //=> Thu Jul 10 2014 12:45:29.250
*/
function subMilliseconds(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addMilliseconds_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, -amount);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/subMinutes/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/subMinutes/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return subMinutes; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addMinutes_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addMinutes/index.js */ "./node_modules/date-fns/esm/addMinutes/index.js");
/**
* @name subMinutes
* @category Minute Helpers
* @summary Subtract the specified number of minutes from the given date.
*
* @description
* Subtract the specified number of minutes from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of minutes to be subtracted
* @returns {Date} the new date with the minutes subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 30 minutes from 10 July 2014 12:00:00:
* var result = subMinutes(new Date(2014, 6, 10, 12, 0), 30)
* //=> Thu Jul 10 2014 11:30:00
*/
function subMinutes(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addMinutes_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, -amount);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/subMonths/index.js":
/*!******************************************************!*\
!*** ./node_modules/date-fns/esm/subMonths/index.js ***!
\******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return subMonths; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addMonths_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addMonths/index.js */ "./node_modules/date-fns/esm/addMonths/index.js");
/**
* @name subMonths
* @category Month Helpers
* @summary Subtract the specified number of months from the given date.
*
* @description
* Subtract the specified number of months from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of months to be subtracted
* @returns {Date} the new date with the months subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 5 months from 1 February 2015:
* var result = subMonths(new Date(2015, 1, 1), 5)
* //=> Mon Sep 01 2014 00:00:00
*/
function subMonths(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addMonths_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, -amount);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/subQuarters/index.js":
/*!********************************************************!*\
!*** ./node_modules/date-fns/esm/subQuarters/index.js ***!
\********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return subQuarters; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addQuarters_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addQuarters/index.js */ "./node_modules/date-fns/esm/addQuarters/index.js");
/**
* @name subQuarters
* @category Quarter Helpers
* @summary Subtract the specified number of year quarters from the given date.
*
* @description
* Subtract the specified number of year quarters from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of quarters to be subtracted
* @returns {Date} the new date with the quarters subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 3 quarters from 1 September 2014:
* var result = subQuarters(new Date(2014, 8, 1), 3)
* //=> Sun Dec 01 2013 00:00:00
*/
function subQuarters(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addQuarters_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, -amount);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/subSeconds/index.js":
/*!*******************************************************!*\
!*** ./node_modules/date-fns/esm/subSeconds/index.js ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return subSeconds; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addSeconds_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addSeconds/index.js */ "./node_modules/date-fns/esm/addSeconds/index.js");
/**
* @name subSeconds
* @category Second Helpers
* @summary Subtract the specified number of seconds from the given date.
*
* @description
* Subtract the specified number of seconds from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of seconds to be subtracted
* @returns {Date} the new date with the seconds subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 30 seconds from 10 July 2014 12:45:00:
* var result = subSeconds(new Date(2014, 6, 10, 12, 45, 0), 30)
* //=> Thu Jul 10 2014 12:44:30
*/
function subSeconds(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addSeconds_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, -amount);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/subWeeks/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/subWeeks/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return subWeeks; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addWeeks_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addWeeks/index.js */ "./node_modules/date-fns/esm/addWeeks/index.js");
/**
* @name subWeeks
* @category Week Helpers
* @summary Subtract the specified number of weeks from the given date.
*
* @description
* Subtract the specified number of weeks from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of weeks to be subtracted
* @returns {Date} the new date with the weeks subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 4 weeks from 1 September 2014:
* var result = subWeeks(new Date(2014, 8, 1), 4)
* //=> Mon Aug 04 2014 00:00:00
*/
function subWeeks(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addWeeks_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, -amount);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/subYears/index.js":
/*!*****************************************************!*\
!*** ./node_modules/date-fns/esm/subYears/index.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return subYears; });
/* harmony import */ var _lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../_lib/toInteger/index.js */ "./node_modules/date-fns/esm/_lib/toInteger/index.js");
/* harmony import */ var _addYears_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../addYears/index.js */ "./node_modules/date-fns/esm/addYears/index.js");
/**
* @name subYears
* @category Year Helpers
* @summary Subtract the specified number of years from the given date.
*
* @description
* Subtract the specified number of years from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of years to be subtracted
* @returns {Date} the new date with the years subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 5 years from 1 September 2014:
* var result = subYears(new Date(2014, 8, 1), 5)
* //=> Tue Sep 01 2009 00:00:00
*/
function subYears(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present');
}
var amount = Object(_lib_toInteger_index_js__WEBPACK_IMPORTED_MODULE_0__["default"])(dirtyAmount);
return Object(_addYears_index_js__WEBPACK_IMPORTED_MODULE_1__["default"])(dirtyDate, -amount);
}
/***/ }),
/***/ "./node_modules/date-fns/esm/toDate/index.js":
/*!***************************************************!*\
!*** ./node_modules/date-fns/esm/toDate/index.js ***!
\***************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return toDate; });
/**
* @name toDate
* @category Common Helpers
* @summary Convert the given argument to an instance of Date.
*
* @description
* Convert the given argument to an instance of Date.
*
* If the argument is an instance of Date, the function returns its clone.
*
* If the argument is a number, it is treated as a timestamp.
*
* If the argument is none of the above, the function returns Invalid Date.
*
* **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
*
* @param {Date|Number} argument - the value to convert
* @returns {Date} the parsed date in the local time zone
* @throws {TypeError} 1 argument required
*
* @example
* // Clone the date:
* var result = toDate(new Date(2014, 1, 11, 11, 30, 30))
* //=> Tue Feb 11 2014 11:30:30
*
* @example
* // Convert the timestamp to date:
* var result = toDate(1392098430000)
* //=> Tue Feb 11 2014 11:30:30
*/
function toDate(argument) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var argStr = Object.prototype.toString.call(argument); // Clone the date
if (argument instanceof Date || typeof argument === 'object' && argStr === '[object Date]') {
// Prevent the date to lose the milliseconds when passed to new Date() in IE10
return new Date(argument.getTime());
} else if (typeof argument === 'number' || argStr === '[object Number]') {
return new Date(argument);
} else {
if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as arguments. Please use `parseISO` to parse strings. See: https://git.io/fpAk2");
console.warn(new Error().stack);
}
return new Date(NaN);
}
}
/***/ }),
/***/ "./node_modules/deep-equal/index.js":
/*!******************************************!*\
!*** ./node_modules/deep-equal/index.js ***!
\******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var objectKeys = __webpack_require__(/*! object-keys */ "./node_modules/object-keys/index.js");
var isArguments = __webpack_require__(/*! is-arguments */ "./node_modules/is-arguments/index.js");
var is = __webpack_require__(/*! object-is */ "./node_modules/object-is/index.js");
var isRegex = __webpack_require__(/*! is-regex */ "./node_modules/is-regex/index.js");
var flags = __webpack_require__(/*! regexp.prototype.flags */ "./node_modules/regexp.prototype.flags/index.js");
var isArray = __webpack_require__(/*! isarray */ "./node_modules/deep-equal/node_modules/isarray/index.js");
var isDate = __webpack_require__(/*! is-date-object */ "./node_modules/is-date-object/index.js");
var whichBoxedPrimitive = __webpack_require__(/*! which-boxed-primitive */ "./node_modules/which-boxed-primitive/index.js");
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var whichCollection = __webpack_require__(/*! which-collection */ "./node_modules/which-collection/index.js");
var getIterator = __webpack_require__(/*! es-get-iterator */ "./node_modules/es-get-iterator/index.js");
var getSideChannel = __webpack_require__(/*! side-channel */ "./node_modules/side-channel/index.js");
var whichTypedArray = __webpack_require__(/*! which-typed-array */ "./node_modules/which-typed-array/index.js");
var assign = __webpack_require__(/*! object.assign */ "./node_modules/object.assign/index.js");
var $getTime = callBound('Date.prototype.getTime');
var gPO = Object.getPrototypeOf;
var $objToString = callBound('Object.prototype.toString');
var $Set = GetIntrinsic('%Set%', true);
var $mapHas = callBound('Map.prototype.has', true);
var $mapGet = callBound('Map.prototype.get', true);
var $mapSize = callBound('Map.prototype.size', true);
var $setAdd = callBound('Set.prototype.add', true);
var $setDelete = callBound('Set.prototype.delete', true);
var $setHas = callBound('Set.prototype.has', true);
var $setSize = callBound('Set.prototype.size', true); // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L401-L414
function setHasEqualElement(set, val1, opts, channel) {
var i = getIterator(set);
var result;
while ((result = i.next()) && !result.done) {
if (internalDeepEqual(val1, result.value, opts, channel)) {
// eslint-disable-line no-use-before-define
// Remove the matching element to make sure we do not check that again.
$setDelete(set, result.value);
return true;
}
}
return false;
} // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L416-L439
function findLooseMatchingPrimitives(prim) {
if (typeof prim === 'undefined') {
return null;
}
if (typeof prim === 'object') {
// Only pass in null as object!
return void 0;
}
if (typeof prim === 'symbol') {
return false;
}
if (typeof prim === 'string' || typeof prim === 'number') {
// Loose equal entries exist only if the string is possible to convert to a regular number and not NaN.
return +prim === +prim; // eslint-disable-line no-implicit-coercion
}
return true;
} // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L449-L460
function mapMightHaveLoosePrim(a, b, prim, item, opts, channel) {
var altValue = findLooseMatchingPrimitives(prim);
if (altValue != null) {
return altValue;
}
var curB = $mapGet(b, altValue);
var looseOpts = assign({}, opts, {
strict: false
});
if (typeof curB === 'undefined' && !$mapHas(b, altValue) // eslint-disable-next-line no-use-before-define
|| !internalDeepEqual(item, curB, looseOpts, channel)) {
return false;
} // eslint-disable-next-line no-use-before-define
return !$mapHas(a, altValue) && internalDeepEqual(item, curB, looseOpts, channel);
} // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L441-L447
function setMightHaveLoosePrim(a, b, prim) {
var altValue = findLooseMatchingPrimitives(prim);
if (altValue != null) {
return altValue;
}
return $setHas(b, altValue) && !$setHas(a, altValue);
} // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L518-L533
function mapHasEqualEntry(set, map, key1, item1, opts, channel) {
var i = getIterator(set);
var result;
var key2;
while ((result = i.next()) && !result.done) {
key2 = result.value;
if ( // eslint-disable-next-line no-use-before-define
internalDeepEqual(key1, key2, opts, channel) // eslint-disable-next-line no-use-before-define
&& internalDeepEqual(item1, $mapGet(map, key2), opts, channel)) {
$setDelete(set, key2);
return true;
}
}
return false;
}
function internalDeepEqual(actual, expected, options, channel) {
var opts = options || {}; // 7.1. All identical values are equivalent, as determined by ===.
if (opts.strict ? is(actual, expected) : actual === expected) {
return true;
}
var actualBoxed = whichBoxedPrimitive(actual);
var expectedBoxed = whichBoxedPrimitive(expected);
if (actualBoxed !== expectedBoxed) {
return false;
} // 7.3. Other pairs that do not both pass typeof value == 'object', equivalence is determined by ==.
if (!actual || !expected || typeof actual !== 'object' && typeof expected !== 'object') {
return opts.strict ? is(actual, expected) : actual == expected; // eslint-disable-line eqeqeq
}
/*
* 7.4. For all other Object pairs, including Array objects, equivalence is
* determined by having the same number of owned properties (as verified
* with Object.prototype.hasOwnProperty.call), the same set of keys
* (although not necessarily the same order), equivalent values for every
* corresponding key, and an identical 'prototype' property. Note: this
* accounts for both named and indexed properties on Arrays.
*/
// see https://github.com/nodejs/node/commit/d3aafd02efd3a403d646a3044adcf14e63a88d32 for memos/channel inspiration
var hasActual = channel.has(actual);
var hasExpected = channel.has(expected);
var sentinel;
if (hasActual && hasExpected) {
if (channel.get(actual) === channel.get(expected)) {
return true;
}
} else {
sentinel = {};
}
if (!hasActual) {
channel.set(actual, sentinel);
}
if (!hasExpected) {
channel.set(expected, sentinel);
} // eslint-disable-next-line no-use-before-define
return objEquiv(actual, expected, opts, channel);
}
function isBuffer(x) {
if (!x || typeof x !== 'object' || typeof x.length !== 'number') {
return false;
}
if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
return false;
}
if (x.length > 0 && typeof x[0] !== 'number') {
return false;
}
return !!(x.constructor && x.constructor.isBuffer && x.constructor.isBuffer(x));
}
function setEquiv(a, b, opts, channel) {
if ($setSize(a) !== $setSize(b)) {
return false;
}
var iA = getIterator(a);
var iB = getIterator(b);
var resultA;
var resultB;
var set;
while ((resultA = iA.next()) && !resultA.done) {
if (resultA.value && typeof resultA.value === 'object') {
if (!set) {
set = new $Set();
}
$setAdd(set, resultA.value);
} else if (!$setHas(b, resultA.value)) {
if (opts.strict) {
return false;
}
if (!setMightHaveLoosePrim(a, b, resultA.value)) {
return false;
}
if (!set) {
set = new $Set();
}
$setAdd(set, resultA.value);
}
}
if (set) {
while ((resultB = iB.next()) && !resultB.done) {
// We have to check if a primitive value is already matching and only if it's not, go hunting for it.
if (resultB.value && typeof resultB.value === 'object') {
if (!setHasEqualElement(set, resultB.value, opts.strict, channel)) {
return false;
}
} else if (!opts.strict && !$setHas(a, resultB.value) && !setHasEqualElement(set, resultB.value, opts.strict, channel)) {
return false;
}
}
return $setSize(set) === 0;
}
return true;
}
function mapEquiv(a, b, opts, channel) {
if ($mapSize(a) !== $mapSize(b)) {
return false;
}
var iA = getIterator(a);
var iB = getIterator(b);
var resultA;
var resultB;
var set;
var key;
var item1;
var item2;
while ((resultA = iA.next()) && !resultA.done) {
key = resultA.value[0];
item1 = resultA.value[1];
if (key && typeof key === 'object') {
if (!set) {
set = new $Set();
}
$setAdd(set, key);
} else {
item2 = $mapGet(b, key);
if (typeof item2 === 'undefined' && !$mapHas(b, key) || !internalDeepEqual(item1, item2, opts, channel)) {
if (opts.strict) {
return false;
}
if (!mapMightHaveLoosePrim(a, b, key, item1, opts, channel)) {
return false;
}
if (!set) {
set = new $Set();
}
$setAdd(set, key);
}
}
}
if (set) {
while ((resultB = iB.next()) && !resultB.done) {
key = resultB.value[0];
item2 = resultB.value[1];
if (key && typeof key === 'object') {
if (!mapHasEqualEntry(set, a, key, item2, opts, channel)) {
return false;
}
} else if (!opts.strict && (!a.has(key) || !internalDeepEqual($mapGet(a, key), item2, opts, channel)) && !mapHasEqualEntry(set, a, key, item2, assign({}, opts, {
strict: false
}), channel)) {
return false;
}
}
return $setSize(set) === 0;
}
return true;
}
function objEquiv(a, b, opts, channel) {
/* eslint max-statements: [2, 100], max-lines-per-function: [2, 120], max-depth: [2, 5] */
var i, key;
if (typeof a !== typeof b) {
return false;
}
if (a == null || b == null) {
return false;
}
if ($objToString(a) !== $objToString(b)) {
return false;
}
if (isArguments(a) !== isArguments(b)) {
return false;
}
var aIsArray = isArray(a);
var bIsArray = isArray(b);
if (aIsArray !== bIsArray) {
return false;
} // TODO: replace when a cross-realm brand check is available
var aIsError = a instanceof Error;
var bIsError = b instanceof Error;
if (aIsError !== bIsError) {
return false;
}
if (aIsError || bIsError) {
if (a.name !== b.name || a.message !== b.message) {
return false;
}
}
var aIsRegex = isRegex(a);
var bIsRegex = isRegex(b);
if (aIsRegex !== bIsRegex) {
return false;
}
if ((aIsRegex || bIsRegex) && (a.source !== b.source || flags(a) !== flags(b))) {
return false;
}
var aIsDate = isDate(a);
var bIsDate = isDate(b);
if (aIsDate !== bIsDate) {
return false;
}
if (aIsDate || bIsDate) {
// && would work too, because both are true or both false here
if ($getTime(a) !== $getTime(b)) {
return false;
}
}
if (opts.strict && gPO && gPO(a) !== gPO(b)) {
return false;
}
if (whichTypedArray(a) !== whichTypedArray(b)) {
return false;
}
var aIsBuffer = isBuffer(a);
var bIsBuffer = isBuffer(b);
if (aIsBuffer !== bIsBuffer) {
return false;
}
if (aIsBuffer || bIsBuffer) {
// && would work too, because both are true or both false here
if (a.length !== b.length) {
return false;
}
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
if (typeof a !== typeof b) {
return false;
}
var ka = objectKeys(a);
var kb = objectKeys(b); // having the same number of owned properties (keys incorporates hasOwnProperty)
if (ka.length !== kb.length) {
return false;
} // the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort(); // ~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i]) {
return false;
} // eslint-disable-line eqeqeq
} // equivalent values for every corresponding key, and ~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!internalDeepEqual(a[key], b[key], opts, channel)) {
return false;
}
}
var aCollection = whichCollection(a);
var bCollection = whichCollection(b);
if (aCollection !== bCollection) {
return false;
}
if (aCollection === 'Set' || bCollection === 'Set') {
// aCollection === bCollection
return setEquiv(a, b, opts, channel);
}
if (aCollection === 'Map') {
// aCollection === bCollection
return mapEquiv(a, b, opts, channel);
}
return true;
}
module.exports = function deepEqual(a, b, opts) {
return internalDeepEqual(a, b, opts, getSideChannel());
};
/***/ }),
/***/ "./node_modules/deep-equal/node_modules/isarray/index.js":
/*!***************************************************************!*\
!*** ./node_modules/deep-equal/node_modules/isarray/index.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
/***/ }),
/***/ "./node_modules/define-properties/index.js":
/*!*************************************************!*\
!*** ./node_modules/define-properties/index.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var keys = __webpack_require__(/*! object-keys */ "./node_modules/object-keys/index.js");
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
var toStr = Object.prototype.toString;
var concat = Array.prototype.concat;
var origDefineProperty = Object.defineProperty;
var isFunction = function (fn) {
return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
};
var arePropertyDescriptorsSupported = function () {
var obj = {};
try {
origDefineProperty(obj, 'x', {
enumerable: false,
value: obj
}); // eslint-disable-next-line no-unused-vars, no-restricted-syntax
for (var _ in obj) {
// jscs:ignore disallowUnusedVariables
return false;
}
return obj.x === obj;
} catch (e) {
/* this is IE 8. */
return false;
}
};
var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();
var defineProperty = function (object, name, value, predicate) {
if (name in object && (!isFunction(predicate) || !predicate())) {
return;
}
if (supportsDescriptors) {
origDefineProperty(object, name, {
configurable: true,
enumerable: false,
value: value,
writable: true
});
} else {
object[name] = value;
}
};
var defineProperties = function (object, map) {
var predicates = arguments.length > 2 ? arguments[2] : {};
var props = keys(map);
if (hasSymbols) {
props = concat.call(props, Object.getOwnPropertySymbols(map));
}
for (var i = 0; i < props.length; i += 1) {
defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
}
};
defineProperties.supportsDescriptors = !!supportsDescriptors;
module.exports = defineProperties;
/***/ }),
/***/ "./node_modules/es-abstract/2020/ArraySpeciesCreate.js":
/*!*************************************************************!*\
!*** ./node_modules/es-abstract/2020/ArraySpeciesCreate.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $Array = GetIntrinsic('%Array%');
var $species = GetIntrinsic('%Symbol.species%', true);
var $TypeError = GetIntrinsic('%TypeError%');
var Get = __webpack_require__(/*! ./Get */ "./node_modules/es-abstract/2020/Get.js");
var IsArray = __webpack_require__(/*! ./IsArray */ "./node_modules/es-abstract/2020/IsArray.js");
var IsConstructor = __webpack_require__(/*! ./IsConstructor */ "./node_modules/es-abstract/2020/IsConstructor.js");
var IsInteger = __webpack_require__(/*! ./IsInteger */ "./node_modules/es-abstract/2020/IsInteger.js");
var Type = __webpack_require__(/*! ./Type */ "./node_modules/es-abstract/2020/Type.js"); // https://ecma-international.org/ecma-262/6.0/#sec-arrayspeciescreate
module.exports = function ArraySpeciesCreate(originalArray, length) {
if (!IsInteger(length) || length < 0) {
throw new $TypeError('Assertion failed: length must be an integer >= 0');
}
var len = length === 0 ? 0 : length;
var C;
var isArray = IsArray(originalArray);
if (isArray) {
C = Get(originalArray, 'constructor'); // TODO: figure out how to make a cross-realm normal Array, a same-realm Array
// if (IsConstructor(C)) {
// if C is another realm's Array, C = undefined
// Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Array))) === null ?
// }
if ($species && Type(C) === 'Object') {
C = Get(C, $species);
if (C === null) {
C = void 0;
}
}
}
if (typeof C === 'undefined') {
return $Array(len);
}
if (!IsConstructor(C)) {
throw new $TypeError('C must be a constructor');
}
return new C(len); // Construct(C, len);
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/Call.js":
/*!***********************************************!*\
!*** ./node_modules/es-abstract/2020/Call.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var $TypeError = GetIntrinsic('%TypeError%');
var IsArray = __webpack_require__(/*! ./IsArray */ "./node_modules/es-abstract/2020/IsArray.js");
var $apply = GetIntrinsic('%Reflect.apply%', true) || callBound('%Function.prototype.apply%'); // https://ecma-international.org/ecma-262/6.0/#sec-call
module.exports = function Call(F, V) {
var argumentsList = arguments.length > 2 ? arguments[2] : [];
if (!IsArray(argumentsList)) {
throw new $TypeError('Assertion failed: optional `argumentsList`, if provided, must be a List');
}
return $apply(F, V, argumentsList);
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/CreateDataProperty.js":
/*!*************************************************************!*\
!*** ./node_modules/es-abstract/2020/CreateDataProperty.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $TypeError = GetIntrinsic('%TypeError%');
var DefineOwnProperty = __webpack_require__(/*! ../helpers/DefineOwnProperty */ "./node_modules/es-abstract/helpers/DefineOwnProperty.js");
var FromPropertyDescriptor = __webpack_require__(/*! ./FromPropertyDescriptor */ "./node_modules/es-abstract/2020/FromPropertyDescriptor.js");
var OrdinaryGetOwnProperty = __webpack_require__(/*! ./OrdinaryGetOwnProperty */ "./node_modules/es-abstract/2020/OrdinaryGetOwnProperty.js");
var IsDataDescriptor = __webpack_require__(/*! ./IsDataDescriptor */ "./node_modules/es-abstract/2020/IsDataDescriptor.js");
var IsExtensible = __webpack_require__(/*! ./IsExtensible */ "./node_modules/es-abstract/2020/IsExtensible.js");
var IsPropertyKey = __webpack_require__(/*! ./IsPropertyKey */ "./node_modules/es-abstract/2020/IsPropertyKey.js");
var SameValue = __webpack_require__(/*! ./SameValue */ "./node_modules/es-abstract/2020/SameValue.js");
var Type = __webpack_require__(/*! ./Type */ "./node_modules/es-abstract/2020/Type.js"); // https://ecma-international.org/ecma-262/6.0/#sec-createdataproperty
module.exports = function CreateDataProperty(O, P, V) {
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: Type(O) is not Object');
}
if (!IsPropertyKey(P)) {
throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');
}
var oldDesc = OrdinaryGetOwnProperty(O, P);
var extensible = !oldDesc || IsExtensible(O);
var immutable = oldDesc && (!oldDesc['[[Writable]]'] || !oldDesc['[[Configurable]]']);
if (immutable || !extensible) {
return false;
}
return DefineOwnProperty(IsDataDescriptor, SameValue, FromPropertyDescriptor, O, P, {
'[[Configurable]]': true,
'[[Enumerable]]': true,
'[[Value]]': V,
'[[Writable]]': true
});
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/CreateDataPropertyOrThrow.js":
/*!********************************************************************!*\
!*** ./node_modules/es-abstract/2020/CreateDataPropertyOrThrow.js ***!
\********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $TypeError = GetIntrinsic('%TypeError%');
var CreateDataProperty = __webpack_require__(/*! ./CreateDataProperty */ "./node_modules/es-abstract/2020/CreateDataProperty.js");
var IsPropertyKey = __webpack_require__(/*! ./IsPropertyKey */ "./node_modules/es-abstract/2020/IsPropertyKey.js");
var Type = __webpack_require__(/*! ./Type */ "./node_modules/es-abstract/2020/Type.js"); // // https://ecma-international.org/ecma-262/6.0/#sec-createdatapropertyorthrow
module.exports = function CreateDataPropertyOrThrow(O, P, V) {
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: Type(O) is not Object');
}
if (!IsPropertyKey(P)) {
throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');
}
var success = CreateDataProperty(O, P, V);
if (!success) {
throw new $TypeError('unable to create data property');
}
return success;
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/DefinePropertyOrThrow.js":
/*!****************************************************************!*\
!*** ./node_modules/es-abstract/2020/DefinePropertyOrThrow.js ***!
\****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $TypeError = GetIntrinsic('%TypeError%');
var isPropertyDescriptor = __webpack_require__(/*! ../helpers/isPropertyDescriptor */ "./node_modules/es-abstract/helpers/isPropertyDescriptor.js");
var DefineOwnProperty = __webpack_require__(/*! ../helpers/DefineOwnProperty */ "./node_modules/es-abstract/helpers/DefineOwnProperty.js");
var FromPropertyDescriptor = __webpack_require__(/*! ./FromPropertyDescriptor */ "./node_modules/es-abstract/2020/FromPropertyDescriptor.js");
var IsAccessorDescriptor = __webpack_require__(/*! ./IsAccessorDescriptor */ "./node_modules/es-abstract/2020/IsAccessorDescriptor.js");
var IsDataDescriptor = __webpack_require__(/*! ./IsDataDescriptor */ "./node_modules/es-abstract/2020/IsDataDescriptor.js");
var IsPropertyKey = __webpack_require__(/*! ./IsPropertyKey */ "./node_modules/es-abstract/2020/IsPropertyKey.js");
var SameValue = __webpack_require__(/*! ./SameValue */ "./node_modules/es-abstract/2020/SameValue.js");
var ToPropertyDescriptor = __webpack_require__(/*! ./ToPropertyDescriptor */ "./node_modules/es-abstract/2020/ToPropertyDescriptor.js");
var Type = __webpack_require__(/*! ./Type */ "./node_modules/es-abstract/2020/Type.js"); // https://ecma-international.org/ecma-262/6.0/#sec-definepropertyorthrow
module.exports = function DefinePropertyOrThrow(O, P, desc) {
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: Type(O) is not Object');
}
if (!IsPropertyKey(P)) {
throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');
}
var Desc = isPropertyDescriptor({
Type: Type,
IsDataDescriptor: IsDataDescriptor,
IsAccessorDescriptor: IsAccessorDescriptor
}, desc) ? desc : ToPropertyDescriptor(desc);
if (!isPropertyDescriptor({
Type: Type,
IsDataDescriptor: IsDataDescriptor,
IsAccessorDescriptor: IsAccessorDescriptor
}, Desc)) {
throw new $TypeError('Assertion failed: Desc is not a valid Property Descriptor');
}
return DefineOwnProperty(IsDataDescriptor, SameValue, FromPropertyDescriptor, O, P, Desc);
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/FromPropertyDescriptor.js":
/*!*****************************************************************!*\
!*** ./node_modules/es-abstract/2020/FromPropertyDescriptor.js ***!
\*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var assertRecord = __webpack_require__(/*! ../helpers/assertRecord */ "./node_modules/es-abstract/helpers/assertRecord.js");
var Type = __webpack_require__(/*! ./Type */ "./node_modules/es-abstract/2020/Type.js"); // https://ecma-international.org/ecma-262/6.0/#sec-frompropertydescriptor
module.exports = function FromPropertyDescriptor(Desc) {
if (typeof Desc === 'undefined') {
return Desc;
}
assertRecord(Type, 'Property Descriptor', 'Desc', Desc);
var obj = {};
if ('[[Value]]' in Desc) {
obj.value = Desc['[[Value]]'];
}
if ('[[Writable]]' in Desc) {
obj.writable = Desc['[[Writable]]'];
}
if ('[[Get]]' in Desc) {
obj.get = Desc['[[Get]]'];
}
if ('[[Set]]' in Desc) {
obj.set = Desc['[[Set]]'];
}
if ('[[Enumerable]]' in Desc) {
obj.enumerable = Desc['[[Enumerable]]'];
}
if ('[[Configurable]]' in Desc) {
obj.configurable = Desc['[[Configurable]]'];
}
return obj;
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/Get.js":
/*!**********************************************!*\
!*** ./node_modules/es-abstract/2020/Get.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $TypeError = GetIntrinsic('%TypeError%');
var inspect = __webpack_require__(/*! object-inspect */ "./node_modules/object-inspect/index.js");
var IsPropertyKey = __webpack_require__(/*! ./IsPropertyKey */ "./node_modules/es-abstract/2020/IsPropertyKey.js");
var Type = __webpack_require__(/*! ./Type */ "./node_modules/es-abstract/2020/Type.js");
/**
* 7.3.1 Get (O, P) - https://ecma-international.org/ecma-262/6.0/#sec-get-o-p
* 1. Assert: Type(O) is Object.
* 2. Assert: IsPropertyKey(P) is true.
* 3. Return O.[[Get]](P, O).
*/
module.exports = function Get(O, P) {
// 7.3.1.1
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: Type(O) is not Object');
} // 7.3.1.2
if (!IsPropertyKey(P)) {
throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true, got ' + inspect(P));
} // 7.3.1.3
return O[P];
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/HasProperty.js":
/*!******************************************************!*\
!*** ./node_modules/es-abstract/2020/HasProperty.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $TypeError = GetIntrinsic('%TypeError%');
var IsPropertyKey = __webpack_require__(/*! ./IsPropertyKey */ "./node_modules/es-abstract/2020/IsPropertyKey.js");
var Type = __webpack_require__(/*! ./Type */ "./node_modules/es-abstract/2020/Type.js"); // https://ecma-international.org/ecma-262/6.0/#sec-hasproperty
module.exports = function HasProperty(O, P) {
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: `O` must be an Object');
}
if (!IsPropertyKey(P)) {
throw new $TypeError('Assertion failed: `P` must be a Property Key');
}
return P in O;
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/IsAccessorDescriptor.js":
/*!***************************************************************!*\
!*** ./node_modules/es-abstract/2020/IsAccessorDescriptor.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = __webpack_require__(/*! has */ "./node_modules/has/src/index.js");
var assertRecord = __webpack_require__(/*! ../helpers/assertRecord */ "./node_modules/es-abstract/helpers/assertRecord.js");
var Type = __webpack_require__(/*! ./Type */ "./node_modules/es-abstract/2020/Type.js"); // https://ecma-international.org/ecma-262/6.0/#sec-isaccessordescriptor
module.exports = function IsAccessorDescriptor(Desc) {
if (typeof Desc === 'undefined') {
return false;
}
assertRecord(Type, 'Property Descriptor', 'Desc', Desc);
if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) {
return false;
}
return true;
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/IsArray.js":
/*!**************************************************!*\
!*** ./node_modules/es-abstract/2020/IsArray.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $Array = GetIntrinsic('%Array%'); // eslint-disable-next-line global-require
var toStr = !$Array.isArray && __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js")('Object.prototype.toString'); // https://ecma-international.org/ecma-262/6.0/#sec-isarray
module.exports = $Array.isArray || function IsArray(argument) {
return toStr(argument) === '[object Array]';
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/IsCallable.js":
/*!*****************************************************!*\
!*** ./node_modules/es-abstract/2020/IsCallable.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// http://262.ecma-international.org/5.1/#sec-9.11
module.exports = __webpack_require__(/*! is-callable */ "./node_modules/is-callable/index.js");
/***/ }),
/***/ "./node_modules/es-abstract/2020/IsConstructor.js":
/*!********************************************************!*\
!*** ./node_modules/es-abstract/2020/IsConstructor.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! ../GetIntrinsic.js */ "./node_modules/es-abstract/GetIntrinsic.js");
var $construct = GetIntrinsic('%Reflect.construct%', true);
var DefinePropertyOrThrow = __webpack_require__(/*! ./DefinePropertyOrThrow */ "./node_modules/es-abstract/2020/DefinePropertyOrThrow.js");
try {
DefinePropertyOrThrow({}, '', {
'[[Get]]': function () {}
});
} catch (e) {
// Accessor properties aren't supported
DefinePropertyOrThrow = null;
} // https://ecma-international.org/ecma-262/6.0/#sec-isconstructor
if (DefinePropertyOrThrow && $construct) {
var isConstructorMarker = {};
var badArrayLike = {};
DefinePropertyOrThrow(badArrayLike, 'length', {
'[[Get]]': function () {
throw isConstructorMarker;
},
'[[Enumerable]]': true
});
module.exports = function IsConstructor(argument) {
try {
// `Reflect.construct` invokes `IsConstructor(target)` before `Get(args, 'length')`:
$construct(argument, badArrayLike);
} catch (err) {
return err === isConstructorMarker;
}
};
} else {
module.exports = function IsConstructor(argument) {
// unfortunately there's no way to truly check this without try/catch `new argument` in old environments
return typeof argument === 'function' && !!argument.prototype;
};
}
/***/ }),
/***/ "./node_modules/es-abstract/2020/IsDataDescriptor.js":
/*!***********************************************************!*\
!*** ./node_modules/es-abstract/2020/IsDataDescriptor.js ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = __webpack_require__(/*! has */ "./node_modules/has/src/index.js");
var assertRecord = __webpack_require__(/*! ../helpers/assertRecord */ "./node_modules/es-abstract/helpers/assertRecord.js");
var Type = __webpack_require__(/*! ./Type */ "./node_modules/es-abstract/2020/Type.js"); // https://ecma-international.org/ecma-262/6.0/#sec-isdatadescriptor
module.exports = function IsDataDescriptor(Desc) {
if (typeof Desc === 'undefined') {
return false;
}
assertRecord(Type, 'Property Descriptor', 'Desc', Desc);
if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) {
return false;
}
return true;
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/IsExtensible.js":
/*!*******************************************************!*\
!*** ./node_modules/es-abstract/2020/IsExtensible.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $Object = GetIntrinsic('%Object%');
var isPrimitive = __webpack_require__(/*! ../helpers/isPrimitive */ "./node_modules/es-abstract/helpers/isPrimitive.js");
var $preventExtensions = $Object.preventExtensions;
var $isExtensible = $Object.isExtensible; // https://ecma-international.org/ecma-262/6.0/#sec-isextensible-o
module.exports = $preventExtensions ? function IsExtensible(obj) {
return !isPrimitive(obj) && $isExtensible(obj);
} : function IsExtensible(obj) {
return !isPrimitive(obj);
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/IsInteger.js":
/*!****************************************************!*\
!*** ./node_modules/es-abstract/2020/IsInteger.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var abs = __webpack_require__(/*! ./abs */ "./node_modules/es-abstract/2020/abs.js");
var floor = __webpack_require__(/*! ./floor */ "./node_modules/es-abstract/2020/floor.js");
var $isNaN = __webpack_require__(/*! ../helpers/isNaN */ "./node_modules/es-abstract/helpers/isNaN.js");
var $isFinite = __webpack_require__(/*! ../helpers/isFinite */ "./node_modules/es-abstract/helpers/isFinite.js"); // https://ecma-international.org/ecma-262/6.0/#sec-isinteger
module.exports = function IsInteger(argument) {
if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) {
return false;
}
var absValue = abs(argument);
return floor(absValue) === absValue;
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/IsPropertyKey.js":
/*!********************************************************!*\
!*** ./node_modules/es-abstract/2020/IsPropertyKey.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://ecma-international.org/ecma-262/6.0/#sec-ispropertykey
module.exports = function IsPropertyKey(argument) {
return typeof argument === 'string' || typeof argument === 'symbol';
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/IsRegExp.js":
/*!***************************************************!*\
!*** ./node_modules/es-abstract/2020/IsRegExp.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $match = GetIntrinsic('%Symbol.match%', true);
var hasRegExpMatcher = __webpack_require__(/*! is-regex */ "./node_modules/is-regex/index.js");
var ToBoolean = __webpack_require__(/*! ./ToBoolean */ "./node_modules/es-abstract/2020/ToBoolean.js"); // https://ecma-international.org/ecma-262/6.0/#sec-isregexp
module.exports = function IsRegExp(argument) {
if (!argument || typeof argument !== 'object') {
return false;
}
if ($match) {
var isRegExp = argument[$match];
if (typeof isRegExp !== 'undefined') {
return ToBoolean(isRegExp);
}
}
return hasRegExpMatcher(argument);
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/LengthOfArrayLike.js":
/*!************************************************************!*\
!*** ./node_modules/es-abstract/2020/LengthOfArrayLike.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $TypeError = GetIntrinsic('%TypeError%');
var Get = __webpack_require__(/*! ./Get */ "./node_modules/es-abstract/2020/Get.js");
var ToLength = __webpack_require__(/*! ./ToLength */ "./node_modules/es-abstract/2020/ToLength.js");
var Type = __webpack_require__(/*! ./Type */ "./node_modules/es-abstract/2020/Type.js"); // https://262.ecma-international.org/11.0/#sec-lengthofarraylike
module.exports = function LengthOfArrayLike(obj) {
if (Type(obj) !== 'Object') {
throw new $TypeError('Assertion failed: `obj` must be an Object');
}
return ToLength(Get(obj, 'length'));
}; // TODO: use this all over
/***/ }),
/***/ "./node_modules/es-abstract/2020/OrdinaryGetOwnProperty.js":
/*!*****************************************************************!*\
!*** ./node_modules/es-abstract/2020/OrdinaryGetOwnProperty.js ***!
\*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $gOPD = __webpack_require__(/*! ../helpers/getOwnPropertyDescriptor */ "./node_modules/es-abstract/helpers/getOwnPropertyDescriptor.js");
var $TypeError = GetIntrinsic('%TypeError%');
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable');
var has = __webpack_require__(/*! has */ "./node_modules/has/src/index.js");
var IsArray = __webpack_require__(/*! ./IsArray */ "./node_modules/es-abstract/2020/IsArray.js");
var IsPropertyKey = __webpack_require__(/*! ./IsPropertyKey */ "./node_modules/es-abstract/2020/IsPropertyKey.js");
var IsRegExp = __webpack_require__(/*! ./IsRegExp */ "./node_modules/es-abstract/2020/IsRegExp.js");
var ToPropertyDescriptor = __webpack_require__(/*! ./ToPropertyDescriptor */ "./node_modules/es-abstract/2020/ToPropertyDescriptor.js");
var Type = __webpack_require__(/*! ./Type */ "./node_modules/es-abstract/2020/Type.js"); // https://ecma-international.org/ecma-262/6.0/#sec-ordinarygetownproperty
module.exports = function OrdinaryGetOwnProperty(O, P) {
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: O must be an Object');
}
if (!IsPropertyKey(P)) {
throw new $TypeError('Assertion failed: P must be a Property Key');
}
if (!has(O, P)) {
return void 0;
}
if (!$gOPD) {
// ES3 / IE 8 fallback
var arrayLength = IsArray(O) && P === 'length';
var regexLastIndex = IsRegExp(O) && P === 'lastIndex';
return {
'[[Configurable]]': !(arrayLength || regexLastIndex),
'[[Enumerable]]': $isEnumerable(O, P),
'[[Value]]': O[P],
'[[Writable]]': true
};
}
return ToPropertyDescriptor($gOPD(O, P));
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/RequireObjectCoercible.js":
/*!*****************************************************************!*\
!*** ./node_modules/es-abstract/2020/RequireObjectCoercible.js ***!
\*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(/*! ../5/CheckObjectCoercible */ "./node_modules/es-abstract/5/CheckObjectCoercible.js");
/***/ }),
/***/ "./node_modules/es-abstract/2020/SameValue.js":
/*!****************************************************!*\
!*** ./node_modules/es-abstract/2020/SameValue.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $isNaN = __webpack_require__(/*! ../helpers/isNaN */ "./node_modules/es-abstract/helpers/isNaN.js"); // http://262.ecma-international.org/5.1/#sec-9.12
module.exports = function SameValue(x, y) {
if (x === y) {
// 0 === -0, but they are not identical.
if (x === 0) {
return 1 / x === 1 / y;
}
return true;
}
return $isNaN(x) && $isNaN(y);
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/ToBoolean.js":
/*!****************************************************!*\
!*** ./node_modules/es-abstract/2020/ToBoolean.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// http://262.ecma-international.org/5.1/#sec-9.2
module.exports = function ToBoolean(value) {
return !!value;
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/ToInteger.js":
/*!****************************************************!*\
!*** ./node_modules/es-abstract/2020/ToInteger.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ES5ToInteger = __webpack_require__(/*! ../5/ToInteger */ "./node_modules/es-abstract/5/ToInteger.js");
var ToNumber = __webpack_require__(/*! ./ToNumber */ "./node_modules/es-abstract/2020/ToNumber.js"); // https://262.ecma-international.org/11.0/#sec-tointeger
module.exports = function ToInteger(value) {
var number = ToNumber(value);
if (number !== 0) {
number = ES5ToInteger(number);
}
return number === 0 ? 0 : number;
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/ToLength.js":
/*!***************************************************!*\
!*** ./node_modules/es-abstract/2020/ToLength.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var MAX_SAFE_INTEGER = __webpack_require__(/*! ../helpers/maxSafeInteger */ "./node_modules/es-abstract/helpers/maxSafeInteger.js");
var ToInteger = __webpack_require__(/*! ./ToInteger */ "./node_modules/es-abstract/2020/ToInteger.js");
module.exports = function ToLength(argument) {
var len = ToInteger(argument);
if (len <= 0) {
return 0;
} // includes converting -0 to +0
if (len > MAX_SAFE_INTEGER) {
return MAX_SAFE_INTEGER;
}
return len;
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/ToNumber.js":
/*!***************************************************!*\
!*** ./node_modules/es-abstract/2020/ToNumber.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $TypeError = GetIntrinsic('%TypeError%');
var $Number = GetIntrinsic('%Number%');
var $RegExp = GetIntrinsic('%RegExp%');
var $parseInteger = GetIntrinsic('%parseInt%');
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var regexTester = __webpack_require__(/*! ../helpers/regexTester */ "./node_modules/es-abstract/helpers/regexTester.js");
var isPrimitive = __webpack_require__(/*! ../helpers/isPrimitive */ "./node_modules/es-abstract/helpers/isPrimitive.js");
var $strSlice = callBound('String.prototype.slice');
var isBinary = regexTester(/^0b[01]+$/i);
var isOctal = regexTester(/^0o[0-7]+$/i);
var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i);
var nonWS = ['\u0085', '\u200b', '\ufffe'].join('');
var nonWSregex = new $RegExp('[' + nonWS + ']', 'g');
var hasNonWS = regexTester(nonWSregex); // whitespace from: https://es5.github.io/#x15.5.4.20
// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324
var ws = ['\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', '\u2029\uFEFF'].join('');
var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g');
var $replace = callBound('String.prototype.replace');
var $trim = function (value) {
return $replace(value, trimRegex, '');
};
var ToPrimitive = __webpack_require__(/*! ./ToPrimitive */ "./node_modules/es-abstract/2020/ToPrimitive.js"); // https://ecma-international.org/ecma-262/6.0/#sec-tonumber
module.exports = function ToNumber(argument) {
var value = isPrimitive(argument) ? argument : ToPrimitive(argument, $Number);
if (typeof value === 'symbol') {
throw new $TypeError('Cannot convert a Symbol value to a number');
}
if (typeof value === 'string') {
if (isBinary(value)) {
return ToNumber($parseInteger($strSlice(value, 2), 2));
} else if (isOctal(value)) {
return ToNumber($parseInteger($strSlice(value, 2), 8));
} else if (hasNonWS(value) || isInvalidHexLiteral(value)) {
return NaN;
} else {
var trimmed = $trim(value);
if (trimmed !== value) {
return ToNumber(trimmed);
}
}
}
return $Number(value);
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/ToObject.js":
/*!***************************************************!*\
!*** ./node_modules/es-abstract/2020/ToObject.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $Object = GetIntrinsic('%Object%');
var RequireObjectCoercible = __webpack_require__(/*! ./RequireObjectCoercible */ "./node_modules/es-abstract/2020/RequireObjectCoercible.js"); // https://ecma-international.org/ecma-262/6.0/#sec-toobject
module.exports = function ToObject(value) {
RequireObjectCoercible(value);
return $Object(value);
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/ToPrimitive.js":
/*!******************************************************!*\
!*** ./node_modules/es-abstract/2020/ToPrimitive.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toPrimitive = __webpack_require__(/*! es-to-primitive/es2015 */ "./node_modules/es-to-primitive/es2015.js"); // https://ecma-international.org/ecma-262/6.0/#sec-toprimitive
module.exports = function ToPrimitive(input) {
if (arguments.length > 1) {
return toPrimitive(input, arguments[1]);
}
return toPrimitive(input);
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/ToPropertyDescriptor.js":
/*!***************************************************************!*\
!*** ./node_modules/es-abstract/2020/ToPropertyDescriptor.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = __webpack_require__(/*! has */ "./node_modules/has/src/index.js");
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $TypeError = GetIntrinsic('%TypeError%');
var Type = __webpack_require__(/*! ./Type */ "./node_modules/es-abstract/2020/Type.js");
var ToBoolean = __webpack_require__(/*! ./ToBoolean */ "./node_modules/es-abstract/2020/ToBoolean.js");
var IsCallable = __webpack_require__(/*! ./IsCallable */ "./node_modules/es-abstract/2020/IsCallable.js"); // https://262.ecma-international.org/5.1/#sec-8.10.5
module.exports = function ToPropertyDescriptor(Obj) {
if (Type(Obj) !== 'Object') {
throw new $TypeError('ToPropertyDescriptor requires an object');
}
var desc = {};
if (has(Obj, 'enumerable')) {
desc['[[Enumerable]]'] = ToBoolean(Obj.enumerable);
}
if (has(Obj, 'configurable')) {
desc['[[Configurable]]'] = ToBoolean(Obj.configurable);
}
if (has(Obj, 'value')) {
desc['[[Value]]'] = Obj.value;
}
if (has(Obj, 'writable')) {
desc['[[Writable]]'] = ToBoolean(Obj.writable);
}
if (has(Obj, 'get')) {
var getter = Obj.get;
if (typeof getter !== 'undefined' && !IsCallable(getter)) {
throw new $TypeError('getter must be a function');
}
desc['[[Get]]'] = getter;
}
if (has(Obj, 'set')) {
var setter = Obj.set;
if (typeof setter !== 'undefined' && !IsCallable(setter)) {
throw new $TypeError('setter must be a function');
}
desc['[[Set]]'] = setter;
}
if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) {
throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute');
}
return desc;
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/ToString.js":
/*!***************************************************!*\
!*** ./node_modules/es-abstract/2020/ToString.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $String = GetIntrinsic('%String%');
var $TypeError = GetIntrinsic('%TypeError%'); // https://ecma-international.org/ecma-262/6.0/#sec-tostring
module.exports = function ToString(argument) {
if (typeof argument === 'symbol') {
throw new $TypeError('Cannot convert a Symbol value to a string');
}
return $String(argument);
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/Type.js":
/*!***********************************************!*\
!*** ./node_modules/es-abstract/2020/Type.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ES5Type = __webpack_require__(/*! ../5/Type */ "./node_modules/es-abstract/5/Type.js"); // https://262.ecma-international.org/11.0/#sec-ecmascript-data-types-and-values
module.exports = function Type(x) {
if (typeof x === 'symbol') {
return 'Symbol';
}
if (typeof x === 'bigint') {
return 'BigInt';
}
return ES5Type(x);
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/abs.js":
/*!**********************************************!*\
!*** ./node_modules/es-abstract/2020/abs.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $abs = GetIntrinsic('%Math.abs%'); // http://262.ecma-international.org/5.1/#sec-5.2
module.exports = function abs(x) {
return $abs(x);
};
/***/ }),
/***/ "./node_modules/es-abstract/2020/floor.js":
/*!************************************************!*\
!*** ./node_modules/es-abstract/2020/floor.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// var modulo = require('./modulo');
var $floor = Math.floor; // http://262.ecma-international.org/5.1/#sec-5.2
module.exports = function floor(x) {
// return x - modulo(x, 1);
return $floor(x);
};
/***/ }),
/***/ "./node_modules/es-abstract/5/CheckObjectCoercible.js":
/*!************************************************************!*\
!*** ./node_modules/es-abstract/5/CheckObjectCoercible.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $TypeError = GetIntrinsic('%TypeError%'); // http://262.ecma-international.org/5.1/#sec-9.10
module.exports = function CheckObjectCoercible(value, optMessage) {
if (value == null) {
throw new $TypeError(optMessage || 'Cannot call method on ' + value);
}
return value;
};
/***/ }),
/***/ "./node_modules/es-abstract/5/ToInteger.js":
/*!*************************************************!*\
!*** ./node_modules/es-abstract/5/ToInteger.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var abs = __webpack_require__(/*! ./abs */ "./node_modules/es-abstract/5/abs.js");
var floor = __webpack_require__(/*! ./floor */ "./node_modules/es-abstract/5/floor.js");
var ToNumber = __webpack_require__(/*! ./ToNumber */ "./node_modules/es-abstract/5/ToNumber.js");
var $isNaN = __webpack_require__(/*! ../helpers/isNaN */ "./node_modules/es-abstract/helpers/isNaN.js");
var $isFinite = __webpack_require__(/*! ../helpers/isFinite */ "./node_modules/es-abstract/helpers/isFinite.js");
var $sign = __webpack_require__(/*! ../helpers/sign */ "./node_modules/es-abstract/helpers/sign.js"); // http://262.ecma-international.org/5.1/#sec-9.4
module.exports = function ToInteger(value) {
var number = ToNumber(value);
if ($isNaN(number)) {
return 0;
}
if (number === 0 || !$isFinite(number)) {
return number;
}
return $sign(number) * floor(abs(number));
};
/***/ }),
/***/ "./node_modules/es-abstract/5/ToNumber.js":
/*!************************************************!*\
!*** ./node_modules/es-abstract/5/ToNumber.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ToPrimitive = __webpack_require__(/*! ./ToPrimitive */ "./node_modules/es-abstract/5/ToPrimitive.js"); // http://262.ecma-international.org/5.1/#sec-9.3
module.exports = function ToNumber(value) {
var prim = ToPrimitive(value, Number);
if (typeof prim !== 'string') {
return +prim; // eslint-disable-line no-implicit-coercion
} // eslint-disable-next-line no-control-regex
var trimmed = prim.replace(/^[ \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u0085]+|[ \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u0085]+$/g, '');
if (/^0[ob]|^[+-]0x/.test(trimmed)) {
return NaN;
}
return +trimmed; // eslint-disable-line no-implicit-coercion
};
/***/ }),
/***/ "./node_modules/es-abstract/5/ToPrimitive.js":
/*!***************************************************!*\
!*** ./node_modules/es-abstract/5/ToPrimitive.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// http://262.ecma-international.org/5.1/#sec-9.1
module.exports = __webpack_require__(/*! es-to-primitive/es5 */ "./node_modules/es-to-primitive/es5.js");
/***/ }),
/***/ "./node_modules/es-abstract/5/Type.js":
/*!********************************************!*\
!*** ./node_modules/es-abstract/5/Type.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://262.ecma-international.org/5.1/#sec-8
module.exports = function Type(x) {
if (x === null) {
return 'Null';
}
if (typeof x === 'undefined') {
return 'Undefined';
}
if (typeof x === 'function' || typeof x === 'object') {
return 'Object';
}
if (typeof x === 'number') {
return 'Number';
}
if (typeof x === 'boolean') {
return 'Boolean';
}
if (typeof x === 'string') {
return 'String';
}
};
/***/ }),
/***/ "./node_modules/es-abstract/5/abs.js":
/*!*******************************************!*\
!*** ./node_modules/es-abstract/5/abs.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $abs = GetIntrinsic('%Math.abs%'); // http://262.ecma-international.org/5.1/#sec-5.2
module.exports = function abs(x) {
return $abs(x);
};
/***/ }),
/***/ "./node_modules/es-abstract/5/floor.js":
/*!*********************************************!*\
!*** ./node_modules/es-abstract/5/floor.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// var modulo = require('./modulo');
var $floor = Math.floor; // http://262.ecma-international.org/5.1/#sec-5.2
module.exports = function floor(x) {
// return x - modulo(x, 1);
return $floor(x);
};
/***/ }),
/***/ "./node_modules/es-abstract/GetIntrinsic.js":
/*!**************************************************!*\
!*** ./node_modules/es-abstract/GetIntrinsic.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// TODO: remove, semver-major
module.exports = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
/***/ }),
/***/ "./node_modules/es-abstract/helpers/DefineOwnProperty.js":
/*!***************************************************************!*\
!*** ./node_modules/es-abstract/helpers/DefineOwnProperty.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
if ($defineProperty) {
try {
$defineProperty({}, 'a', {
value: 1
});
} catch (e) {
// IE 8 has a broken defineProperty
$defineProperty = null;
}
}
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); // eslint-disable-next-line max-params
module.exports = function DefineOwnProperty(IsDataDescriptor, SameValue, FromPropertyDescriptor, O, P, desc) {
if (!$defineProperty) {
if (!IsDataDescriptor(desc)) {
// ES3 does not support getters/setters
return false;
}
if (!desc['[[Configurable]]'] || !desc['[[Writable]]']) {
return false;
} // fallback for ES3
if (P in O && $isEnumerable(O, P) !== !!desc['[[Enumerable]]']) {
// a non-enumerable existing property
return false;
} // property does not exist at all, or exists but is enumerable
var V = desc['[[Value]]']; // eslint-disable-next-line no-param-reassign
O[P] = V; // will use [[Define]]
return SameValue(O[P], V);
}
$defineProperty(O, P, FromPropertyDescriptor(desc));
return true;
};
/***/ }),
/***/ "./node_modules/es-abstract/helpers/assertRecord.js":
/*!**********************************************************!*\
!*** ./node_modules/es-abstract/helpers/assertRecord.js ***!
\**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $TypeError = GetIntrinsic('%TypeError%');
var $SyntaxError = GetIntrinsic('%SyntaxError%');
var has = __webpack_require__(/*! has */ "./node_modules/has/src/index.js");
var predicates = {
// https://262.ecma-international.org/6.0/#sec-property-descriptor-specification-type
'Property Descriptor': function isPropertyDescriptor(Type, Desc) {
if (Type(Desc) !== 'Object') {
return false;
}
var allowed = {
'[[Configurable]]': true,
'[[Enumerable]]': true,
'[[Get]]': true,
'[[Set]]': true,
'[[Value]]': true,
'[[Writable]]': true
};
for (var key in Desc) {
// eslint-disable-line
if (has(Desc, key) && !allowed[key]) {
return false;
}
}
var isData = has(Desc, '[[Value]]');
var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');
if (isData && IsAccessor) {
throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
}
return true;
}
};
module.exports = function assertRecord(Type, recordType, argumentName, value) {
var predicate = predicates[recordType];
if (typeof predicate !== 'function') {
throw new $SyntaxError('unknown record type: ' + recordType);
}
if (!predicate(Type, value)) {
throw new $TypeError(argumentName + ' must be a ' + recordType);
}
};
/***/ }),
/***/ "./node_modules/es-abstract/helpers/getOwnPropertyDescriptor.js":
/*!**********************************************************************!*\
!*** ./node_modules/es-abstract/helpers/getOwnPropertyDescriptor.js ***!
\**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%');
if ($gOPD) {
try {
$gOPD([], 'length');
} catch (e) {
// IE 8 has a broken gOPD
$gOPD = null;
}
}
module.exports = $gOPD;
/***/ }),
/***/ "./node_modules/es-abstract/helpers/isFinite.js":
/*!******************************************************!*\
!*** ./node_modules/es-abstract/helpers/isFinite.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $isNaN = Number.isNaN || function (a) {
return a !== a;
};
module.exports = Number.isFinite || function (x) {
return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity;
};
/***/ }),
/***/ "./node_modules/es-abstract/helpers/isNaN.js":
/*!***************************************************!*\
!*** ./node_modules/es-abstract/helpers/isNaN.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = Number.isNaN || function isNaN(a) {
return a !== a;
};
/***/ }),
/***/ "./node_modules/es-abstract/helpers/isPrimitive.js":
/*!*********************************************************!*\
!*** ./node_modules/es-abstract/helpers/isPrimitive.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function isPrimitive(value) {
return value === null || typeof value !== 'function' && typeof value !== 'object';
};
/***/ }),
/***/ "./node_modules/es-abstract/helpers/isPropertyDescriptor.js":
/*!******************************************************************!*\
!*** ./node_modules/es-abstract/helpers/isPropertyDescriptor.js ***!
\******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var has = __webpack_require__(/*! has */ "./node_modules/has/src/index.js");
var $TypeError = GetIntrinsic('%TypeError%');
module.exports = function IsPropertyDescriptor(ES, Desc) {
if (ES.Type(Desc) !== 'Object') {
return false;
}
var allowed = {
'[[Configurable]]': true,
'[[Enumerable]]': true,
'[[Get]]': true,
'[[Set]]': true,
'[[Value]]': true,
'[[Writable]]': true
};
for (var key in Desc) {
// eslint-disable-line no-restricted-syntax
if (has(Desc, key) && !allowed[key]) {
return false;
}
}
if (ES.IsDataDescriptor(Desc) && ES.IsAccessorDescriptor(Desc)) {
throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
}
return true;
};
/***/ }),
/***/ "./node_modules/es-abstract/helpers/maxSafeInteger.js":
/*!************************************************************!*\
!*** ./node_modules/es-abstract/helpers/maxSafeInteger.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $Math = GetIntrinsic('%Math%');
var $Number = GetIntrinsic('%Number%');
module.exports = $Number.MAX_SAFE_INTEGER || $Math.pow(2, 53) - 1;
/***/ }),
/***/ "./node_modules/es-abstract/helpers/regexTester.js":
/*!*********************************************************!*\
!*** ./node_modules/es-abstract/helpers/regexTester.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $test = GetIntrinsic('RegExp.prototype.test');
var callBind = __webpack_require__(/*! call-bind */ "./node_modules/call-bind/index.js");
module.exports = function regexTester(regex) {
return callBind($test, regex);
};
/***/ }),
/***/ "./node_modules/es-abstract/helpers/sign.js":
/*!**************************************************!*\
!*** ./node_modules/es-abstract/helpers/sign.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function sign(number) {
return number >= 0 ? 1 : -1;
};
/***/ }),
/***/ "./node_modules/es-array-method-boxes-properly/index.js":
/*!**************************************************************!*\
!*** ./node_modules/es-array-method-boxes-properly/index.js ***!
\**************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = function properlyBoxed(method) {
// Check node 0.6.21 bug where third parameter is not boxed
var properlyBoxesNonStrict = true;
var properlyBoxesStrict = true;
var threwException = false;
if (typeof method === 'function') {
try {
// eslint-disable-next-line max-params
method.call('f', function (_, __, O) {
if (typeof O !== 'object') {
properlyBoxesNonStrict = false;
}
});
method.call([null], function () {
'use strict';
properlyBoxesStrict = typeof this === 'string'; // eslint-disable-line no-invalid-this
}, 'x');
} catch (e) {
threwException = true;
}
return !threwException && properlyBoxesNonStrict && properlyBoxesStrict;
}
return false;
};
/***/ }),
/***/ "./node_modules/es-get-iterator/index.js":
/*!***********************************************!*\
!*** ./node_modules/es-get-iterator/index.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* eslint global-require: 0 */
// the code is structured this way so that bundlers can
// alias out `has-symbols` to `() => true` or `() => false` if your target
// environments' Symbol capabilities are known, and then use
// dead code elimination on the rest of this module.
//
// Similarly, `isarray` can be aliased to `Array.isArray` if
// available in all target environments.
var isArguments = __webpack_require__(/*! is-arguments */ "./node_modules/is-arguments/index.js");
if (__webpack_require__(/*! has-symbols */ "./node_modules/has-symbols/index.js")() || __webpack_require__(/*! has-symbols/shams */ "./node_modules/has-symbols/shams.js")()) {
var $iterator = Symbol.iterator; // Symbol is available natively or shammed
// natively:
// - Chrome >= 38
// - Edge 12-14?, Edge >= 15 for sure
// - FF >= 36
// - Safari >= 9
// - node >= 0.12
module.exports = function getIterator(iterable) {
// alternatively, `iterable[$iterator]?.()`
if (iterable != null && typeof iterable[$iterator] !== 'undefined') {
return iterable[$iterator]();
}
if (isArguments(iterable)) {
// arguments objects lack Symbol.iterator
// - node 0.12
return Array.prototype[$iterator].call(iterable);
}
};
} else {
// Symbol is not available, native or shammed
var isArray = __webpack_require__(/*! isarray */ "./node_modules/es-get-iterator/node_modules/isarray/index.js");
var isString = __webpack_require__(/*! is-string */ "./node_modules/is-string/index.js");
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var $Map = GetIntrinsic('%Map%', true);
var $Set = GetIntrinsic('%Set%', true);
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var $arrayPush = callBound('Array.prototype.push');
var $charCodeAt = callBound('String.prototype.charCodeAt');
var $stringSlice = callBound('String.prototype.slice');
var advanceStringIndex = function advanceStringIndex(S, index) {
var length = S.length;
if (index + 1 >= length) {
return index + 1;
}
var first = $charCodeAt(S, index);
if (first < 0xD800 || first > 0xDBFF) {
return index + 1;
}
var second = $charCodeAt(S, index + 1);
if (second < 0xDC00 || second > 0xDFFF) {
return index + 1;
}
return index + 2;
};
var getArrayIterator = function getArrayIterator(arraylike) {
var i = 0;
return {
next: function next() {
var done = i >= arraylike.length;
var value;
if (!done) {
value = arraylike[i];
i += 1;
}
return {
done: done,
value: value
};
}
};
};
var getNonCollectionIterator = function getNonCollectionIterator(iterable, noPrimordialCollections) {
if (isArray(iterable) || isArguments(iterable)) {
return getArrayIterator(iterable);
}
if (isString(iterable)) {
var i = 0;
return {
next: function next() {
var nextIndex = advanceStringIndex(iterable, i);
var value = $stringSlice(iterable, i, nextIndex);
i = nextIndex;
return {
done: nextIndex > iterable.length,
value: value
};
}
};
} // es6-shim and es-shims' es-map use a string "_es6-shim iterator_" property on different iterables, such as MapIterator.
if (noPrimordialCollections && typeof iterable['_es6-shim iterator_'] !== 'undefined') {
return iterable['_es6-shim iterator_']();
}
};
if (!$Map && !$Set) {
// the only language iterables are Array, String, arguments
// - Safari <= 6.0
// - Chrome < 38
// - node < 0.12
// - FF < 13
// - IE < 11
// - Edge < 11
module.exports = function getIterator(iterable) {
if (iterable != null) {
return getNonCollectionIterator(iterable, true);
}
};
} else {
// either Map or Set are available, but Symbol is not
// - es6-shim on an ES5 browser
// - Safari 6.2 (maybe 6.1?)
// - FF v[13, 36)
// - IE 11
// - Edge 11
// - Safari v[6, 9)
var isMap = __webpack_require__(/*! is-map */ "./node_modules/is-map/index.js");
var isSet = __webpack_require__(/*! is-set */ "./node_modules/is-set/index.js"); // Firefox >= 27, IE 11, Safari 6.2 - 9, Edge 11, es6-shim in older envs, all have forEach
var $mapForEach = callBound('Map.prototype.forEach', true);
var $setForEach = callBound('Set.prototype.forEach', true);
if (typeof process === 'undefined' || !process.versions || !process.versions.node) {
// "if is not node"
// Firefox 17 - 26 has `.iterator()`, whose iterator `.next()` either
// returns a value, or throws a StopIteration object. These browsers
// do not have any other mechanism for iteration.
var $mapIterator = callBound('Map.prototype.iterator', true);
var $setIterator = callBound('Set.prototype.iterator', true);
var getStopIterationIterator = function (iterator) {
var done = false;
return {
next: function next() {
try {
return {
done: done,
value: done ? undefined : iterator.next()
};
} catch (e) {
done = true;
return {
done: true,
value: undefined
};
}
}
};
};
} // Firefox 27-35, and some older es6-shim versions, use a string "@@iterator" property
// this returns a proper iterator object, so we should use it instead of forEach.
// newer es6-shim versions use a string "_es6-shim iterator_" property.
var $mapAtAtIterator = callBound('Map.prototype.@@iterator', true) || callBound('Map.prototype._es6-shim iterator_', true);
var $setAtAtIterator = callBound('Set.prototype.@@iterator', true) || callBound('Set.prototype._es6-shim iterator_', true);
var getCollectionIterator = function getCollectionIterator(iterable) {
if (isMap(iterable)) {
if ($mapIterator) {
return getStopIterationIterator($mapIterator(iterable));
}
if ($mapAtAtIterator) {
return $mapAtAtIterator(iterable);
}
if ($mapForEach) {
var entries = [];
$mapForEach(iterable, function (v, k) {
$arrayPush(entries, [k, v]);
});
return getArrayIterator(entries);
}
}
if (isSet(iterable)) {
if ($setIterator) {
return getStopIterationIterator($setIterator(iterable));
}
if ($setAtAtIterator) {
return $setAtAtIterator(iterable);
}
if ($setForEach) {
var values = [];
$setForEach(iterable, function (v) {
$arrayPush(values, v);
});
return getArrayIterator(values);
}
}
};
module.exports = function getIterator(iterable) {
return getCollectionIterator(iterable) || getNonCollectionIterator(iterable);
};
}
}
/***/ }),
/***/ "./node_modules/es-get-iterator/node_modules/isarray/index.js":
/*!********************************************************************!*\
!*** ./node_modules/es-get-iterator/node_modules/isarray/index.js ***!
\********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
/***/ }),
/***/ "./node_modules/es-to-primitive/es2015.js":
/*!************************************************!*\
!*** ./node_modules/es-to-primitive/es2015.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
var isPrimitive = __webpack_require__(/*! ./helpers/isPrimitive */ "./node_modules/es-to-primitive/helpers/isPrimitive.js");
var isCallable = __webpack_require__(/*! is-callable */ "./node_modules/is-callable/index.js");
var isDate = __webpack_require__(/*! is-date-object */ "./node_modules/is-date-object/index.js");
var isSymbol = __webpack_require__(/*! is-symbol */ "./node_modules/is-symbol/index.js");
var ordinaryToPrimitive = function OrdinaryToPrimitive(O, hint) {
if (typeof O === 'undefined' || O === null) {
throw new TypeError('Cannot call method on ' + O);
}
if (typeof hint !== 'string' || hint !== 'number' && hint !== 'string') {
throw new TypeError('hint must be "string" or "number"');
}
var methodNames = hint === 'string' ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
var method, result, i;
for (i = 0; i < methodNames.length; ++i) {
method = O[methodNames[i]];
if (isCallable(method)) {
result = method.call(O);
if (isPrimitive(result)) {
return result;
}
}
}
throw new TypeError('No default value');
};
var GetMethod = function GetMethod(O, P) {
var func = O[P];
if (func !== null && typeof func !== 'undefined') {
if (!isCallable(func)) {
throw new TypeError(func + ' returned for property ' + P + ' of object ' + O + ' is not a function');
}
return func;
}
return void 0;
}; // http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive
module.exports = function ToPrimitive(input) {
if (isPrimitive(input)) {
return input;
}
var hint = 'default';
if (arguments.length > 1) {
if (arguments[1] === String) {
hint = 'string';
} else if (arguments[1] === Number) {
hint = 'number';
}
}
var exoticToPrim;
if (hasSymbols) {
if (Symbol.toPrimitive) {
exoticToPrim = GetMethod(input, Symbol.toPrimitive);
} else if (isSymbol(input)) {
exoticToPrim = Symbol.prototype.valueOf;
}
}
if (typeof exoticToPrim !== 'undefined') {
var result = exoticToPrim.call(input, hint);
if (isPrimitive(result)) {
return result;
}
throw new TypeError('unable to convert exotic object to primitive');
}
if (hint === 'default' && (isDate(input) || isSymbol(input))) {
hint = 'string';
}
return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint);
};
/***/ }),
/***/ "./node_modules/es-to-primitive/es5.js":
/*!*********************************************!*\
!*** ./node_modules/es-to-primitive/es5.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toStr = Object.prototype.toString;
var isPrimitive = __webpack_require__(/*! ./helpers/isPrimitive */ "./node_modules/es-to-primitive/helpers/isPrimitive.js");
var isCallable = __webpack_require__(/*! is-callable */ "./node_modules/is-callable/index.js"); // http://ecma-international.org/ecma-262/5.1/#sec-8.12.8
var ES5internalSlots = {
'[[DefaultValue]]': function (O) {
var actualHint;
if (arguments.length > 1) {
actualHint = arguments[1];
} else {
actualHint = toStr.call(O) === '[object Date]' ? String : Number;
}
if (actualHint === String || actualHint === Number) {
var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
var value, i;
for (i = 0; i < methods.length; ++i) {
if (isCallable(O[methods[i]])) {
value = O[methods[i]]();
if (isPrimitive(value)) {
return value;
}
}
}
throw new TypeError('No default value');
}
throw new TypeError('invalid [[DefaultValue]] hint supplied');
}
}; // http://ecma-international.org/ecma-262/5.1/#sec-9.1
module.exports = function ToPrimitive(input) {
if (isPrimitive(input)) {
return input;
}
if (arguments.length > 1) {
return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]);
}
return ES5internalSlots['[[DefaultValue]]'](input);
};
/***/ }),
/***/ "./node_modules/es-to-primitive/helpers/isPrimitive.js":
/*!*************************************************************!*\
!*** ./node_modules/es-to-primitive/helpers/isPrimitive.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function isPrimitive(value) {
return value === null || typeof value !== 'function' && typeof value !== 'object';
};
/***/ }),
/***/ "./node_modules/foreach/index.js":
/*!***************************************!*\
!*** ./node_modules/foreach/index.js ***!
\***************************************/
/*! no static exports found */
/***/ (function(module, exports) {
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
module.exports = function forEach(obj, fn, ctx) {
if (toString.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
/***/ }),
/***/ "./node_modules/function-bind/implementation.js":
/*!******************************************************!*\
!*** ./node_modules/function-bind/implementation.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice = Array.prototype.slice;
var toStr = Object.prototype.toString;
var funcType = '[object Function]';
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.call(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slice.call(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(this, args.concat(slice.call(arguments)));
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(that, args.concat(slice.call(arguments)));
}
};
var boundLength = Math.max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs.push('$' + i);
}
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ "./node_modules/function-bind/index.js":
/*!*********************************************!*\
!*** ./node_modules/function-bind/index.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/function-bind/implementation.js");
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ "./node_modules/get-intrinsic/index.js":
/*!*********************************************!*\
!*** ./node_modules/get-intrinsic/index.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var undefined;
var $SyntaxError = SyntaxError;
var $Function = Function;
var $TypeError = TypeError; // eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD ? function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}() : throwTypeError;
var hasSymbols = __webpack_require__(/*! has-symbols */ "./node_modules/has-symbols/index.js")();
var getProto = Object.getPrototypeOf || function (x) {
return x.__proto__;
}; // eslint-disable-line no-proto
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);
var INTRINSICS = {
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': Error,
'%eval%': eval,
// eslint-disable-line no-eval
'%EvalError%': EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': RangeError,
'%ReferenceError%': ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(/*! function-bind */ "./node_modules/function-bind/index.js");
var hasOwn = __webpack_require__(/*! has */ "./node_modules/has/src/index.js");
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g;
/** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if ((first === '"' || first === "'" || first === '`' || last === '"' || last === "'" || last === '`') && first !== last) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && i + 1 >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc; // By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ "./node_modules/google-protobuf/google-protobuf.js":
/*!*********************************************************!*\
!*** ./node_modules/google-protobuf/google-protobuf.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
var $jscomp = $jscomp || {};
$jscomp.scope = {};
$jscomp.findInternal = function (a, b, c) {
a instanceof String && (a = String(a));
for (var d = a.length, e = 0; e < d; e++) {
var f = a[e];
if (b.call(c, f, e, a)) return {
i: e,
v: f
};
}
return {
i: -1,
v: void 0
};
};
$jscomp.ASSUME_ES5 = !1;
$jscomp.ASSUME_NO_NATIVE_MAP = !1;
$jscomp.ASSUME_NO_NATIVE_SET = !1;
$jscomp.SIMPLE_FROUND_POLYFILL = !1;
$jscomp.defineProperty = $jscomp.ASSUME_ES5 || "function" == typeof Object.defineProperties ? Object.defineProperty : function (a, b, c) {
a != Array.prototype && a != Object.prototype && (a[b] = c.value);
};
$jscomp.getGlobal = function (a) {
return "undefined" != typeof window && window === a ? a : "undefined" != typeof global && null != global ? global : a;
};
$jscomp.global = $jscomp.getGlobal(this);
$jscomp.polyfill = function (a, b, c, d) {
if (b) {
c = $jscomp.global;
a = a.split(".");
for (d = 0; d < a.length - 1; d++) {
var e = a[d];
e in c || (c[e] = {});
c = c[e];
}
a = a[a.length - 1];
d = c[a];
b = b(d);
b != d && null != b && $jscomp.defineProperty(c, a, {
configurable: !0,
writable: !0,
value: b
});
}
};
$jscomp.polyfill("Array.prototype.findIndex", function (a) {
return a ? a : function (a, c) {
return $jscomp.findInternal(this, a, c).i;
};
}, "es6", "es3");
$jscomp.checkStringArgs = function (a, b, c) {
if (null == a) throw new TypeError("The 'this' value for String.prototype." + c + " must not be null or undefined");
if (b instanceof RegExp) throw new TypeError("First argument to String.prototype." + c + " must not be a regular expression");
return a + "";
};
$jscomp.polyfill("String.prototype.endsWith", function (a) {
return a ? a : function (a, c) {
var b = $jscomp.checkStringArgs(this, a, "endsWith");
a += "";
void 0 === c && (c = b.length);
c = Math.max(0, Math.min(c | 0, b.length));
for (var e = a.length; 0 < e && 0 < c;) if (b[--c] != a[--e]) return !1;
return 0 >= e;
};
}, "es6", "es3");
$jscomp.polyfill("Array.prototype.find", function (a) {
return a ? a : function (a, c) {
return $jscomp.findInternal(this, a, c).v;
};
}, "es6", "es3");
$jscomp.polyfill("String.prototype.startsWith", function (a) {
return a ? a : function (a, c) {
var b = $jscomp.checkStringArgs(this, a, "startsWith");
a += "";
var e = b.length,
f = a.length;
c = Math.max(0, Math.min(c | 0, b.length));
for (var g = 0; g < f && c < e;) if (b[c++] != a[g++]) return !1;
return g >= f;
};
}, "es6", "es3");
$jscomp.polyfill("String.prototype.repeat", function (a) {
return a ? a : function (a) {
var b = $jscomp.checkStringArgs(this, null, "repeat");
if (0 > a || 1342177279 < a) throw new RangeError("Invalid count value");
a |= 0;
for (var d = ""; a;) if (a & 1 && (d += b), a >>>= 1) b += b;
return d;
};
}, "es6", "es3");
var COMPILED = !0,
goog = goog || {};
goog.global = this || self;
goog.isDef = function (a) {
return void 0 !== a;
};
goog.isString = function (a) {
return "string" == typeof a;
};
goog.isBoolean = function (a) {
return "boolean" == typeof a;
};
goog.isNumber = function (a) {
return "number" == typeof a;
};
goog.exportPath_ = function (a, b, c) {
a = a.split(".");
c = c || goog.global;
a[0] in c || "undefined" == typeof c.execScript || c.execScript("var " + a[0]);
for (var d; a.length && (d = a.shift());) !a.length && goog.isDef(b) ? c[d] = b : c = c[d] && c[d] !== Object.prototype[d] ? c[d] : c[d] = {};
};
goog.define = function (a, b) {
if (!COMPILED) {
var c = goog.global.CLOSURE_UNCOMPILED_DEFINES,
d = goog.global.CLOSURE_DEFINES;
c && void 0 === c.nodeType && Object.prototype.hasOwnProperty.call(c, a) ? b = c[a] : d && void 0 === d.nodeType && Object.prototype.hasOwnProperty.call(d, a) && (b = d[a]);
}
return b;
};
goog.FEATURESET_YEAR = 2012;
goog.DEBUG = !0;
goog.LOCALE = "en";
goog.TRUSTED_SITE = !0;
goog.STRICT_MODE_COMPATIBLE = !1;
goog.DISALLOW_TEST_ONLY_CODE = COMPILED && !goog.DEBUG;
goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING = !1;
goog.provide = function (a) {
if (goog.isInModuleLoader_()) throw Error("goog.provide cannot be used within a module.");
if (!COMPILED && goog.isProvided_(a)) throw Error('Namespace "' + a + '" already declared.');
goog.constructNamespace_(a);
};
goog.constructNamespace_ = function (a, b) {
if (!COMPILED) {
delete goog.implicitNamespaces_[a];
for (var c = a; (c = c.substring(0, c.lastIndexOf("."))) && !goog.getObjectByName(c);) goog.implicitNamespaces_[c] = !0;
}
goog.exportPath_(a, b);
};
goog.getScriptNonce = function (a) {
if (a && a != goog.global) return goog.getScriptNonce_(a.document);
null === goog.cspNonce_ && (goog.cspNonce_ = goog.getScriptNonce_(goog.global.document));
return goog.cspNonce_;
};
goog.NONCE_PATTERN_ = /^[\w+/_-]+[=]{0,2}$/;
goog.cspNonce_ = null;
goog.getScriptNonce_ = function (a) {
return (a = a.querySelector && a.querySelector("script[nonce]")) && (a = a.nonce || a.getAttribute("nonce")) && goog.NONCE_PATTERN_.test(a) ? a : "";
};
goog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;
goog.module = function (a) {
if (!goog.isString(a) || !a || -1 == a.search(goog.VALID_MODULE_RE_)) throw Error("Invalid module identifier");
if (!goog.isInGoogModuleLoader_()) throw Error("Module " + a + " has been loaded incorrectly. Note, modules cannot be loaded as normal scripts. They require some kind of pre-processing step. You're likely trying to load a module via a script tag or as a part of a concatenated bundle without rewriting the module. For more info see: https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.");
if (goog.moduleLoaderState_.moduleName) throw Error("goog.module may only be called once per module.");
goog.moduleLoaderState_.moduleName = a;
if (!COMPILED) {
if (goog.isProvided_(a)) throw Error('Namespace "' + a + '" already declared.');
delete goog.implicitNamespaces_[a];
}
};
goog.module.get = function (a) {
return goog.module.getInternal_(a);
};
goog.module.getInternal_ = function (a) {
if (!COMPILED) {
if (a in goog.loadedModules_) return goog.loadedModules_[a].exports;
if (!goog.implicitNamespaces_[a]) return a = goog.getObjectByName(a), null != a ? a : null;
}
return null;
};
goog.ModuleType = {
ES6: "es6",
GOOG: "goog"
};
goog.moduleLoaderState_ = null;
goog.isInModuleLoader_ = function () {
return goog.isInGoogModuleLoader_() || goog.isInEs6ModuleLoader_();
};
goog.isInGoogModuleLoader_ = function () {
return !!goog.moduleLoaderState_ && goog.moduleLoaderState_.type == goog.ModuleType.GOOG;
};
goog.isInEs6ModuleLoader_ = function () {
if (goog.moduleLoaderState_ && goog.moduleLoaderState_.type == goog.ModuleType.ES6) return !0;
var a = goog.global.$jscomp;
return a ? "function" != typeof a.getCurrentModulePath ? !1 : !!a.getCurrentModulePath() : !1;
};
goog.module.declareLegacyNamespace = function () {
if (!COMPILED && !goog.isInGoogModuleLoader_()) throw Error("goog.module.declareLegacyNamespace must be called from within a goog.module");
if (!COMPILED && !goog.moduleLoaderState_.moduleName) throw Error("goog.module must be called prior to goog.module.declareLegacyNamespace.");
goog.moduleLoaderState_.declareLegacyNamespace = !0;
};
goog.declareModuleId = function (a) {
if (!COMPILED) {
if (!goog.isInEs6ModuleLoader_()) throw Error("goog.declareModuleId may only be called from within an ES6 module");
if (goog.moduleLoaderState_ && goog.moduleLoaderState_.moduleName) throw Error("goog.declareModuleId may only be called once per module.");
if (a in goog.loadedModules_) throw Error('Module with namespace "' + a + '" already exists.');
}
if (goog.moduleLoaderState_) goog.moduleLoaderState_.moduleName = a;else {
var b = goog.global.$jscomp;
if (!b || "function" != typeof b.getCurrentModulePath) throw Error('Module with namespace "' + a + '" has been loaded incorrectly.');
b = b.require(b.getCurrentModulePath());
goog.loadedModules_[a] = {
exports: b,
type: goog.ModuleType.ES6,
moduleId: a
};
}
};
goog.setTestOnly = function (a) {
if (goog.DISALLOW_TEST_ONLY_CODE) throw a = a || "", Error("Importing test-only code into non-debug environment" + (a ? ": " + a : "."));
};
goog.forwardDeclare = function (a) {};
COMPILED || (goog.isProvided_ = function (a) {
return a in goog.loadedModules_ || !goog.implicitNamespaces_[a] && goog.isDefAndNotNull(goog.getObjectByName(a));
}, goog.implicitNamespaces_ = {
"goog.module": !0
});
goog.getObjectByName = function (a, b) {
a = a.split(".");
b = b || goog.global;
for (var c = 0; c < a.length; c++) if (b = b[a[c]], !goog.isDefAndNotNull(b)) return null;
return b;
};
goog.globalize = function (a, b) {
b = b || goog.global;
for (var c in a) b[c] = a[c];
};
goog.addDependency = function (a, b, c, d) {
!COMPILED && goog.DEPENDENCIES_ENABLED && goog.debugLoader_.addDependency(a, b, c, d);
};
goog.ENABLE_DEBUG_LOADER = !0;
goog.logToConsole_ = function (a) {
goog.global.console && goog.global.console.error(a);
};
goog.require = function (a) {
if (!COMPILED) {
goog.ENABLE_DEBUG_LOADER && goog.debugLoader_.requested(a);
if (goog.isProvided_(a)) {
if (goog.isInModuleLoader_()) return goog.module.getInternal_(a);
} else if (goog.ENABLE_DEBUG_LOADER) {
var b = goog.moduleLoaderState_;
goog.moduleLoaderState_ = null;
try {
goog.debugLoader_.load_(a);
} finally {
goog.moduleLoaderState_ = b;
}
}
return null;
}
};
goog.requireType = function (a) {
return {};
};
goog.basePath = "";
goog.nullFunction = function () {};
goog.abstractMethod = function () {
throw Error("unimplemented abstract method");
};
goog.addSingletonGetter = function (a) {
a.instance_ = void 0;
a.getInstance = function () {
if (a.instance_) return a.instance_;
goog.DEBUG && (goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = a);
return a.instance_ = new a();
};
};
goog.instantiatedSingletons_ = [];
goog.LOAD_MODULE_USING_EVAL = !0;
goog.SEAL_MODULE_EXPORTS = goog.DEBUG;
goog.loadedModules_ = {};
goog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;
goog.TRANSPILE = "detect";
goog.ASSUME_ES_MODULES_TRANSPILED = !1;
goog.TRANSPILE_TO_LANGUAGE = "";
goog.TRANSPILER = "transpile.js";
goog.hasBadLetScoping = null;
goog.useSafari10Workaround = function () {
if (null == goog.hasBadLetScoping) {
try {
var a = !eval('"use strict";let x = 1; function f() { return typeof x; };f() == "number";');
} catch (b) {
a = !1;
}
goog.hasBadLetScoping = a;
}
return goog.hasBadLetScoping;
};
goog.workaroundSafari10EvalBug = function (a) {
return "(function(){" + a + "\n;})();\n";
};
goog.loadModule = function (a) {
var b = goog.moduleLoaderState_;
try {
goog.moduleLoaderState_ = {
moduleName: "",
declareLegacyNamespace: !1,
type: goog.ModuleType.GOOG
};
if (goog.isFunction(a)) var c = a.call(void 0, {});else if (goog.isString(a)) goog.useSafari10Workaround() && (a = goog.workaroundSafari10EvalBug(a)), c = goog.loadModuleFromSource_.call(void 0, a);else throw Error("Invalid module definition");
var d = goog.moduleLoaderState_.moduleName;
if (goog.isString(d) && d) goog.moduleLoaderState_.declareLegacyNamespace ? goog.constructNamespace_(d, c) : goog.SEAL_MODULE_EXPORTS && Object.seal && "object" == typeof c && null != c && Object.seal(c), goog.loadedModules_[d] = {
exports: c,
type: goog.ModuleType.GOOG,
moduleId: goog.moduleLoaderState_.moduleName
};else throw Error('Invalid module name "' + d + '"');
} finally {
goog.moduleLoaderState_ = b;
}
};
goog.loadModuleFromSource_ = function (a) {
eval(a);
return {};
};
goog.normalizePath_ = function (a) {
a = a.split("/");
for (var b = 0; b < a.length;) "." == a[b] ? a.splice(b, 1) : b && ".." == a[b] && a[b - 1] && ".." != a[b - 1] ? a.splice(--b, 2) : b++;
return a.join("/");
};
goog.loadFileSync_ = function (a) {
if (goog.global.CLOSURE_LOAD_FILE_SYNC) return goog.global.CLOSURE_LOAD_FILE_SYNC(a);
try {
var b = new goog.global.XMLHttpRequest();
b.open("get", a, !1);
b.send();
return 0 == b.status || 200 == b.status ? b.responseText : null;
} catch (c) {
return null;
}
};
goog.transpile_ = function (a, b, c) {
var d = goog.global.$jscomp;
d || (goog.global.$jscomp = d = {});
var e = d.transpile;
if (!e) {
var f = goog.basePath + goog.TRANSPILER,
g = goog.loadFileSync_(f);
if (g) {
(function () {
(0, eval)(g + "\n//# sourceURL=" + f);
}).call(goog.global);
if (goog.global.$gwtExport && goog.global.$gwtExport.$jscomp && !goog.global.$gwtExport.$jscomp.transpile) throw Error('The transpiler did not properly export the "transpile" method. $gwtExport: ' + JSON.stringify(goog.global.$gwtExport));
goog.global.$jscomp.transpile = goog.global.$gwtExport.$jscomp.transpile;
d = goog.global.$jscomp;
e = d.transpile;
}
}
e || (e = d.transpile = function (a, b) {
goog.logToConsole_(b + " requires transpilation but no transpiler was found.");
return a;
});
return e(a, b, c);
};
goog.typeOf = function (a) {
var b = typeof a;
if ("object" == b) {
if (a) {
if (a instanceof Array) return "array";
if (a instanceof Object) return b;
var c = Object.prototype.toString.call(a);
if ("[object Window]" == c) return "object";
if ("[object Array]" == c || "number" == typeof a.length && "undefined" != typeof a.splice && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("splice")) return "array";
if ("[object Function]" == c || "undefined" != typeof a.call && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("call")) return "function";
} else return "null";
} else if ("function" == b && "undefined" == typeof a.call) return "object";
return b;
};
goog.isNull = function (a) {
return null === a;
};
goog.isDefAndNotNull = function (a) {
return null != a;
};
goog.isArray = function (a) {
return "array" == goog.typeOf(a);
};
goog.isArrayLike = function (a) {
var b = goog.typeOf(a);
return "array" == b || "object" == b && "number" == typeof a.length;
};
goog.isDateLike = function (a) {
return goog.isObject(a) && "function" == typeof a.getFullYear;
};
goog.isFunction = function (a) {
return "function" == goog.typeOf(a);
};
goog.isObject = function (a) {
var b = typeof a;
return "object" == b && null != a || "function" == b;
};
goog.getUid = function (a) {
return a[goog.UID_PROPERTY_] || (a[goog.UID_PROPERTY_] = ++goog.uidCounter_);
};
goog.hasUid = function (a) {
return !!a[goog.UID_PROPERTY_];
};
goog.removeUid = function (a) {
null !== a && "removeAttribute" in a && a.removeAttribute(goog.UID_PROPERTY_);
try {
delete a[goog.UID_PROPERTY_];
} catch (b) {}
};
goog.UID_PROPERTY_ = "closure_uid_" + (1E9 * Math.random() >>> 0);
goog.uidCounter_ = 0;
goog.getHashCode = goog.getUid;
goog.removeHashCode = goog.removeUid;
goog.cloneObject = function (a) {
var b = goog.typeOf(a);
if ("object" == b || "array" == b) {
if ("function" === typeof a.clone) return a.clone();
b = "array" == b ? [] : {};
for (var c in a) b[c] = goog.cloneObject(a[c]);
return b;
}
return a;
};
goog.bindNative_ = function (a, b, c) {
return a.call.apply(a.bind, arguments);
};
goog.bindJs_ = function (a, b, c) {
if (!a) throw Error();
if (2 < arguments.length) {
var d = Array.prototype.slice.call(arguments, 2);
return function () {
var c = Array.prototype.slice.call(arguments);
Array.prototype.unshift.apply(c, d);
return a.apply(b, c);
};
}
return function () {
return a.apply(b, arguments);
};
};
goog.bind = function (a, b, c) {
Function.prototype.bind && -1 != Function.prototype.bind.toString().indexOf("native code") ? goog.bind = goog.bindNative_ : goog.bind = goog.bindJs_;
return goog.bind.apply(null, arguments);
};
goog.partial = function (a, b) {
var c = Array.prototype.slice.call(arguments, 1);
return function () {
var b = c.slice();
b.push.apply(b, arguments);
return a.apply(this, b);
};
};
goog.mixin = function (a, b) {
for (var c in b) a[c] = b[c];
};
goog.now = goog.TRUSTED_SITE && Date.now || function () {
return +new Date();
};
goog.globalEval = function (a) {
if (goog.global.execScript) goog.global.execScript(a, "JavaScript");else if (goog.global.eval) {
if (null == goog.evalWorksForGlobals_) {
try {
goog.global.eval("var _evalTest_ = 1;");
} catch (d) {}
if ("undefined" != typeof goog.global._evalTest_) {
try {
delete goog.global._evalTest_;
} catch (d) {}
goog.evalWorksForGlobals_ = !0;
} else goog.evalWorksForGlobals_ = !1;
}
if (goog.evalWorksForGlobals_) goog.global.eval(a);else {
var b = goog.global.document,
c = b.createElement("SCRIPT");
c.type = "text/javascript";
c.defer = !1;
c.appendChild(b.createTextNode(a));
b.head.appendChild(c);
b.head.removeChild(c);
}
} else throw Error("goog.globalEval not available");
};
goog.evalWorksForGlobals_ = null;
goog.getCssName = function (a, b) {
if ("." == String(a).charAt(0)) throw Error('className passed in goog.getCssName must not start with ".". You passed: ' + a);
var c = function (a) {
return goog.cssNameMapping_[a] || a;
},
d = function (a) {
a = a.split("-");
for (var b = [], d = 0; d < a.length; d++) b.push(c(a[d]));
return b.join("-");
};
d = goog.cssNameMapping_ ? "BY_WHOLE" == goog.cssNameMappingStyle_ ? c : d : function (a) {
return a;
};
a = b ? a + "-" + d(b) : d(a);
return goog.global.CLOSURE_CSS_NAME_MAP_FN ? goog.global.CLOSURE_CSS_NAME_MAP_FN(a) : a;
};
goog.setCssNameMapping = function (a, b) {
goog.cssNameMapping_ = a;
goog.cssNameMappingStyle_ = b;
};
!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING && (goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING);
goog.getMsg = function (a, b, c) {
c && c.html && (a = a.replace(/</g, "&lt;"));
b && (a = a.replace(/\{\$([^}]+)}/g, function (a, c) {
return null != b && c in b ? b[c] : a;
}));
return a;
};
goog.getMsgWithFallback = function (a, b) {
return a;
};
goog.exportSymbol = function (a, b, c) {
goog.exportPath_(a, b, c);
};
goog.exportProperty = function (a, b, c) {
a[b] = c;
};
goog.inherits = function (a, b) {
function c() {}
c.prototype = b.prototype;
a.superClass_ = b.prototype;
a.prototype = new c();
a.prototype.constructor = a;
a.base = function (a, c, f) {
for (var d = Array(arguments.length - 2), e = 2; e < arguments.length; e++) d[e - 2] = arguments[e];
return b.prototype[c].apply(a, d);
};
};
goog.base = function (a, b, c) {
var d = arguments.callee.caller;
if (goog.STRICT_MODE_COMPATIBLE || goog.DEBUG && !d) throw Error("arguments.caller not defined. goog.base() cannot be used with strict mode code. See http://www.ecma-international.org/ecma-262/5.1/#sec-C");
if ("undefined" !== typeof d.superClass_) {
for (var e = Array(arguments.length - 1), f = 1; f < arguments.length; f++) e[f - 1] = arguments[f];
return d.superClass_.constructor.apply(a, e);
}
if ("string" != typeof b && "symbol" != typeof b) throw Error("method names provided to goog.base must be a string or a symbol");
e = Array(arguments.length - 2);
for (f = 2; f < arguments.length; f++) e[f - 2] = arguments[f];
f = !1;
for (var g = a.constructor.prototype; g; g = Object.getPrototypeOf(g)) if (g[b] === d) f = !0;else if (f) return g[b].apply(a, e);
if (a[b] === d) return a.constructor.prototype[b].apply(a, e);
throw Error("goog.base called from a method of one name to a method of a different name");
};
goog.scope = function (a) {
if (goog.isInModuleLoader_()) throw Error("goog.scope is not supported within a module.");
a.call(goog.global);
};
COMPILED || (goog.global.COMPILED = COMPILED);
goog.defineClass = function (a, b) {
var c = b.constructor,
d = b.statics;
c && c != Object.prototype.constructor || (c = function () {
throw Error("cannot instantiate an interface (no constructor defined).");
});
c = goog.defineClass.createSealingConstructor_(c, a);
a && goog.inherits(c, a);
delete b.constructor;
delete b.statics;
goog.defineClass.applyProperties_(c.prototype, b);
null != d && (d instanceof Function ? d(c) : goog.defineClass.applyProperties_(c, d));
return c;
};
goog.defineClass.SEAL_CLASS_INSTANCES = goog.DEBUG;
goog.defineClass.createSealingConstructor_ = function (a, b) {
if (!goog.defineClass.SEAL_CLASS_INSTANCES) return a;
var c = !goog.defineClass.isUnsealable_(b),
d = function () {
var b = a.apply(this, arguments) || this;
b[goog.UID_PROPERTY_] = b[goog.UID_PROPERTY_];
this.constructor === d && c && Object.seal instanceof Function && Object.seal(b);
return b;
};
return d;
};
goog.defineClass.isUnsealable_ = function (a) {
return a && a.prototype && a.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_];
};
goog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = "constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");
goog.defineClass.applyProperties_ = function (a, b) {
for (var c in b) Object.prototype.hasOwnProperty.call(b, c) && (a[c] = b[c]);
for (var d = 0; d < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; d++) c = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[d], Object.prototype.hasOwnProperty.call(b, c) && (a[c] = b[c]);
};
goog.tagUnsealableClass = function (a) {
!COMPILED && goog.defineClass.SEAL_CLASS_INSTANCES && (a.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_] = !0);
};
goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_ = "goog_defineClass_legacy_unsealable";
!COMPILED && goog.DEPENDENCIES_ENABLED && (goog.inHtmlDocument_ = function () {
var a = goog.global.document;
return null != a && "write" in a;
}, goog.isDocumentLoading_ = function () {
var a = goog.global.document;
return a.attachEvent ? "complete" != a.readyState : "loading" == a.readyState;
}, goog.findBasePath_ = function () {
if (goog.isDef(goog.global.CLOSURE_BASE_PATH) && goog.isString(goog.global.CLOSURE_BASE_PATH)) goog.basePath = goog.global.CLOSURE_BASE_PATH;else if (goog.inHtmlDocument_()) {
var a = goog.global.document,
b = a.currentScript;
a = b ? [b] : a.getElementsByTagName("SCRIPT");
for (b = a.length - 1; 0 <= b; --b) {
var c = a[b].src,
d = c.lastIndexOf("?");
d = -1 == d ? c.length : d;
if ("base.js" == c.substr(d - 7, 7)) {
goog.basePath = c.substr(0, d - 7);
break;
}
}
}
}, goog.findBasePath_(), goog.Transpiler = function () {
this.requiresTranspilation_ = null;
this.transpilationTarget_ = goog.TRANSPILE_TO_LANGUAGE;
}, goog.Transpiler.prototype.createRequiresTranspilation_ = function () {
function a(a, b) {
e ? d[a] = !0 : b() ? (c = a, d[a] = !1) : e = d[a] = !0;
}
function b(a) {
try {
return !!eval(a);
} catch (h) {
return !1;
}
}
var c = "es3",
d = {
es3: !1
},
e = !1,
f = goog.global.navigator && goog.global.navigator.userAgent ? goog.global.navigator.userAgent : "";
a("es5", function () {
return b("[1,].length==1");
});
a("es6", function () {
return f.match(/Edge\/(\d+)(\.\d)*/i) ? !1 : b('(()=>{"use strict";class X{constructor(){if(new.target!=String)throw 1;this.x=42}}let q=Reflect.construct(X,[],String);if(q.x!=42||!(q instanceof String))throw 1;for(const a of[2,3]){if(a==2)continue;function f(z={a}){let a=0;return z.a}{function f(){return 0;}}return f()==3}})()');
});
a("es7", function () {
return b("2 ** 2 == 4");
});
a("es8", function () {
return b("async () => 1, true");
});
a("es9", function () {
return b("({...rest} = {}), true");
});
a("es_next", function () {
return !1;
});
return {
target: c,
map: d
};
}, goog.Transpiler.prototype.needsTranspile = function (a, b) {
if ("always" == goog.TRANSPILE) return !0;
if ("never" == goog.TRANSPILE) return !1;
if (!this.requiresTranspilation_) {
var c = this.createRequiresTranspilation_();
this.requiresTranspilation_ = c.map;
this.transpilationTarget_ = this.transpilationTarget_ || c.target;
}
if (a in this.requiresTranspilation_) return this.requiresTranspilation_[a] ? !0 : !goog.inHtmlDocument_() || "es6" != b || "noModule" in goog.global.document.createElement("script") ? !1 : !0;
throw Error("Unknown language mode: " + a);
}, goog.Transpiler.prototype.transpile = function (a, b) {
return goog.transpile_(a, b, this.transpilationTarget_);
}, goog.transpiler_ = new goog.Transpiler(), goog.protectScriptTag_ = function (a) {
return a.replace(/<\/(SCRIPT)/ig, "\\x3c/$1");
}, goog.DebugLoader_ = function () {
this.dependencies_ = {};
this.idToPath_ = {};
this.written_ = {};
this.loadingDeps_ = [];
this.depsToLoad_ = [];
this.paused_ = !1;
this.factory_ = new goog.DependencyFactory(goog.transpiler_);
this.deferredCallbacks_ = {};
this.deferredQueue_ = [];
}, goog.DebugLoader_.prototype.bootstrap = function (a, b) {
function c() {
d && (goog.global.setTimeout(d, 0), d = null);
}
var d = b;
if (a.length) {
b = [];
for (var e = 0; e < a.length; e++) {
var f = this.getPathFromDeps_(a[e]);
if (!f) throw Error("Unregonized namespace: " + a[e]);
b.push(this.dependencies_[f]);
}
f = goog.require;
var g = 0;
for (e = 0; e < a.length; e++) f(a[e]), b[e].onLoad(function () {
++g == a.length && c();
});
} else c();
}, goog.DebugLoader_.prototype.loadClosureDeps = function () {
this.depsToLoad_.push(this.factory_.createDependency(goog.normalizePath_(goog.basePath + "deps.js"), "deps.js", [], [], {}, !1));
this.loadDeps_();
}, goog.DebugLoader_.prototype.requested = function (a, b) {
(a = this.getPathFromDeps_(a)) && (b || this.areDepsLoaded_(this.dependencies_[a].requires)) && (b = this.deferredCallbacks_[a]) && (delete this.deferredCallbacks_[a], b());
}, goog.DebugLoader_.prototype.setDependencyFactory = function (a) {
this.factory_ = a;
}, goog.DebugLoader_.prototype.load_ = function (a) {
if (this.getPathFromDeps_(a)) {
var b = this,
c = [],
d = function (a) {
var e = b.getPathFromDeps_(a);
if (!e) throw Error("Bad dependency path or symbol: " + a);
if (!b.written_[e]) {
b.written_[e] = !0;
a = b.dependencies_[e];
for (e = 0; e < a.requires.length; e++) goog.isProvided_(a.requires[e]) || d(a.requires[e]);
c.push(a);
}
};
d(a);
a = !!this.depsToLoad_.length;
this.depsToLoad_ = this.depsToLoad_.concat(c);
this.paused_ || a || this.loadDeps_();
} else throw a = "goog.require could not find: " + a, goog.logToConsole_(a), Error(a);
}, goog.DebugLoader_.prototype.loadDeps_ = function () {
for (var a = this, b = this.paused_; this.depsToLoad_.length && !b;) (function () {
var c = !1,
d = a.depsToLoad_.shift(),
e = !1;
a.loading_(d);
var f = {
pause: function () {
if (c) throw Error("Cannot call pause after the call to load.");
b = !0;
},
resume: function () {
c ? a.resume_() : b = !1;
},
loaded: function () {
if (e) throw Error("Double call to loaded.");
e = !0;
a.loaded_(d);
},
pending: function () {
for (var b = [], c = 0; c < a.loadingDeps_.length; c++) b.push(a.loadingDeps_[c]);
return b;
},
setModuleState: function (a) {
goog.moduleLoaderState_ = {
type: a,
moduleName: "",
declareLegacyNamespace: !1
};
},
registerEs6ModuleExports: function (a, b, c) {
c && (goog.loadedModules_[c] = {
exports: b,
type: goog.ModuleType.ES6,
moduleId: c || ""
});
},
registerGoogModuleExports: function (a, b) {
goog.loadedModules_[a] = {
exports: b,
type: goog.ModuleType.GOOG,
moduleId: a
};
},
clearModuleState: function () {
goog.moduleLoaderState_ = null;
},
defer: function (b) {
if (c) throw Error("Cannot register with defer after the call to load.");
a.defer_(d, b);
},
areDepsLoaded: function () {
return a.areDepsLoaded_(d.requires);
}
};
try {
d.load(f);
} finally {
c = !0;
}
})();
b && this.pause_();
}, goog.DebugLoader_.prototype.pause_ = function () {
this.paused_ = !0;
}, goog.DebugLoader_.prototype.resume_ = function () {
this.paused_ && (this.paused_ = !1, this.loadDeps_());
}, goog.DebugLoader_.prototype.loading_ = function (a) {
this.loadingDeps_.push(a);
}, goog.DebugLoader_.prototype.loaded_ = function (a) {
for (var b = 0; b < this.loadingDeps_.length; b++) if (this.loadingDeps_[b] == a) {
this.loadingDeps_.splice(b, 1);
break;
}
for (b = 0; b < this.deferredQueue_.length; b++) if (this.deferredQueue_[b] == a.path) {
this.deferredQueue_.splice(b, 1);
break;
}
if (this.loadingDeps_.length == this.deferredQueue_.length && !this.depsToLoad_.length) for (; this.deferredQueue_.length;) this.requested(this.deferredQueue_.shift(), !0);
a.loaded();
}, goog.DebugLoader_.prototype.areDepsLoaded_ = function (a) {
for (var b = 0; b < a.length; b++) {
var c = this.getPathFromDeps_(a[b]);
if (!c || !(c in this.deferredCallbacks_ || goog.isProvided_(a[b]))) return !1;
}
return !0;
}, goog.DebugLoader_.prototype.getPathFromDeps_ = function (a) {
return a in this.idToPath_ ? this.idToPath_[a] : a in this.dependencies_ ? a : null;
}, goog.DebugLoader_.prototype.defer_ = function (a, b) {
this.deferredCallbacks_[a.path] = b;
this.deferredQueue_.push(a.path);
}, goog.LoadController = function () {}, goog.LoadController.prototype.pause = function () {}, goog.LoadController.prototype.resume = function () {}, goog.LoadController.prototype.loaded = function () {}, goog.LoadController.prototype.pending = function () {}, goog.LoadController.prototype.registerEs6ModuleExports = function (a, b, c) {}, goog.LoadController.prototype.setModuleState = function (a) {}, goog.LoadController.prototype.clearModuleState = function () {}, goog.LoadController.prototype.defer = function (a) {}, goog.LoadController.prototype.areDepsLoaded = function () {}, goog.Dependency = function (a, b, c, d, e) {
this.path = a;
this.relativePath = b;
this.provides = c;
this.requires = d;
this.loadFlags = e;
this.loaded_ = !1;
this.loadCallbacks_ = [];
}, goog.Dependency.prototype.getPathName = function () {
var a = this.path,
b = a.indexOf("://");
0 <= b && (a = a.substring(b + 3), b = a.indexOf("/"), 0 <= b && (a = a.substring(b + 1)));
return a;
}, goog.Dependency.prototype.onLoad = function (a) {
this.loaded_ ? a() : this.loadCallbacks_.push(a);
}, goog.Dependency.prototype.loaded = function () {
this.loaded_ = !0;
var a = this.loadCallbacks_;
this.loadCallbacks_ = [];
for (var b = 0; b < a.length; b++) a[b]();
}, goog.Dependency.defer_ = !1, goog.Dependency.callbackMap_ = {}, goog.Dependency.registerCallback_ = function (a) {
var b = Math.random().toString(32);
goog.Dependency.callbackMap_[b] = a;
return b;
}, goog.Dependency.unregisterCallback_ = function (a) {
delete goog.Dependency.callbackMap_[a];
}, goog.Dependency.callback_ = function (a, b) {
if (a in goog.Dependency.callbackMap_) {
for (var c = goog.Dependency.callbackMap_[a], d = [], e = 1; e < arguments.length; e++) d.push(arguments[e]);
c.apply(void 0, d);
} else throw Error("Callback key " + a + " does not exist (was base.js loaded more than once?).");
}, goog.Dependency.prototype.load = function (a) {
if (goog.global.CLOSURE_IMPORT_SCRIPT) goog.global.CLOSURE_IMPORT_SCRIPT(this.path) ? a.loaded() : a.pause();else if (goog.inHtmlDocument_()) {
var b = goog.global.document;
if ("complete" == b.readyState && !goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING) {
if (/\bdeps.js$/.test(this.path)) {
a.loaded();
return;
}
throw Error('Cannot write "' + this.path + '" after document load');
}
if (!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING && goog.isDocumentLoading_()) {
var c = goog.Dependency.registerCallback_(function (b) {
goog.DebugLoader_.IS_OLD_IE_ && "complete" != b.readyState || (goog.Dependency.unregisterCallback_(c), a.loaded());
}),
d = !goog.DebugLoader_.IS_OLD_IE_ && goog.getScriptNonce() ? ' nonce="' + goog.getScriptNonce() + '"' : "";
d = '<script src="' + this.path + '" ' + (goog.DebugLoader_.IS_OLD_IE_ ? "onreadystatechange" : "onload") + "=\"goog.Dependency.callback_('" + c + '\', this)" type="text/javascript" ' + (goog.Dependency.defer_ ? "defer" : "") + d + ">\x3c/script>";
b.write(goog.TRUSTED_TYPES_POLICY_ ? goog.TRUSTED_TYPES_POLICY_.createHTML(d) : d);
} else {
var e = b.createElement("script");
e.defer = goog.Dependency.defer_;
e.async = !1;
e.type = "text/javascript";
(d = goog.getScriptNonce()) && e.setAttribute("nonce", d);
goog.DebugLoader_.IS_OLD_IE_ ? (a.pause(), e.onreadystatechange = function () {
if ("loaded" == e.readyState || "complete" == e.readyState) a.loaded(), a.resume();
}) : e.onload = function () {
e.onload = null;
a.loaded();
};
e.src = goog.TRUSTED_TYPES_POLICY_ ? goog.TRUSTED_TYPES_POLICY_.createScriptURL(this.path) : this.path;
b.head.appendChild(e);
}
} else goog.logToConsole_("Cannot use default debug loader outside of HTML documents."), "deps.js" == this.relativePath ? (goog.logToConsole_("Consider setting CLOSURE_IMPORT_SCRIPT before loading base.js, or setting CLOSURE_NO_DEPS to true."), a.loaded()) : a.pause();
}, goog.Es6ModuleDependency = function (a, b, c, d, e) {
goog.Dependency.call(this, a, b, c, d, e);
}, goog.inherits(goog.Es6ModuleDependency, goog.Dependency), goog.Es6ModuleDependency.prototype.load = function (a) {
function b(a, b) {
a = b ? '<script type="module" crossorigin>' + b + "\x3c/script>" : '<script type="module" crossorigin src="' + a + '">\x3c/script>';
d.write(goog.TRUSTED_TYPES_POLICY_ ? goog.TRUSTED_TYPES_POLICY_.createHTML(a) : a);
}
function c(a, b) {
var c = d.createElement("script");
c.defer = !0;
c.async = !1;
c.type = "module";
c.setAttribute("crossorigin", !0);
var e = goog.getScriptNonce();
e && c.setAttribute("nonce", e);
b ? c.textContent = goog.TRUSTED_TYPES_POLICY_ ? goog.TRUSTED_TYPES_POLICY_.createScript(b) : b : c.src = goog.TRUSTED_TYPES_POLICY_ ? goog.TRUSTED_TYPES_POLICY_.createScriptURL(a) : a;
d.head.appendChild(c);
}
if (goog.global.CLOSURE_IMPORT_SCRIPT) goog.global.CLOSURE_IMPORT_SCRIPT(this.path) ? a.loaded() : a.pause();else if (goog.inHtmlDocument_()) {
var d = goog.global.document,
e = this;
if (goog.isDocumentLoading_()) {
var f = b;
goog.Dependency.defer_ = !0;
} else f = c;
var g = goog.Dependency.registerCallback_(function () {
goog.Dependency.unregisterCallback_(g);
a.setModuleState(goog.ModuleType.ES6);
});
f(void 0, 'goog.Dependency.callback_("' + g + '")');
f(this.path, void 0);
var h = goog.Dependency.registerCallback_(function (b) {
goog.Dependency.unregisterCallback_(h);
a.registerEs6ModuleExports(e.path, b, goog.moduleLoaderState_.moduleName);
});
f(void 0, 'import * as m from "' + this.path + '"; goog.Dependency.callback_("' + h + '", m)');
var k = goog.Dependency.registerCallback_(function () {
goog.Dependency.unregisterCallback_(k);
a.clearModuleState();
a.loaded();
});
f(void 0, 'goog.Dependency.callback_("' + k + '")');
} else goog.logToConsole_("Cannot use default debug loader outside of HTML documents."), a.pause();
}, goog.TransformedDependency = function (a, b, c, d, e) {
goog.Dependency.call(this, a, b, c, d, e);
this.contents_ = null;
this.lazyFetch_ = !goog.inHtmlDocument_() || !("noModule" in goog.global.document.createElement("script"));
}, goog.inherits(goog.TransformedDependency, goog.Dependency), goog.TransformedDependency.prototype.load = function (a) {
function b() {
e.contents_ = goog.loadFileSync_(e.path);
e.contents_ && (e.contents_ = e.transform(e.contents_), e.contents_ && (e.contents_ += "\n//# sourceURL=" + e.path));
}
function c() {
e.lazyFetch_ && b();
if (e.contents_) {
f && a.setModuleState(goog.ModuleType.ES6);
try {
var c = e.contents_;
e.contents_ = null;
goog.globalEval(c);
if (f) var d = goog.moduleLoaderState_.moduleName;
} finally {
f && a.clearModuleState();
}
f && goog.global.$jscomp.require.ensure([e.getPathName()], function () {
a.registerEs6ModuleExports(e.path, goog.global.$jscomp.require(e.getPathName()), d);
});
a.loaded();
}
}
function d() {
var a = goog.global.document,
b = goog.Dependency.registerCallback_(function () {
goog.Dependency.unregisterCallback_(b);
c();
}),
d = '<script type="text/javascript">' + goog.protectScriptTag_('goog.Dependency.callback_("' + b + '");') + "\x3c/script>";
a.write(goog.TRUSTED_TYPES_POLICY_ ? goog.TRUSTED_TYPES_POLICY_.createHTML(d) : d);
}
var e = this;
if (goog.global.CLOSURE_IMPORT_SCRIPT) b(), this.contents_ && goog.global.CLOSURE_IMPORT_SCRIPT("", this.contents_) ? (this.contents_ = null, a.loaded()) : a.pause();else {
var f = this.loadFlags.module == goog.ModuleType.ES6;
this.lazyFetch_ || b();
var g = 1 < a.pending().length,
h = g && goog.DebugLoader_.IS_OLD_IE_;
g = goog.Dependency.defer_ && (g || goog.isDocumentLoading_());
if (h || g) a.defer(function () {
c();
});else {
var k = goog.global.document;
h = goog.inHtmlDocument_() && "ActiveXObject" in goog.global;
if (f && goog.inHtmlDocument_() && goog.isDocumentLoading_() && !h) {
goog.Dependency.defer_ = !0;
a.pause();
var l = k.onreadystatechange;
k.onreadystatechange = function () {
"interactive" == k.readyState && (k.onreadystatechange = l, c(), a.resume());
goog.isFunction(l) && l.apply(void 0, arguments);
};
} else !goog.DebugLoader_.IS_OLD_IE_ && goog.inHtmlDocument_() && goog.isDocumentLoading_() ? d() : c();
}
}
}, goog.TransformedDependency.prototype.transform = function (a) {}, goog.TranspiledDependency = function (a, b, c, d, e, f) {
goog.TransformedDependency.call(this, a, b, c, d, e);
this.transpiler = f;
}, goog.inherits(goog.TranspiledDependency, goog.TransformedDependency), goog.TranspiledDependency.prototype.transform = function (a) {
return this.transpiler.transpile(a, this.getPathName());
}, goog.PreTranspiledEs6ModuleDependency = function (a, b, c, d, e) {
goog.TransformedDependency.call(this, a, b, c, d, e);
}, goog.inherits(goog.PreTranspiledEs6ModuleDependency, goog.TransformedDependency), goog.PreTranspiledEs6ModuleDependency.prototype.transform = function (a) {
return a;
}, goog.GoogModuleDependency = function (a, b, c, d, e, f, g) {
goog.TransformedDependency.call(this, a, b, c, d, e);
this.needsTranspile_ = f;
this.transpiler_ = g;
}, goog.inherits(goog.GoogModuleDependency, goog.TransformedDependency), goog.GoogModuleDependency.prototype.transform = function (a) {
this.needsTranspile_ && (a = this.transpiler_.transpile(a, this.getPathName()));
return goog.LOAD_MODULE_USING_EVAL && goog.isDef(goog.global.JSON) ? "goog.loadModule(" + goog.global.JSON.stringify(a + "\n//# sourceURL=" + this.path + "\n") + ");" : 'goog.loadModule(function(exports) {"use strict";' + a + "\n;return exports});\n//# sourceURL=" + this.path + "\n";
}, goog.DebugLoader_.IS_OLD_IE_ = !(goog.global.atob || !goog.global.document || !goog.global.document.all), goog.DebugLoader_.prototype.addDependency = function (a, b, c, d) {
b = b || [];
a = a.replace(/\\/g, "/");
var e = goog.normalizePath_(goog.basePath + a);
d && "boolean" !== typeof d || (d = d ? {
module: goog.ModuleType.GOOG
} : {});
c = this.factory_.createDependency(e, a, b, c, d, goog.transpiler_.needsTranspile(d.lang || "es3", d.module));
this.dependencies_[e] = c;
for (c = 0; c < b.length; c++) this.idToPath_[b[c]] = e;
this.idToPath_[a] = e;
}, goog.DependencyFactory = function (a) {
this.transpiler = a;
}, goog.DependencyFactory.prototype.createDependency = function (a, b, c, d, e, f) {
return e.module == goog.ModuleType.GOOG ? new goog.GoogModuleDependency(a, b, c, d, e, f, this.transpiler) : f ? new goog.TranspiledDependency(a, b, c, d, e, this.transpiler) : e.module == goog.ModuleType.ES6 ? "never" == goog.TRANSPILE && goog.ASSUME_ES_MODULES_TRANSPILED ? new goog.PreTranspiledEs6ModuleDependency(a, b, c, d, e) : new goog.Es6ModuleDependency(a, b, c, d, e) : new goog.Dependency(a, b, c, d, e);
}, goog.debugLoader_ = new goog.DebugLoader_(), goog.loadClosureDeps = function () {
goog.debugLoader_.loadClosureDeps();
}, goog.setDependencyFactory = function (a) {
goog.debugLoader_.setDependencyFactory(a);
}, goog.global.CLOSURE_NO_DEPS || goog.debugLoader_.loadClosureDeps(), goog.bootstrap = function (a, b) {
goog.debugLoader_.bootstrap(a, b);
});
goog.TRUSTED_TYPES_POLICY_NAME = "";
goog.identity_ = function (a) {
return a;
};
goog.createTrustedTypesPolicy = function (a) {
var b = null;
if ("undefined" === typeof TrustedTypes || !TrustedTypes.createPolicy) return b;
try {
b = TrustedTypes.createPolicy(a, {
createHTML: goog.identity_,
createScript: goog.identity_,
createScriptURL: goog.identity_,
createURL: goog.identity_
});
} catch (c) {
goog.logToConsole_(c.message);
}
return b;
};
goog.TRUSTED_TYPES_POLICY_ = goog.TRUSTED_TYPES_POLICY_NAME ? goog.createTrustedTypesPolicy(goog.TRUSTED_TYPES_POLICY_NAME + "#base") : null;
var jspb = {
BinaryConstants: {},
ConstBinaryMessage: function () {},
BinaryMessage: function () {}
};
jspb.BinaryConstants.FieldType = {
INVALID: -1,
DOUBLE: 1,
FLOAT: 2,
INT64: 3,
UINT64: 4,
INT32: 5,
FIXED64: 6,
FIXED32: 7,
BOOL: 8,
STRING: 9,
GROUP: 10,
MESSAGE: 11,
BYTES: 12,
UINT32: 13,
ENUM: 14,
SFIXED32: 15,
SFIXED64: 16,
SINT32: 17,
SINT64: 18,
FHASH64: 30,
VHASH64: 31
};
jspb.BinaryConstants.WireType = {
INVALID: -1,
VARINT: 0,
FIXED64: 1,
DELIMITED: 2,
START_GROUP: 3,
END_GROUP: 4,
FIXED32: 5
};
jspb.BinaryConstants.FieldTypeToWireType = function (a) {
var b = jspb.BinaryConstants.FieldType,
c = jspb.BinaryConstants.WireType;
switch (a) {
case b.INT32:
case b.INT64:
case b.UINT32:
case b.UINT64:
case b.SINT32:
case b.SINT64:
case b.BOOL:
case b.ENUM:
case b.VHASH64:
return c.VARINT;
case b.DOUBLE:
case b.FIXED64:
case b.SFIXED64:
case b.FHASH64:
return c.FIXED64;
case b.STRING:
case b.MESSAGE:
case b.BYTES:
return c.DELIMITED;
case b.FLOAT:
case b.FIXED32:
case b.SFIXED32:
return c.FIXED32;
default:
return c.INVALID;
}
};
jspb.BinaryConstants.INVALID_FIELD_NUMBER = -1;
jspb.BinaryConstants.FLOAT32_EPS = 1.401298464324817E-45;
jspb.BinaryConstants.FLOAT32_MIN = 1.1754943508222875E-38;
jspb.BinaryConstants.FLOAT32_MAX = 3.4028234663852886E38;
jspb.BinaryConstants.FLOAT64_EPS = 4.9E-324;
jspb.BinaryConstants.FLOAT64_MIN = 2.2250738585072014E-308;
jspb.BinaryConstants.FLOAT64_MAX = 1.7976931348623157E308;
jspb.BinaryConstants.TWO_TO_20 = 1048576;
jspb.BinaryConstants.TWO_TO_23 = 8388608;
jspb.BinaryConstants.TWO_TO_31 = 2147483648;
jspb.BinaryConstants.TWO_TO_32 = 4294967296;
jspb.BinaryConstants.TWO_TO_52 = 4503599627370496;
jspb.BinaryConstants.TWO_TO_63 = 0x7fffffffffffffff;
jspb.BinaryConstants.TWO_TO_64 = 1.8446744073709552E19;
jspb.BinaryConstants.ZERO_HASH = "\x00\x00\x00\x00\x00\x00\x00\x00";
goog.dom = {};
goog.dom.NodeType = {
ELEMENT: 1,
ATTRIBUTE: 2,
TEXT: 3,
CDATA_SECTION: 4,
ENTITY_REFERENCE: 5,
ENTITY: 6,
PROCESSING_INSTRUCTION: 7,
COMMENT: 8,
DOCUMENT: 9,
DOCUMENT_TYPE: 10,
DOCUMENT_FRAGMENT: 11,
NOTATION: 12
};
goog.debug = {};
goog.debug.Error = function (a) {
if (Error.captureStackTrace) Error.captureStackTrace(this, goog.debug.Error);else {
var b = Error().stack;
b && (this.stack = b);
}
a && (this.message = String(a));
this.reportErrorToServer = !0;
};
goog.inherits(goog.debug.Error, Error);
goog.debug.Error.prototype.name = "CustomError";
goog.asserts = {};
goog.asserts.ENABLE_ASSERTS = goog.DEBUG;
goog.asserts.AssertionError = function (a, b) {
goog.debug.Error.call(this, goog.asserts.subs_(a, b));
this.messagePattern = a;
};
goog.inherits(goog.asserts.AssertionError, goog.debug.Error);
goog.asserts.AssertionError.prototype.name = "AssertionError";
goog.asserts.DEFAULT_ERROR_HANDLER = function (a) {
throw a;
};
goog.asserts.errorHandler_ = goog.asserts.DEFAULT_ERROR_HANDLER;
goog.asserts.subs_ = function (a, b) {
a = a.split("%s");
for (var c = "", d = a.length - 1, e = 0; e < d; e++) c += a[e] + (e < b.length ? b[e] : "%s");
return c + a[d];
};
goog.asserts.doAssertFailure_ = function (a, b, c, d) {
var e = "Assertion failed";
if (c) {
e += ": " + c;
var f = d;
} else a && (e += ": " + a, f = b);
a = new goog.asserts.AssertionError("" + e, f || []);
goog.asserts.errorHandler_(a);
};
goog.asserts.setErrorHandler = function (a) {
goog.asserts.ENABLE_ASSERTS && (goog.asserts.errorHandler_ = a);
};
goog.asserts.assert = function (a, b, c) {
goog.asserts.ENABLE_ASSERTS && !a && goog.asserts.doAssertFailure_("", null, b, Array.prototype.slice.call(arguments, 2));
return a;
};
goog.asserts.assertExists = function (a, b, c) {
goog.asserts.ENABLE_ASSERTS && null == a && goog.asserts.doAssertFailure_("Expected to exist: %s.", [a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
goog.asserts.fail = function (a, b) {
goog.asserts.ENABLE_ASSERTS && goog.asserts.errorHandler_(new goog.asserts.AssertionError("Failure" + (a ? ": " + a : ""), Array.prototype.slice.call(arguments, 1)));
};
goog.asserts.assertNumber = function (a, b, c) {
goog.asserts.ENABLE_ASSERTS && !goog.isNumber(a) && goog.asserts.doAssertFailure_("Expected number but got %s: %s.", [goog.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
goog.asserts.assertString = function (a, b, c) {
goog.asserts.ENABLE_ASSERTS && !goog.isString(a) && goog.asserts.doAssertFailure_("Expected string but got %s: %s.", [goog.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
goog.asserts.assertFunction = function (a, b, c) {
goog.asserts.ENABLE_ASSERTS && !goog.isFunction(a) && goog.asserts.doAssertFailure_("Expected function but got %s: %s.", [goog.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
goog.asserts.assertObject = function (a, b, c) {
goog.asserts.ENABLE_ASSERTS && !goog.isObject(a) && goog.asserts.doAssertFailure_("Expected object but got %s: %s.", [goog.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
goog.asserts.assertArray = function (a, b, c) {
goog.asserts.ENABLE_ASSERTS && !goog.isArray(a) && goog.asserts.doAssertFailure_("Expected array but got %s: %s.", [goog.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
goog.asserts.assertBoolean = function (a, b, c) {
goog.asserts.ENABLE_ASSERTS && !goog.isBoolean(a) && goog.asserts.doAssertFailure_("Expected boolean but got %s: %s.", [goog.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
goog.asserts.assertElement = function (a, b, c) {
!goog.asserts.ENABLE_ASSERTS || goog.isObject(a) && a.nodeType == goog.dom.NodeType.ELEMENT || goog.asserts.doAssertFailure_("Expected Element but got %s: %s.", [goog.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
goog.asserts.assertInstanceof = function (a, b, c, d) {
!goog.asserts.ENABLE_ASSERTS || a instanceof b || goog.asserts.doAssertFailure_("Expected instanceof %s but got %s.", [goog.asserts.getType_(b), goog.asserts.getType_(a)], c, Array.prototype.slice.call(arguments, 3));
return a;
};
goog.asserts.assertFinite = function (a, b, c) {
!goog.asserts.ENABLE_ASSERTS || "number" == typeof a && isFinite(a) || goog.asserts.doAssertFailure_("Expected %s to be a finite number but it is not.", [a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
goog.asserts.assertObjectPrototypeIsIntact = function () {
for (var a in Object.prototype) goog.asserts.fail(a + " should not be enumerable in Object.prototype.");
};
goog.asserts.getType_ = function (a) {
return a instanceof Function ? a.displayName || a.name || "unknown type name" : a instanceof Object ? a.constructor.displayName || a.constructor.name || Object.prototype.toString.call(a) : null === a ? "null" : typeof a;
};
goog.array = {};
goog.NATIVE_ARRAY_PROTOTYPES = goog.TRUSTED_SITE;
goog.array.ASSUME_NATIVE_FUNCTIONS = 2012 < goog.FEATURESET_YEAR;
goog.array.peek = function (a) {
return a[a.length - 1];
};
goog.array.last = goog.array.peek;
goog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ? function (a, b, c) {
goog.asserts.assert(null != a.length);
return Array.prototype.indexOf.call(a, b, c);
} : function (a, b, c) {
c = null == c ? 0 : 0 > c ? Math.max(0, a.length + c) : c;
if (goog.isString(a)) return goog.isString(b) && 1 == b.length ? a.indexOf(b, c) : -1;
for (; c < a.length; c++) if (c in a && a[c] === b) return c;
return -1;
};
goog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ? function (a, b, c) {
goog.asserts.assert(null != a.length);
return Array.prototype.lastIndexOf.call(a, b, null == c ? a.length - 1 : c);
} : function (a, b, c) {
c = null == c ? a.length - 1 : c;
0 > c && (c = Math.max(0, a.length + c));
if (goog.isString(a)) return goog.isString(b) && 1 == b.length ? a.lastIndexOf(b, c) : -1;
for (; 0 <= c; c--) if (c in a && a[c] === b) return c;
return -1;
};
goog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ? function (a, b, c) {
goog.asserts.assert(null != a.length);
Array.prototype.forEach.call(a, b, c);
} : function (a, b, c) {
for (var d = a.length, e = goog.isString(a) ? a.split("") : a, f = 0; f < d; f++) f in e && b.call(c, e[f], f, a);
};
goog.array.forEachRight = function (a, b, c) {
var d = a.length,
e = goog.isString(a) ? a.split("") : a;
for (--d; 0 <= d; --d) d in e && b.call(c, e[d], d, a);
};
goog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ? function (a, b, c) {
goog.asserts.assert(null != a.length);
return Array.prototype.filter.call(a, b, c);
} : function (a, b, c) {
for (var d = a.length, e = [], f = 0, g = goog.isString(a) ? a.split("") : a, h = 0; h < d; h++) if (h in g) {
var k = g[h];
b.call(c, k, h, a) && (e[f++] = k);
}
return e;
};
goog.array.map = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ? function (a, b, c) {
goog.asserts.assert(null != a.length);
return Array.prototype.map.call(a, b, c);
} : function (a, b, c) {
for (var d = a.length, e = Array(d), f = goog.isString(a) ? a.split("") : a, g = 0; g < d; g++) g in f && (e[g] = b.call(c, f[g], g, a));
return e;
};
goog.array.reduce = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ? function (a, b, c, d) {
goog.asserts.assert(null != a.length);
d && (b = goog.bind(b, d));
return Array.prototype.reduce.call(a, b, c);
} : function (a, b, c, d) {
var e = c;
goog.array.forEach(a, function (c, g) {
e = b.call(d, e, c, g, a);
});
return e;
};
goog.array.reduceRight = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ? function (a, b, c, d) {
goog.asserts.assert(null != a.length);
goog.asserts.assert(null != b);
d && (b = goog.bind(b, d));
return Array.prototype.reduceRight.call(a, b, c);
} : function (a, b, c, d) {
var e = c;
goog.array.forEachRight(a, function (c, g) {
e = b.call(d, e, c, g, a);
});
return e;
};
goog.array.some = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ? function (a, b, c) {
goog.asserts.assert(null != a.length);
return Array.prototype.some.call(a, b, c);
} : function (a, b, c) {
for (var d = a.length, e = goog.isString(a) ? a.split("") : a, f = 0; f < d; f++) if (f in e && b.call(c, e[f], f, a)) return !0;
return !1;
};
goog.array.every = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ? function (a, b, c) {
goog.asserts.assert(null != a.length);
return Array.prototype.every.call(a, b, c);
} : function (a, b, c) {
for (var d = a.length, e = goog.isString(a) ? a.split("") : a, f = 0; f < d; f++) if (f in e && !b.call(c, e[f], f, a)) return !1;
return !0;
};
goog.array.count = function (a, b, c) {
var d = 0;
goog.array.forEach(a, function (a, f, g) {
b.call(c, a, f, g) && ++d;
}, c);
return d;
};
goog.array.find = function (a, b, c) {
b = goog.array.findIndex(a, b, c);
return 0 > b ? null : goog.isString(a) ? a.charAt(b) : a[b];
};
goog.array.findIndex = function (a, b, c) {
for (var d = a.length, e = goog.isString(a) ? a.split("") : a, f = 0; f < d; f++) if (f in e && b.call(c, e[f], f, a)) return f;
return -1;
};
goog.array.findRight = function (a, b, c) {
b = goog.array.findIndexRight(a, b, c);
return 0 > b ? null : goog.isString(a) ? a.charAt(b) : a[b];
};
goog.array.findIndexRight = function (a, b, c) {
var d = a.length,
e = goog.isString(a) ? a.split("") : a;
for (--d; 0 <= d; d--) if (d in e && b.call(c, e[d], d, a)) return d;
return -1;
};
goog.array.contains = function (a, b) {
return 0 <= goog.array.indexOf(a, b);
};
goog.array.isEmpty = function (a) {
return 0 == a.length;
};
goog.array.clear = function (a) {
if (!goog.isArray(a)) for (var b = a.length - 1; 0 <= b; b--) delete a[b];
a.length = 0;
};
goog.array.insert = function (a, b) {
goog.array.contains(a, b) || a.push(b);
};
goog.array.insertAt = function (a, b, c) {
goog.array.splice(a, c, 0, b);
};
goog.array.insertArrayAt = function (a, b, c) {
goog.partial(goog.array.splice, a, c, 0).apply(null, b);
};
goog.array.insertBefore = function (a, b, c) {
var d;
2 == arguments.length || 0 > (d = goog.array.indexOf(a, c)) ? a.push(b) : goog.array.insertAt(a, b, d);
};
goog.array.remove = function (a, b) {
b = goog.array.indexOf(a, b);
var c;
(c = 0 <= b) && goog.array.removeAt(a, b);
return c;
};
goog.array.removeLast = function (a, b) {
b = goog.array.lastIndexOf(a, b);
return 0 <= b ? (goog.array.removeAt(a, b), !0) : !1;
};
goog.array.removeAt = function (a, b) {
goog.asserts.assert(null != a.length);
return 1 == Array.prototype.splice.call(a, b, 1).length;
};
goog.array.removeIf = function (a, b, c) {
b = goog.array.findIndex(a, b, c);
return 0 <= b ? (goog.array.removeAt(a, b), !0) : !1;
};
goog.array.removeAllIf = function (a, b, c) {
var d = 0;
goog.array.forEachRight(a, function (e, f) {
b.call(c, e, f, a) && goog.array.removeAt(a, f) && d++;
});
return d;
};
goog.array.concat = function (a) {
return Array.prototype.concat.apply([], arguments);
};
goog.array.join = function (a) {
return Array.prototype.concat.apply([], arguments);
};
goog.array.toArray = function (a) {
var b = a.length;
if (0 < b) {
for (var c = Array(b), d = 0; d < b; d++) c[d] = a[d];
return c;
}
return [];
};
goog.array.clone = goog.array.toArray;
goog.array.extend = function (a, b) {
for (var c = 1; c < arguments.length; c++) {
var d = arguments[c];
if (goog.isArrayLike(d)) {
var e = a.length || 0,
f = d.length || 0;
a.length = e + f;
for (var g = 0; g < f; g++) a[e + g] = d[g];
} else a.push(d);
}
};
goog.array.splice = function (a, b, c, d) {
goog.asserts.assert(null != a.length);
return Array.prototype.splice.apply(a, goog.array.slice(arguments, 1));
};
goog.array.slice = function (a, b, c) {
goog.asserts.assert(null != a.length);
return 2 >= arguments.length ? Array.prototype.slice.call(a, b) : Array.prototype.slice.call(a, b, c);
};
goog.array.removeDuplicates = function (a, b, c) {
b = b || a;
var d = function (a) {
return goog.isObject(a) ? "o" + goog.getUid(a) : (typeof a).charAt(0) + a;
};
c = c || d;
d = {};
for (var e = 0, f = 0; f < a.length;) {
var g = a[f++],
h = c(g);
Object.prototype.hasOwnProperty.call(d, h) || (d[h] = !0, b[e++] = g);
}
b.length = e;
};
goog.array.binarySearch = function (a, b, c) {
return goog.array.binarySearch_(a, c || goog.array.defaultCompare, !1, b);
};
goog.array.binarySelect = function (a, b, c) {
return goog.array.binarySearch_(a, b, !0, void 0, c);
};
goog.array.binarySearch_ = function (a, b, c, d, e) {
for (var f = 0, g = a.length, h; f < g;) {
var k = f + g >> 1;
var l = c ? b.call(e, a[k], k, a) : b(d, a[k]);
0 < l ? f = k + 1 : (g = k, h = !l);
}
return h ? f : ~f;
};
goog.array.sort = function (a, b) {
a.sort(b || goog.array.defaultCompare);
};
goog.array.stableSort = function (a, b) {
for (var c = Array(a.length), d = 0; d < a.length; d++) c[d] = {
index: d,
value: a[d]
};
var e = b || goog.array.defaultCompare;
goog.array.sort(c, function (a, b) {
return e(a.value, b.value) || a.index - b.index;
});
for (d = 0; d < a.length; d++) a[d] = c[d].value;
};
goog.array.sortByKey = function (a, b, c) {
var d = c || goog.array.defaultCompare;
goog.array.sort(a, function (a, c) {
return d(b(a), b(c));
});
};
goog.array.sortObjectsByKey = function (a, b, c) {
goog.array.sortByKey(a, function (a) {
return a[b];
}, c);
};
goog.array.isSorted = function (a, b, c) {
b = b || goog.array.defaultCompare;
for (var d = 1; d < a.length; d++) {
var e = b(a[d - 1], a[d]);
if (0 < e || 0 == e && c) return !1;
}
return !0;
};
goog.array.equals = function (a, b, c) {
if (!goog.isArrayLike(a) || !goog.isArrayLike(b) || a.length != b.length) return !1;
var d = a.length;
c = c || goog.array.defaultCompareEquality;
for (var e = 0; e < d; e++) if (!c(a[e], b[e])) return !1;
return !0;
};
goog.array.compare3 = function (a, b, c) {
c = c || goog.array.defaultCompare;
for (var d = Math.min(a.length, b.length), e = 0; e < d; e++) {
var f = c(a[e], b[e]);
if (0 != f) return f;
}
return goog.array.defaultCompare(a.length, b.length);
};
goog.array.defaultCompare = function (a, b) {
return a > b ? 1 : a < b ? -1 : 0;
};
goog.array.inverseDefaultCompare = function (a, b) {
return -goog.array.defaultCompare(a, b);
};
goog.array.defaultCompareEquality = function (a, b) {
return a === b;
};
goog.array.binaryInsert = function (a, b, c) {
c = goog.array.binarySearch(a, b, c);
return 0 > c ? (goog.array.insertAt(a, b, -(c + 1)), !0) : !1;
};
goog.array.binaryRemove = function (a, b, c) {
b = goog.array.binarySearch(a, b, c);
return 0 <= b ? goog.array.removeAt(a, b) : !1;
};
goog.array.bucket = function (a, b, c) {
for (var d = {}, e = 0; e < a.length; e++) {
var f = a[e],
g = b.call(c, f, e, a);
goog.isDef(g) && (d[g] || (d[g] = [])).push(f);
}
return d;
};
goog.array.toObject = function (a, b, c) {
var d = {};
goog.array.forEach(a, function (e, f) {
d[b.call(c, e, f, a)] = e;
});
return d;
};
goog.array.range = function (a, b, c) {
var d = [],
e = 0,
f = a;
c = c || 1;
void 0 !== b && (e = a, f = b);
if (0 > c * (f - e)) return [];
if (0 < c) for (a = e; a < f; a += c) d.push(a);else for (a = e; a > f; a += c) d.push(a);
return d;
};
goog.array.repeat = function (a, b) {
for (var c = [], d = 0; d < b; d++) c[d] = a;
return c;
};
goog.array.flatten = function (a) {
for (var b = [], c = 0; c < arguments.length; c++) {
var d = arguments[c];
if (goog.isArray(d)) for (var e = 0; e < d.length; e += 8192) {
var f = goog.array.slice(d, e, e + 8192);
f = goog.array.flatten.apply(null, f);
for (var g = 0; g < f.length; g++) b.push(f[g]);
} else b.push(d);
}
return b;
};
goog.array.rotate = function (a, b) {
goog.asserts.assert(null != a.length);
a.length && (b %= a.length, 0 < b ? Array.prototype.unshift.apply(a, a.splice(-b, b)) : 0 > b && Array.prototype.push.apply(a, a.splice(0, -b)));
return a;
};
goog.array.moveItem = function (a, b, c) {
goog.asserts.assert(0 <= b && b < a.length);
goog.asserts.assert(0 <= c && c < a.length);
b = Array.prototype.splice.call(a, b, 1);
Array.prototype.splice.call(a, c, 0, b[0]);
};
goog.array.zip = function (a) {
if (!arguments.length) return [];
for (var b = [], c = arguments[0].length, d = 1; d < arguments.length; d++) arguments[d].length < c && (c = arguments[d].length);
for (d = 0; d < c; d++) {
for (var e = [], f = 0; f < arguments.length; f++) e.push(arguments[f][d]);
b.push(e);
}
return b;
};
goog.array.shuffle = function (a, b) {
b = b || Math.random;
for (var c = a.length - 1; 0 < c; c--) {
var d = Math.floor(b() * (c + 1)),
e = a[c];
a[c] = a[d];
a[d] = e;
}
};
goog.array.copyByIndex = function (a, b) {
var c = [];
goog.array.forEach(b, function (b) {
c.push(a[b]);
});
return c;
};
goog.array.concatMap = function (a, b, c) {
return goog.array.concat.apply([], goog.array.map(a, b, c));
};
goog.crypt = {};
goog.crypt.stringToByteArray = function (a) {
for (var b = [], c = 0, d = 0; d < a.length; d++) {
var e = a.charCodeAt(d);
255 < e && (b[c++] = e & 255, e >>= 8);
b[c++] = e;
}
return b;
};
goog.crypt.byteArrayToString = function (a) {
if (8192 >= a.length) return String.fromCharCode.apply(null, a);
for (var b = "", c = 0; c < a.length; c += 8192) {
var d = goog.array.slice(a, c, c + 8192);
b += String.fromCharCode.apply(null, d);
}
return b;
};
goog.crypt.byteArrayToHex = function (a, b) {
return goog.array.map(a, function (a) {
a = a.toString(16);
return 1 < a.length ? a : "0" + a;
}).join(b || "");
};
goog.crypt.hexToByteArray = function (a) {
goog.asserts.assert(0 == a.length % 2, "Key string length must be multiple of 2");
for (var b = [], c = 0; c < a.length; c += 2) b.push(parseInt(a.substring(c, c + 2), 16));
return b;
};
goog.crypt.stringToUtf8ByteArray = function (a) {
for (var b = [], c = 0, d = 0; d < a.length; d++) {
var e = a.charCodeAt(d);
128 > e ? b[c++] = e : (2048 > e ? b[c++] = e >> 6 | 192 : (55296 == (e & 64512) && d + 1 < a.length && 56320 == (a.charCodeAt(d + 1) & 64512) ? (e = 65536 + ((e & 1023) << 10) + (a.charCodeAt(++d) & 1023), b[c++] = e >> 18 | 240, b[c++] = e >> 12 & 63 | 128) : b[c++] = e >> 12 | 224, b[c++] = e >> 6 & 63 | 128), b[c++] = e & 63 | 128);
}
return b;
};
goog.crypt.utf8ByteArrayToString = function (a) {
for (var b = [], c = 0, d = 0; c < a.length;) {
var e = a[c++];
if (128 > e) b[d++] = String.fromCharCode(e);else if (191 < e && 224 > e) {
var f = a[c++];
b[d++] = String.fromCharCode((e & 31) << 6 | f & 63);
} else if (239 < e && 365 > e) {
f = a[c++];
var g = a[c++],
h = a[c++];
e = ((e & 7) << 18 | (f & 63) << 12 | (g & 63) << 6 | h & 63) - 65536;
b[d++] = String.fromCharCode(55296 + (e >> 10));
b[d++] = String.fromCharCode(56320 + (e & 1023));
} else f = a[c++], g = a[c++], b[d++] = String.fromCharCode((e & 15) << 12 | (f & 63) << 6 | g & 63);
}
return b.join("");
};
goog.crypt.xorByteArray = function (a, b) {
goog.asserts.assert(a.length == b.length, "XOR array lengths must match");
for (var c = [], d = 0; d < a.length; d++) c.push(a[d] ^ b[d]);
return c;
};
goog.string = {};
goog.string.internal = {};
goog.string.internal.startsWith = function (a, b) {
return 0 == a.lastIndexOf(b, 0);
};
goog.string.internal.endsWith = function (a, b) {
var c = a.length - b.length;
return 0 <= c && a.indexOf(b, c) == c;
};
goog.string.internal.caseInsensitiveStartsWith = function (a, b) {
return 0 == goog.string.internal.caseInsensitiveCompare(b, a.substr(0, b.length));
};
goog.string.internal.caseInsensitiveEndsWith = function (a, b) {
return 0 == goog.string.internal.caseInsensitiveCompare(b, a.substr(a.length - b.length, b.length));
};
goog.string.internal.caseInsensitiveEquals = function (a, b) {
return a.toLowerCase() == b.toLowerCase();
};
goog.string.internal.isEmptyOrWhitespace = function (a) {
return /^[\s\xa0]*$/.test(a);
};
goog.string.internal.trim = goog.TRUSTED_SITE && String.prototype.trim ? function (a) {
return a.trim();
} : function (a) {
return /^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(a)[1];
};
goog.string.internal.caseInsensitiveCompare = function (a, b) {
a = String(a).toLowerCase();
b = String(b).toLowerCase();
return a < b ? -1 : a == b ? 0 : 1;
};
goog.string.internal.newLineToBr = function (a, b) {
return a.replace(/(\r\n|\r|\n)/g, b ? "<br />" : "<br>");
};
goog.string.internal.htmlEscape = function (a, b) {
if (b) a = a.replace(goog.string.internal.AMP_RE_, "&amp;").replace(goog.string.internal.LT_RE_, "&lt;").replace(goog.string.internal.GT_RE_, "&gt;").replace(goog.string.internal.QUOT_RE_, "&quot;").replace(goog.string.internal.SINGLE_QUOTE_RE_, "&#39;").replace(goog.string.internal.NULL_RE_, "&#0;");else {
if (!goog.string.internal.ALL_RE_.test(a)) return a;
-1 != a.indexOf("&") && (a = a.replace(goog.string.internal.AMP_RE_, "&amp;"));
-1 != a.indexOf("<") && (a = a.replace(goog.string.internal.LT_RE_, "&lt;"));
-1 != a.indexOf(">") && (a = a.replace(goog.string.internal.GT_RE_, "&gt;"));
-1 != a.indexOf('"') && (a = a.replace(goog.string.internal.QUOT_RE_, "&quot;"));
-1 != a.indexOf("'") && (a = a.replace(goog.string.internal.SINGLE_QUOTE_RE_, "&#39;"));
-1 != a.indexOf("\x00") && (a = a.replace(goog.string.internal.NULL_RE_, "&#0;"));
}
return a;
};
goog.string.internal.AMP_RE_ = /&/g;
goog.string.internal.LT_RE_ = /</g;
goog.string.internal.GT_RE_ = />/g;
goog.string.internal.QUOT_RE_ = /"/g;
goog.string.internal.SINGLE_QUOTE_RE_ = /'/g;
goog.string.internal.NULL_RE_ = /\x00/g;
goog.string.internal.ALL_RE_ = /[\x00&<>"']/;
goog.string.internal.whitespaceEscape = function (a, b) {
return goog.string.internal.newLineToBr(a.replace(/ /g, " &#160;"), b);
};
goog.string.internal.contains = function (a, b) {
return -1 != a.indexOf(b);
};
goog.string.internal.caseInsensitiveContains = function (a, b) {
return goog.string.internal.contains(a.toLowerCase(), b.toLowerCase());
};
goog.string.internal.compareVersions = function (a, b) {
var c = 0;
a = goog.string.internal.trim(String(a)).split(".");
b = goog.string.internal.trim(String(b)).split(".");
for (var d = Math.max(a.length, b.length), e = 0; 0 == c && e < d; e++) {
var f = a[e] || "",
g = b[e] || "";
do {
f = /(\d*)(\D*)(.*)/.exec(f) || ["", "", "", ""];
g = /(\d*)(\D*)(.*)/.exec(g) || ["", "", "", ""];
if (0 == f[0].length && 0 == g[0].length) break;
c = 0 == f[1].length ? 0 : parseInt(f[1], 10);
var h = 0 == g[1].length ? 0 : parseInt(g[1], 10);
c = goog.string.internal.compareElements_(c, h) || goog.string.internal.compareElements_(0 == f[2].length, 0 == g[2].length) || goog.string.internal.compareElements_(f[2], g[2]);
f = f[3];
g = g[3];
} while (0 == c);
}
return c;
};
goog.string.internal.compareElements_ = function (a, b) {
return a < b ? -1 : a > b ? 1 : 0;
};
goog.string.TypedString = function () {};
goog.string.Const = function (a, b) {
this.stringConstValueWithSecurityContract__googStringSecurityPrivate_ = a === goog.string.Const.GOOG_STRING_CONSTRUCTOR_TOKEN_PRIVATE_ && b || "";
this.STRING_CONST_TYPE_MARKER__GOOG_STRING_SECURITY_PRIVATE_ = goog.string.Const.TYPE_MARKER_;
};
goog.string.Const.prototype.implementsGoogStringTypedString = !0;
goog.string.Const.prototype.getTypedStringValue = function () {
return this.stringConstValueWithSecurityContract__googStringSecurityPrivate_;
};
goog.string.Const.prototype.toString = function () {
return "Const{" + this.stringConstValueWithSecurityContract__googStringSecurityPrivate_ + "}";
};
goog.string.Const.unwrap = function (a) {
if (a instanceof goog.string.Const && a.constructor === goog.string.Const && a.STRING_CONST_TYPE_MARKER__GOOG_STRING_SECURITY_PRIVATE_ === goog.string.Const.TYPE_MARKER_) return a.stringConstValueWithSecurityContract__googStringSecurityPrivate_;
goog.asserts.fail("expected object of type Const, got '" + a + "'");
return "type_error:Const";
};
goog.string.Const.from = function (a) {
return new goog.string.Const(goog.string.Const.GOOG_STRING_CONSTRUCTOR_TOKEN_PRIVATE_, a);
};
goog.string.Const.TYPE_MARKER_ = {};
goog.string.Const.GOOG_STRING_CONSTRUCTOR_TOKEN_PRIVATE_ = {};
goog.string.Const.EMPTY = goog.string.Const.from("");
goog.fs = {};
goog.fs.url = {};
goog.fs.url.createObjectUrl = function (a) {
return goog.fs.url.getUrlObject_().createObjectURL(a);
};
goog.fs.url.revokeObjectUrl = function (a) {
goog.fs.url.getUrlObject_().revokeObjectURL(a);
};
goog.fs.url.getUrlObject_ = function () {
var a = goog.fs.url.findUrlObject_();
if (null != a) return a;
throw Error("This browser doesn't seem to support blob URLs");
};
goog.fs.url.findUrlObject_ = function () {
return goog.isDef(goog.global.URL) && goog.isDef(goog.global.URL.createObjectURL) ? goog.global.URL : goog.isDef(goog.global.webkitURL) && goog.isDef(goog.global.webkitURL.createObjectURL) ? goog.global.webkitURL : goog.isDef(goog.global.createObjectURL) ? goog.global : null;
};
goog.fs.url.browserSupportsObjectUrls = function () {
return null != goog.fs.url.findUrlObject_();
};
goog.html = {};
goog.html.trustedtypes = {};
goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY = goog.TRUSTED_TYPES_POLICY_NAME ? goog.createTrustedTypesPolicy(goog.TRUSTED_TYPES_POLICY_NAME + "#html") : null;
goog.i18n = {};
goog.i18n.bidi = {};
goog.i18n.bidi.FORCE_RTL = !1;
goog.i18n.bidi.IS_RTL = goog.i18n.bidi.FORCE_RTL || ("ar" == goog.LOCALE.substring(0, 2).toLowerCase() || "fa" == goog.LOCALE.substring(0, 2).toLowerCase() || "he" == goog.LOCALE.substring(0, 2).toLowerCase() || "iw" == goog.LOCALE.substring(0, 2).toLowerCase() || "ps" == goog.LOCALE.substring(0, 2).toLowerCase() || "sd" == goog.LOCALE.substring(0, 2).toLowerCase() || "ug" == goog.LOCALE.substring(0, 2).toLowerCase() || "ur" == goog.LOCALE.substring(0, 2).toLowerCase() || "yi" == goog.LOCALE.substring(0, 2).toLowerCase()) && (2 == goog.LOCALE.length || "-" == goog.LOCALE.substring(2, 3) || "_" == goog.LOCALE.substring(2, 3)) || 3 <= goog.LOCALE.length && "ckb" == goog.LOCALE.substring(0, 3).toLowerCase() && (3 == goog.LOCALE.length || "-" == goog.LOCALE.substring(3, 4) || "_" == goog.LOCALE.substring(3, 4)) || 7 <= goog.LOCALE.length && ("-" == goog.LOCALE.substring(2, 3) || "_" == goog.LOCALE.substring(2, 3)) && ("adlm" == goog.LOCALE.substring(3, 7).toLowerCase() || "arab" == goog.LOCALE.substring(3, 7).toLowerCase() || "hebr" == goog.LOCALE.substring(3, 7).toLowerCase() || "nkoo" == goog.LOCALE.substring(3, 7).toLowerCase() || "rohg" == goog.LOCALE.substring(3, 7).toLowerCase() || "thaa" == goog.LOCALE.substring(3, 7).toLowerCase()) || 8 <= goog.LOCALE.length && ("-" == goog.LOCALE.substring(3, 4) || "_" == goog.LOCALE.substring(3, 4)) && ("adlm" == goog.LOCALE.substring(4, 8).toLowerCase() || "arab" == goog.LOCALE.substring(4, 8).toLowerCase() || "hebr" == goog.LOCALE.substring(4, 8).toLowerCase() || "nkoo" == goog.LOCALE.substring(4, 8).toLowerCase() || "rohg" == goog.LOCALE.substring(4, 8).toLowerCase() || "thaa" == goog.LOCALE.substring(4, 8).toLowerCase());
goog.i18n.bidi.Format = {
LRE: "\u202a",
RLE: "\u202b",
PDF: "\u202c",
LRM: "\u200e",
RLM: "\u200f"
};
goog.i18n.bidi.Dir = {
LTR: 1,
RTL: -1,
NEUTRAL: 0
};
goog.i18n.bidi.RIGHT = "right";
goog.i18n.bidi.LEFT = "left";
goog.i18n.bidi.I18N_RIGHT = goog.i18n.bidi.IS_RTL ? goog.i18n.bidi.LEFT : goog.i18n.bidi.RIGHT;
goog.i18n.bidi.I18N_LEFT = goog.i18n.bidi.IS_RTL ? goog.i18n.bidi.RIGHT : goog.i18n.bidi.LEFT;
goog.i18n.bidi.toDir = function (a, b) {
return "number" == typeof a ? 0 < a ? goog.i18n.bidi.Dir.LTR : 0 > a ? goog.i18n.bidi.Dir.RTL : b ? null : goog.i18n.bidi.Dir.NEUTRAL : null == a ? null : a ? goog.i18n.bidi.Dir.RTL : goog.i18n.bidi.Dir.LTR;
};
goog.i18n.bidi.ltrChars_ = "A-Za-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02b8\u0300-\u0590\u0900-\u1fff\u200e\u2c00-\ud801\ud804-\ud839\ud83c-\udbff\uf900-\ufb1c\ufe00-\ufe6f\ufefd-\uffff";
goog.i18n.bidi.rtlChars_ = "\u0591-\u06ef\u06fa-\u08ff\u200f\ud802-\ud803\ud83a-\ud83b\ufb1d-\ufdff\ufe70-\ufefc";
goog.i18n.bidi.htmlSkipReg_ = /<[^>]*>|&[^;]+;/g;
goog.i18n.bidi.stripHtmlIfNeeded_ = function (a, b) {
return b ? a.replace(goog.i18n.bidi.htmlSkipReg_, "") : a;
};
goog.i18n.bidi.rtlCharReg_ = new RegExp("[" + goog.i18n.bidi.rtlChars_ + "]");
goog.i18n.bidi.ltrCharReg_ = new RegExp("[" + goog.i18n.bidi.ltrChars_ + "]");
goog.i18n.bidi.hasAnyRtl = function (a, b) {
return goog.i18n.bidi.rtlCharReg_.test(goog.i18n.bidi.stripHtmlIfNeeded_(a, b));
};
goog.i18n.bidi.hasRtlChar = goog.i18n.bidi.hasAnyRtl;
goog.i18n.bidi.hasAnyLtr = function (a, b) {
return goog.i18n.bidi.ltrCharReg_.test(goog.i18n.bidi.stripHtmlIfNeeded_(a, b));
};
goog.i18n.bidi.ltrRe_ = new RegExp("^[" + goog.i18n.bidi.ltrChars_ + "]");
goog.i18n.bidi.rtlRe_ = new RegExp("^[" + goog.i18n.bidi.rtlChars_ + "]");
goog.i18n.bidi.isRtlChar = function (a) {
return goog.i18n.bidi.rtlRe_.test(a);
};
goog.i18n.bidi.isLtrChar = function (a) {
return goog.i18n.bidi.ltrRe_.test(a);
};
goog.i18n.bidi.isNeutralChar = function (a) {
return !goog.i18n.bidi.isLtrChar(a) && !goog.i18n.bidi.isRtlChar(a);
};
goog.i18n.bidi.ltrDirCheckRe_ = new RegExp("^[^" + goog.i18n.bidi.rtlChars_ + "]*[" + goog.i18n.bidi.ltrChars_ + "]");
goog.i18n.bidi.rtlDirCheckRe_ = new RegExp("^[^" + goog.i18n.bidi.ltrChars_ + "]*[" + goog.i18n.bidi.rtlChars_ + "]");
goog.i18n.bidi.startsWithRtl = function (a, b) {
return goog.i18n.bidi.rtlDirCheckRe_.test(goog.i18n.bidi.stripHtmlIfNeeded_(a, b));
};
goog.i18n.bidi.isRtlText = goog.i18n.bidi.startsWithRtl;
goog.i18n.bidi.startsWithLtr = function (a, b) {
return goog.i18n.bidi.ltrDirCheckRe_.test(goog.i18n.bidi.stripHtmlIfNeeded_(a, b));
};
goog.i18n.bidi.isLtrText = goog.i18n.bidi.startsWithLtr;
goog.i18n.bidi.isRequiredLtrRe_ = /^http:\/\/.*/;
goog.i18n.bidi.isNeutralText = function (a, b) {
a = goog.i18n.bidi.stripHtmlIfNeeded_(a, b);
return goog.i18n.bidi.isRequiredLtrRe_.test(a) || !goog.i18n.bidi.hasAnyLtr(a) && !goog.i18n.bidi.hasAnyRtl(a);
};
goog.i18n.bidi.ltrExitDirCheckRe_ = new RegExp("[" + goog.i18n.bidi.ltrChars_ + "][^" + goog.i18n.bidi.rtlChars_ + "]*$");
goog.i18n.bidi.rtlExitDirCheckRe_ = new RegExp("[" + goog.i18n.bidi.rtlChars_ + "][^" + goog.i18n.bidi.ltrChars_ + "]*$");
goog.i18n.bidi.endsWithLtr = function (a, b) {
return goog.i18n.bidi.ltrExitDirCheckRe_.test(goog.i18n.bidi.stripHtmlIfNeeded_(a, b));
};
goog.i18n.bidi.isLtrExitText = goog.i18n.bidi.endsWithLtr;
goog.i18n.bidi.endsWithRtl = function (a, b) {
return goog.i18n.bidi.rtlExitDirCheckRe_.test(goog.i18n.bidi.stripHtmlIfNeeded_(a, b));
};
goog.i18n.bidi.isRtlExitText = goog.i18n.bidi.endsWithRtl;
goog.i18n.bidi.rtlLocalesRe_ = /^(ar|ckb|dv|he|iw|fa|nqo|ps|sd|ug|ur|yi|.*[-_](Adlm|Arab|Hebr|Nkoo|Rohg|Thaa))(?!.*[-_](Latn|Cyrl)($|-|_))($|-|_)/i;
goog.i18n.bidi.isRtlLanguage = function (a) {
return goog.i18n.bidi.rtlLocalesRe_.test(a);
};
goog.i18n.bidi.bracketGuardTextRe_ = /(\(.*?\)+)|(\[.*?\]+)|(\{.*?\}+)|(<.*?>+)/g;
goog.i18n.bidi.guardBracketInText = function (a, b) {
b = (void 0 === b ? goog.i18n.bidi.hasAnyRtl(a) : b) ? goog.i18n.bidi.Format.RLM : goog.i18n.bidi.Format.LRM;
return a.replace(goog.i18n.bidi.bracketGuardTextRe_, b + "$&" + b);
};
goog.i18n.bidi.enforceRtlInHtml = function (a) {
return "<" == a.charAt(0) ? a.replace(/<\w+/, "$& dir=rtl") : "\n<span dir=rtl>" + a + "</span>";
};
goog.i18n.bidi.enforceRtlInText = function (a) {
return goog.i18n.bidi.Format.RLE + a + goog.i18n.bidi.Format.PDF;
};
goog.i18n.bidi.enforceLtrInHtml = function (a) {
return "<" == a.charAt(0) ? a.replace(/<\w+/, "$& dir=ltr") : "\n<span dir=ltr>" + a + "</span>";
};
goog.i18n.bidi.enforceLtrInText = function (a) {
return goog.i18n.bidi.Format.LRE + a + goog.i18n.bidi.Format.PDF;
};
goog.i18n.bidi.dimensionsRe_ = /:\s*([.\d][.\w]*)\s+([.\d][.\w]*)\s+([.\d][.\w]*)\s+([.\d][.\w]*)/g;
goog.i18n.bidi.leftRe_ = /left/gi;
goog.i18n.bidi.rightRe_ = /right/gi;
goog.i18n.bidi.tempRe_ = /%%%%/g;
goog.i18n.bidi.mirrorCSS = function (a) {
return a.replace(goog.i18n.bidi.dimensionsRe_, ":$1 $4 $3 $2").replace(goog.i18n.bidi.leftRe_, "%%%%").replace(goog.i18n.bidi.rightRe_, goog.i18n.bidi.LEFT).replace(goog.i18n.bidi.tempRe_, goog.i18n.bidi.RIGHT);
};
goog.i18n.bidi.doubleQuoteSubstituteRe_ = /([\u0591-\u05f2])"/g;
goog.i18n.bidi.singleQuoteSubstituteRe_ = /([\u0591-\u05f2])'/g;
goog.i18n.bidi.normalizeHebrewQuote = function (a) {
return a.replace(goog.i18n.bidi.doubleQuoteSubstituteRe_, "$1\u05f4").replace(goog.i18n.bidi.singleQuoteSubstituteRe_, "$1\u05f3");
};
goog.i18n.bidi.wordSeparatorRe_ = /\s+/;
goog.i18n.bidi.hasNumeralsRe_ = /[\d\u06f0-\u06f9]/;
goog.i18n.bidi.rtlDetectionThreshold_ = .4;
goog.i18n.bidi.estimateDirection = function (a, b) {
var c = 0,
d = 0,
e = !1;
a = goog.i18n.bidi.stripHtmlIfNeeded_(a, b).split(goog.i18n.bidi.wordSeparatorRe_);
for (b = 0; b < a.length; b++) {
var f = a[b];
goog.i18n.bidi.startsWithRtl(f) ? (c++, d++) : goog.i18n.bidi.isRequiredLtrRe_.test(f) ? e = !0 : goog.i18n.bidi.hasAnyLtr(f) ? d++ : goog.i18n.bidi.hasNumeralsRe_.test(f) && (e = !0);
}
return 0 == d ? e ? goog.i18n.bidi.Dir.LTR : goog.i18n.bidi.Dir.NEUTRAL : c / d > goog.i18n.bidi.rtlDetectionThreshold_ ? goog.i18n.bidi.Dir.RTL : goog.i18n.bidi.Dir.LTR;
};
goog.i18n.bidi.detectRtlDirectionality = function (a, b) {
return goog.i18n.bidi.estimateDirection(a, b) == goog.i18n.bidi.Dir.RTL;
};
goog.i18n.bidi.setElementDirAndAlign = function (a, b) {
a && (b = goog.i18n.bidi.toDir(b)) && (a.style.textAlign = b == goog.i18n.bidi.Dir.RTL ? goog.i18n.bidi.RIGHT : goog.i18n.bidi.LEFT, a.dir = b == goog.i18n.bidi.Dir.RTL ? "rtl" : "ltr");
};
goog.i18n.bidi.setElementDirByTextDirectionality = function (a, b) {
switch (goog.i18n.bidi.estimateDirection(b)) {
case goog.i18n.bidi.Dir.LTR:
a.dir = "ltr";
break;
case goog.i18n.bidi.Dir.RTL:
a.dir = "rtl";
break;
default:
a.removeAttribute("dir");
}
};
goog.i18n.bidi.DirectionalString = function () {};
goog.html.TrustedResourceUrl = function () {
this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ = "";
this.trustedURL_ = null;
this.TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
};
goog.html.TrustedResourceUrl.prototype.implementsGoogStringTypedString = !0;
goog.html.TrustedResourceUrl.prototype.getTypedStringValue = function () {
return this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_.toString();
};
goog.html.TrustedResourceUrl.prototype.implementsGoogI18nBidiDirectionalString = !0;
goog.html.TrustedResourceUrl.prototype.getDirection = function () {
return goog.i18n.bidi.Dir.LTR;
};
goog.html.TrustedResourceUrl.prototype.cloneWithParams = function (a, b) {
var c = goog.html.TrustedResourceUrl.unwrap(this);
c = goog.html.TrustedResourceUrl.URL_PARAM_PARSER_.exec(c);
var d = c[3] || "";
return goog.html.TrustedResourceUrl.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(c[1] + goog.html.TrustedResourceUrl.stringifyParams_("?", c[2] || "", a) + goog.html.TrustedResourceUrl.stringifyParams_("#", d, b));
};
goog.DEBUG && (goog.html.TrustedResourceUrl.prototype.toString = function () {
return "TrustedResourceUrl{" + this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ + "}";
});
goog.html.TrustedResourceUrl.unwrap = function (a) {
return goog.html.TrustedResourceUrl.unwrapTrustedScriptURL(a).toString();
};
goog.html.TrustedResourceUrl.unwrapTrustedScriptURL = function (a) {
if (a instanceof goog.html.TrustedResourceUrl && a.constructor === goog.html.TrustedResourceUrl && a.TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) return a.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_;
goog.asserts.fail("expected object of type TrustedResourceUrl, got '" + a + "' of type " + goog.typeOf(a));
return "type_error:TrustedResourceUrl";
};
goog.html.TrustedResourceUrl.unwrapTrustedURL = function (a) {
return a.trustedURL_ ? a.trustedURL_ : goog.html.TrustedResourceUrl.unwrap(a);
};
goog.html.TrustedResourceUrl.format = function (a, b) {
var c = goog.string.Const.unwrap(a);
if (!goog.html.TrustedResourceUrl.BASE_URL_.test(c)) throw Error("Invalid TrustedResourceUrl format: " + c);
a = c.replace(goog.html.TrustedResourceUrl.FORMAT_MARKER_, function (a, e) {
if (!Object.prototype.hasOwnProperty.call(b, e)) throw Error('Found marker, "' + e + '", in format string, "' + c + '", but no valid label mapping found in args: ' + JSON.stringify(b));
a = b[e];
return a instanceof goog.string.Const ? goog.string.Const.unwrap(a) : encodeURIComponent(String(a));
});
return goog.html.TrustedResourceUrl.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.TrustedResourceUrl.FORMAT_MARKER_ = /%{(\w+)}/g;
goog.html.TrustedResourceUrl.BASE_URL_ = /^((https:)?\/\/[0-9a-z.:[\]-]+\/|\/[^/\\]|[^:/\\%]+\/|[^:/\\%]*[?#]|about:blank#)/i;
goog.html.TrustedResourceUrl.URL_PARAM_PARSER_ = /^([^?#]*)(\?[^#]*)?(#[\s\S]*)?/;
goog.html.TrustedResourceUrl.formatWithParams = function (a, b, c, d) {
return goog.html.TrustedResourceUrl.format(a, b).cloneWithParams(c, d);
};
goog.html.TrustedResourceUrl.fromConstant = function (a) {
return goog.html.TrustedResourceUrl.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(goog.string.Const.unwrap(a));
};
goog.html.TrustedResourceUrl.fromConstants = function (a) {
for (var b = "", c = 0; c < a.length; c++) b += goog.string.Const.unwrap(a[c]);
return goog.html.TrustedResourceUrl.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(b);
};
goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
goog.html.TrustedResourceUrl.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse = function (a) {
var b = new goog.html.TrustedResourceUrl();
b.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ = goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY ? goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY.createScriptURL(a) : a;
goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY && (b.trustedURL_ = goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY.createURL(a));
return b;
};
goog.html.TrustedResourceUrl.stringifyParams_ = function (a, b, c) {
if (null == c) return b;
if (goog.isString(c)) return c ? a + encodeURIComponent(c) : "";
for (var d in c) {
var e = c[d];
e = goog.isArray(e) ? e : [e];
for (var f = 0; f < e.length; f++) {
var g = e[f];
null != g && (b || (b = a), b += (b.length > a.length ? "&" : "") + encodeURIComponent(d) + "=" + encodeURIComponent(String(g)));
}
}
return b;
};
goog.html.SafeUrl = function () {
this.privateDoNotAccessOrElseSafeUrlWrappedValue_ = "";
this.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
};
goog.html.SafeUrl.INNOCUOUS_STRING = "about:invalid#zClosurez";
goog.html.SafeUrl.prototype.implementsGoogStringTypedString = !0;
goog.html.SafeUrl.prototype.getTypedStringValue = function () {
return this.privateDoNotAccessOrElseSafeUrlWrappedValue_.toString();
};
goog.html.SafeUrl.prototype.implementsGoogI18nBidiDirectionalString = !0;
goog.html.SafeUrl.prototype.getDirection = function () {
return goog.i18n.bidi.Dir.LTR;
};
goog.DEBUG && (goog.html.SafeUrl.prototype.toString = function () {
return "SafeUrl{" + this.privateDoNotAccessOrElseSafeUrlWrappedValue_ + "}";
});
goog.html.SafeUrl.unwrap = function (a) {
return goog.html.SafeUrl.unwrapTrustedURL(a).toString();
};
goog.html.SafeUrl.unwrapTrustedURL = function (a) {
if (a instanceof goog.html.SafeUrl && a.constructor === goog.html.SafeUrl && a.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) return a.privateDoNotAccessOrElseSafeUrlWrappedValue_;
goog.asserts.fail("expected object of type SafeUrl, got '" + a + "' of type " + goog.typeOf(a));
return "type_error:SafeUrl";
};
goog.html.SafeUrl.fromConstant = function (a) {
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(goog.string.Const.unwrap(a));
};
goog.html.SAFE_MIME_TYPE_PATTERN_ = /^(?:audio\/(?:3gpp2|3gpp|aac|L16|midi|mp3|mp4|mpeg|oga|ogg|opus|x-m4a|x-wav|wav|webm)|image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp|x-icon)|text\/csv|video\/(?:mpeg|mp4|ogg|webm|quicktime))(?:;\w+=(?:\w+|"[\w;=]+"))*$/i;
goog.html.SafeUrl.isSafeMimeType = function (a) {
return goog.html.SAFE_MIME_TYPE_PATTERN_.test(a);
};
goog.html.SafeUrl.fromBlob = function (a) {
a = goog.html.SAFE_MIME_TYPE_PATTERN_.test(a.type) ? goog.fs.url.createObjectUrl(a) : goog.html.SafeUrl.INNOCUOUS_STRING;
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.DATA_URL_PATTERN_ = /^data:([^,]*);base64,[a-z0-9+\/]+=*$/i;
goog.html.SafeUrl.fromDataUrl = function (a) {
a = a.replace(/(%0A|%0D)/g, "");
var b = a.match(goog.html.DATA_URL_PATTERN_);
b = b && goog.html.SAFE_MIME_TYPE_PATTERN_.test(b[1]);
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(b ? a : goog.html.SafeUrl.INNOCUOUS_STRING);
};
goog.html.SafeUrl.fromTelUrl = function (a) {
goog.string.internal.caseInsensitiveStartsWith(a, "tel:") || (a = goog.html.SafeUrl.INNOCUOUS_STRING);
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.SIP_URL_PATTERN_ = /^sip[s]?:[+a-z0-9_.!$%&'*\/=^`{|}~-]+@([a-z0-9-]+\.)+[a-z0-9]{2,63}$/i;
goog.html.SafeUrl.fromSipUrl = function (a) {
goog.html.SIP_URL_PATTERN_.test(decodeURIComponent(a)) || (a = goog.html.SafeUrl.INNOCUOUS_STRING);
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.SafeUrl.fromFacebookMessengerUrl = function (a) {
goog.string.internal.caseInsensitiveStartsWith(a, "fb-messenger://share") || (a = goog.html.SafeUrl.INNOCUOUS_STRING);
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.SafeUrl.fromWhatsAppUrl = function (a) {
goog.string.internal.caseInsensitiveStartsWith(a, "whatsapp://send") || (a = goog.html.SafeUrl.INNOCUOUS_STRING);
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.SafeUrl.fromSmsUrl = function (a) {
goog.string.internal.caseInsensitiveStartsWith(a, "sms:") && goog.html.SafeUrl.isSmsUrlBodyValid_(a) || (a = goog.html.SafeUrl.INNOCUOUS_STRING);
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.SafeUrl.isSmsUrlBodyValid_ = function (a) {
var b = a.indexOf("#");
0 < b && (a = a.substring(0, b));
b = a.match(/[?&]body=/gi);
if (!b) return !0;
if (1 < b.length) return !1;
a = a.match(/[?&]body=([^&]*)/)[1];
if (!a) return !0;
try {
decodeURIComponent(a);
} catch (c) {
return !1;
}
return /^(?:[a-z0-9\-_.~]|%[0-9a-f]{2})+$/i.test(a);
};
goog.html.SafeUrl.fromSshUrl = function (a) {
goog.string.internal.caseInsensitiveStartsWith(a, "ssh://") || (a = goog.html.SafeUrl.INNOCUOUS_STRING);
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.SafeUrl.sanitizeChromeExtensionUrl = function (a, b) {
return goog.html.SafeUrl.sanitizeExtensionUrl_(/^chrome-extension:\/\/([^\/]+)\//, a, b);
};
goog.html.SafeUrl.sanitizeFirefoxExtensionUrl = function (a, b) {
return goog.html.SafeUrl.sanitizeExtensionUrl_(/^moz-extension:\/\/([^\/]+)\//, a, b);
};
goog.html.SafeUrl.sanitizeEdgeExtensionUrl = function (a, b) {
return goog.html.SafeUrl.sanitizeExtensionUrl_(/^ms-browser-extension:\/\/([^\/]+)\//, a, b);
};
goog.html.SafeUrl.sanitizeExtensionUrl_ = function (a, b, c) {
(a = a.exec(b)) ? (a = a[1], -1 == (c instanceof goog.string.Const ? [goog.string.Const.unwrap(c)] : c.map(function (a) {
return goog.string.Const.unwrap(a);
})).indexOf(a) && (b = goog.html.SafeUrl.INNOCUOUS_STRING)) : b = goog.html.SafeUrl.INNOCUOUS_STRING;
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(b);
};
goog.html.SafeUrl.fromTrustedResourceUrl = function (a) {
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(goog.html.TrustedResourceUrl.unwrap(a));
};
goog.html.SAFE_URL_PATTERN_ = /^(?:(?:https?|mailto|ftp):|[^:/?#]*(?:[/?#]|$))/i;
goog.html.SafeUrl.SAFE_URL_PATTERN = goog.html.SAFE_URL_PATTERN_;
goog.html.SafeUrl.sanitize = function (a) {
if (a instanceof goog.html.SafeUrl) return a;
a = "object" == typeof a && a.implementsGoogStringTypedString ? a.getTypedStringValue() : String(a);
goog.html.SAFE_URL_PATTERN_.test(a) || (a = goog.html.SafeUrl.INNOCUOUS_STRING);
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.SafeUrl.sanitizeAssertUnchanged = function (a, b) {
if (a instanceof goog.html.SafeUrl) return a;
a = "object" == typeof a && a.implementsGoogStringTypedString ? a.getTypedStringValue() : String(a);
if (b && /^data:/i.test(a) && (b = goog.html.SafeUrl.fromDataUrl(a), b.getTypedStringValue() == a)) return b;
goog.asserts.assert(goog.html.SAFE_URL_PATTERN_.test(a), "%s does not match the safe URL pattern", a) || (a = goog.html.SafeUrl.INNOCUOUS_STRING);
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse = function (a) {
var b = new goog.html.SafeUrl();
b.privateDoNotAccessOrElseSafeUrlWrappedValue_ = goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY ? goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY.createURL(a) : a;
return b;
};
goog.html.SafeUrl.ABOUT_BLANK = goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse("about:blank");
goog.html.SafeStyle = function () {
this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = "";
this.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
};
goog.html.SafeStyle.prototype.implementsGoogStringTypedString = !0;
goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
goog.html.SafeStyle.fromConstant = function (a) {
a = goog.string.Const.unwrap(a);
if (0 === a.length) return goog.html.SafeStyle.EMPTY;
goog.asserts.assert(goog.string.internal.endsWith(a, ";"), "Last character of style string is not ';': " + a);
goog.asserts.assert(goog.string.internal.contains(a, ":"), "Style string must contain at least one ':', to specify a \"name: value\" pair: " + a);
return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.SafeStyle.prototype.getTypedStringValue = function () {
return this.privateDoNotAccessOrElseSafeStyleWrappedValue_;
};
goog.DEBUG && (goog.html.SafeStyle.prototype.toString = function () {
return "SafeStyle{" + this.privateDoNotAccessOrElseSafeStyleWrappedValue_ + "}";
});
goog.html.SafeStyle.unwrap = function (a) {
if (a instanceof goog.html.SafeStyle && a.constructor === goog.html.SafeStyle && a.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) return a.privateDoNotAccessOrElseSafeStyleWrappedValue_;
goog.asserts.fail("expected object of type SafeStyle, got '" + a + "' of type " + goog.typeOf(a));
return "type_error:SafeStyle";
};
goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse = function (a) {
return new goog.html.SafeStyle().initSecurityPrivateDoNotAccessOrElse_(a);
};
goog.html.SafeStyle.prototype.initSecurityPrivateDoNotAccessOrElse_ = function (a) {
this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = a;
return this;
};
goog.html.SafeStyle.EMPTY = goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse("");
goog.html.SafeStyle.INNOCUOUS_STRING = "zClosurez";
goog.html.SafeStyle.create = function (a) {
var b = "",
c;
for (c in a) {
if (!/^[-_a-zA-Z0-9]+$/.test(c)) throw Error("Name allows only [-_a-zA-Z0-9], got: " + c);
var d = a[c];
null != d && (d = goog.isArray(d) ? goog.array.map(d, goog.html.SafeStyle.sanitizePropertyValue_).join(" ") : goog.html.SafeStyle.sanitizePropertyValue_(d), b += c + ":" + d + ";");
}
return b ? goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(b) : goog.html.SafeStyle.EMPTY;
};
goog.html.SafeStyle.sanitizePropertyValue_ = function (a) {
if (a instanceof goog.html.SafeUrl) return 'url("' + goog.html.SafeUrl.unwrap(a).replace(/</g, "%3c").replace(/[\\"]/g, "\\$&") + '")';
a = a instanceof goog.string.Const ? goog.string.Const.unwrap(a) : goog.html.SafeStyle.sanitizePropertyValueString_(String(a));
if (/[{;}]/.test(a)) throw new goog.asserts.AssertionError("Value does not allow [{;}], got: %s.", [a]);
return a;
};
goog.html.SafeStyle.sanitizePropertyValueString_ = function (a) {
var b = a.replace(goog.html.SafeStyle.FUNCTIONS_RE_, "$1").replace(goog.html.SafeStyle.FUNCTIONS_RE_, "$1").replace(goog.html.SafeStyle.URL_RE_, "url");
if (goog.html.SafeStyle.VALUE_RE_.test(b)) {
if (goog.html.SafeStyle.COMMENT_RE_.test(a)) return goog.asserts.fail("String value disallows comments, got: " + a), goog.html.SafeStyle.INNOCUOUS_STRING;
if (!goog.html.SafeStyle.hasBalancedQuotes_(a)) return goog.asserts.fail("String value requires balanced quotes, got: " + a), goog.html.SafeStyle.INNOCUOUS_STRING;
if (!goog.html.SafeStyle.hasBalancedSquareBrackets_(a)) return goog.asserts.fail("String value requires balanced square brackets and one identifier per pair of brackets, got: " + a), goog.html.SafeStyle.INNOCUOUS_STRING;
} else return goog.asserts.fail("String value allows only " + goog.html.SafeStyle.VALUE_ALLOWED_CHARS_ + " and simple functions, got: " + a), goog.html.SafeStyle.INNOCUOUS_STRING;
return goog.html.SafeStyle.sanitizeUrl_(a);
};
goog.html.SafeStyle.hasBalancedQuotes_ = function (a) {
for (var b = !0, c = !0, d = 0; d < a.length; d++) {
var e = a.charAt(d);
"'" == e && c ? b = !b : '"' == e && b && (c = !c);
}
return b && c;
};
goog.html.SafeStyle.hasBalancedSquareBrackets_ = function (a) {
for (var b = !0, c = /^[-_a-zA-Z0-9]$/, d = 0; d < a.length; d++) {
var e = a.charAt(d);
if ("]" == e) {
if (b) return !1;
b = !0;
} else if ("[" == e) {
if (!b) return !1;
b = !1;
} else if (!b && !c.test(e)) return !1;
}
return b;
};
goog.html.SafeStyle.VALUE_ALLOWED_CHARS_ = "[-,.\"'%_!# a-zA-Z0-9\\[\\]]";
goog.html.SafeStyle.VALUE_RE_ = new RegExp("^" + goog.html.SafeStyle.VALUE_ALLOWED_CHARS_ + "+$");
goog.html.SafeStyle.URL_RE_ = /\b(url\([ \t\n]*)('[ -&(-\[\]-~]*'|"[ !#-\[\]-~]*"|[!#-&*-\[\]-~]*)([ \t\n]*\))/g;
goog.html.SafeStyle.FUNCTIONS_RE_ = /\b(hsl|hsla|rgb|rgba|matrix|calc|minmax|fit-content|repeat|(rotate|scale|translate)(X|Y|Z|3d)?)\([-+*/0-9a-z.%\[\], ]+\)/g;
goog.html.SafeStyle.COMMENT_RE_ = /\/\*/;
goog.html.SafeStyle.sanitizeUrl_ = function (a) {
return a.replace(goog.html.SafeStyle.URL_RE_, function (a, c, d, e) {
var b = "";
d = d.replace(/^(['"])(.*)\1$/, function (a, c, d) {
b = c;
return d;
});
a = goog.html.SafeUrl.sanitize(d).getTypedStringValue();
return c + b + a + b + e;
});
};
goog.html.SafeStyle.concat = function (a) {
var b = "",
c = function (a) {
goog.isArray(a) ? goog.array.forEach(a, c) : b += goog.html.SafeStyle.unwrap(a);
};
goog.array.forEach(arguments, c);
return b ? goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(b) : goog.html.SafeStyle.EMPTY;
};
goog.html.SafeScript = function () {
this.privateDoNotAccessOrElseSafeScriptWrappedValue_ = "";
this.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
};
goog.html.SafeScript.prototype.implementsGoogStringTypedString = !0;
goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
goog.html.SafeScript.fromConstant = function (a) {
a = goog.string.Const.unwrap(a);
return 0 === a.length ? goog.html.SafeScript.EMPTY : goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.SafeScript.fromConstantAndArgs = function (a, b) {
for (var c = [], d = 1; d < arguments.length; d++) c.push(goog.html.SafeScript.stringify_(arguments[d]));
return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse("(" + goog.string.Const.unwrap(a) + ")(" + c.join(", ") + ");");
};
goog.html.SafeScript.fromJson = function (a) {
return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(goog.html.SafeScript.stringify_(a));
};
goog.html.SafeScript.prototype.getTypedStringValue = function () {
return this.privateDoNotAccessOrElseSafeScriptWrappedValue_.toString();
};
goog.DEBUG && (goog.html.SafeScript.prototype.toString = function () {
return "SafeScript{" + this.privateDoNotAccessOrElseSafeScriptWrappedValue_ + "}";
});
goog.html.SafeScript.unwrap = function (a) {
return goog.html.SafeScript.unwrapTrustedScript(a).toString();
};
goog.html.SafeScript.unwrapTrustedScript = function (a) {
if (a instanceof goog.html.SafeScript && a.constructor === goog.html.SafeScript && a.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) return a.privateDoNotAccessOrElseSafeScriptWrappedValue_;
goog.asserts.fail("expected object of type SafeScript, got '" + a + "' of type " + goog.typeOf(a));
return "type_error:SafeScript";
};
goog.html.SafeScript.stringify_ = function (a) {
return JSON.stringify(a).replace(/</g, "\\x3c");
};
goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse = function (a) {
return new goog.html.SafeScript().initSecurityPrivateDoNotAccessOrElse_(a);
};
goog.html.SafeScript.prototype.initSecurityPrivateDoNotAccessOrElse_ = function (a) {
this.privateDoNotAccessOrElseSafeScriptWrappedValue_ = goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY ? goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY.createScript(a) : a;
return this;
};
goog.html.SafeScript.EMPTY = goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse("");
goog.object = {};
goog.object.is = function (a, b) {
return a === b ? 0 !== a || 1 / a === 1 / b : a !== a && b !== b;
};
goog.object.forEach = function (a, b, c) {
for (var d in a) b.call(c, a[d], d, a);
};
goog.object.filter = function (a, b, c) {
var d = {},
e;
for (e in a) b.call(c, a[e], e, a) && (d[e] = a[e]);
return d;
};
goog.object.map = function (a, b, c) {
var d = {},
e;
for (e in a) d[e] = b.call(c, a[e], e, a);
return d;
};
goog.object.some = function (a, b, c) {
for (var d in a) if (b.call(c, a[d], d, a)) return !0;
return !1;
};
goog.object.every = function (a, b, c) {
for (var d in a) if (!b.call(c, a[d], d, a)) return !1;
return !0;
};
goog.object.getCount = function (a) {
var b = 0,
c;
for (c in a) b++;
return b;
};
goog.object.getAnyKey = function (a) {
for (var b in a) return b;
};
goog.object.getAnyValue = function (a) {
for (var b in a) return a[b];
};
goog.object.contains = function (a, b) {
return goog.object.containsValue(a, b);
};
goog.object.getValues = function (a) {
var b = [],
c = 0,
d;
for (d in a) b[c++] = a[d];
return b;
};
goog.object.getKeys = function (a) {
var b = [],
c = 0,
d;
for (d in a) b[c++] = d;
return b;
};
goog.object.getValueByKeys = function (a, b) {
var c = goog.isArrayLike(b),
d = c ? b : arguments;
for (c = c ? 0 : 1; c < d.length; c++) {
if (null == a) return;
a = a[d[c]];
}
return a;
};
goog.object.containsKey = function (a, b) {
return null !== a && b in a;
};
goog.object.containsValue = function (a, b) {
for (var c in a) if (a[c] == b) return !0;
return !1;
};
goog.object.findKey = function (a, b, c) {
for (var d in a) if (b.call(c, a[d], d, a)) return d;
};
goog.object.findValue = function (a, b, c) {
return (b = goog.object.findKey(a, b, c)) && a[b];
};
goog.object.isEmpty = function (a) {
for (var b in a) return !1;
return !0;
};
goog.object.clear = function (a) {
for (var b in a) delete a[b];
};
goog.object.remove = function (a, b) {
var c;
(c = b in a) && delete a[b];
return c;
};
goog.object.add = function (a, b, c) {
if (null !== a && b in a) throw Error('The object already contains the key "' + b + '"');
goog.object.set(a, b, c);
};
goog.object.get = function (a, b, c) {
return null !== a && b in a ? a[b] : c;
};
goog.object.set = function (a, b, c) {
a[b] = c;
};
goog.object.setIfUndefined = function (a, b, c) {
return b in a ? a[b] : a[b] = c;
};
goog.object.setWithReturnValueIfNotSet = function (a, b, c) {
if (b in a) return a[b];
c = c();
return a[b] = c;
};
goog.object.equals = function (a, b) {
for (var c in a) if (!(c in b) || a[c] !== b[c]) return !1;
for (var d in b) if (!(d in a)) return !1;
return !0;
};
goog.object.clone = function (a) {
var b = {},
c;
for (c in a) b[c] = a[c];
return b;
};
goog.object.unsafeClone = function (a) {
var b = goog.typeOf(a);
if ("object" == b || "array" == b) {
if (goog.isFunction(a.clone)) return a.clone();
b = "array" == b ? [] : {};
for (var c in a) b[c] = goog.object.unsafeClone(a[c]);
return b;
}
return a;
};
goog.object.transpose = function (a) {
var b = {},
c;
for (c in a) b[a[c]] = c;
return b;
};
goog.object.PROTOTYPE_FIELDS_ = "constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");
goog.object.extend = function (a, b) {
for (var c, d, e = 1; e < arguments.length; e++) {
d = arguments[e];
for (c in d) a[c] = d[c];
for (var f = 0; f < goog.object.PROTOTYPE_FIELDS_.length; f++) c = goog.object.PROTOTYPE_FIELDS_[f], Object.prototype.hasOwnProperty.call(d, c) && (a[c] = d[c]);
}
};
goog.object.create = function (a) {
var b = arguments.length;
if (1 == b && goog.isArray(arguments[0])) return goog.object.create.apply(null, arguments[0]);
if (b % 2) throw Error("Uneven number of arguments");
for (var c = {}, d = 0; d < b; d += 2) c[arguments[d]] = arguments[d + 1];
return c;
};
goog.object.createSet = function (a) {
var b = arguments.length;
if (1 == b && goog.isArray(arguments[0])) return goog.object.createSet.apply(null, arguments[0]);
for (var c = {}, d = 0; d < b; d++) c[arguments[d]] = !0;
return c;
};
goog.object.createImmutableView = function (a) {
var b = a;
Object.isFrozen && !Object.isFrozen(a) && (b = Object.create(a), Object.freeze(b));
return b;
};
goog.object.isImmutableView = function (a) {
return !!Object.isFrozen && Object.isFrozen(a);
};
goog.object.getAllPropertyNames = function (a, b, c) {
if (!a) return [];
if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) return goog.object.getKeys(a);
for (var d = {}; a && (a !== Object.prototype || b) && (a !== Function.prototype || c);) {
for (var e = Object.getOwnPropertyNames(a), f = 0; f < e.length; f++) d[e[f]] = !0;
a = Object.getPrototypeOf(a);
}
return goog.object.getKeys(d);
};
goog.object.getSuperClass = function (a) {
return (a = Object.getPrototypeOf(a.prototype)) && a.constructor;
};
goog.html.SafeStyleSheet = function () {
this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ = "";
this.SAFE_STYLE_SHEET_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
};
goog.html.SafeStyleSheet.prototype.implementsGoogStringTypedString = !0;
goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
goog.html.SafeStyleSheet.createRule = function (a, b) {
if (goog.string.internal.contains(a, "<")) throw Error("Selector does not allow '<', got: " + a);
var c = a.replace(/('|")((?!\1)[^\r\n\f\\]|\\[\s\S])*\1/g, "");
if (!/^[-_a-zA-Z0-9#.:* ,>+~[\]()=^$|]+$/.test(c)) throw Error("Selector allows only [-_a-zA-Z0-9#.:* ,>+~[\\]()=^$|] and strings, got: " + a);
if (!goog.html.SafeStyleSheet.hasBalancedBrackets_(c)) throw Error("() and [] in selector must be balanced, got: " + a);
b instanceof goog.html.SafeStyle || (b = goog.html.SafeStyle.create(b));
a = a + "{" + goog.html.SafeStyle.unwrap(b).replace(/</g, "\\3C ") + "}";
return goog.html.SafeStyleSheet.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.SafeStyleSheet.hasBalancedBrackets_ = function (a) {
for (var b = {
"(": ")",
"[": "]"
}, c = [], d = 0; d < a.length; d++) {
var e = a[d];
if (b[e]) c.push(b[e]);else if (goog.object.contains(b, e) && c.pop() != e) return !1;
}
return 0 == c.length;
};
goog.html.SafeStyleSheet.concat = function (a) {
var b = "",
c = function (a) {
goog.isArray(a) ? goog.array.forEach(a, c) : b += goog.html.SafeStyleSheet.unwrap(a);
};
goog.array.forEach(arguments, c);
return goog.html.SafeStyleSheet.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(b);
};
goog.html.SafeStyleSheet.fromConstant = function (a) {
a = goog.string.Const.unwrap(a);
if (0 === a.length) return goog.html.SafeStyleSheet.EMPTY;
goog.asserts.assert(!goog.string.internal.contains(a, "<"), "Forbidden '<' character in style sheet string: " + a);
return goog.html.SafeStyleSheet.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(a);
};
goog.html.SafeStyleSheet.prototype.getTypedStringValue = function () {
return this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_;
};
goog.DEBUG && (goog.html.SafeStyleSheet.prototype.toString = function () {
return "SafeStyleSheet{" + this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ + "}";
});
goog.html.SafeStyleSheet.unwrap = function (a) {
if (a instanceof goog.html.SafeStyleSheet && a.constructor === goog.html.SafeStyleSheet && a.SAFE_STYLE_SHEET_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) return a.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_;
goog.asserts.fail("expected object of type SafeStyleSheet, got '" + a + "' of type " + goog.typeOf(a));
return "type_error:SafeStyleSheet";
};
goog.html.SafeStyleSheet.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse = function (a) {
return new goog.html.SafeStyleSheet().initSecurityPrivateDoNotAccessOrElse_(a);
};
goog.html.SafeStyleSheet.prototype.initSecurityPrivateDoNotAccessOrElse_ = function (a) {
this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ = a;
return this;
};
goog.html.SafeStyleSheet.EMPTY = goog.html.SafeStyleSheet.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse("");
goog.dom.tags = {};
goog.dom.tags.VOID_TAGS_ = {
area: !0,
base: !0,
br: !0,
col: !0,
command: !0,
embed: !0,
hr: !0,
img: !0,
input: !0,
keygen: !0,
link: !0,
meta: !0,
param: !0,
source: !0,
track: !0,
wbr: !0
};
goog.dom.tags.isVoidTag = function (a) {
return !0 === goog.dom.tags.VOID_TAGS_[a];
};
goog.dom.HtmlElement = function () {};
goog.dom.TagName = function (a) {
this.tagName_ = a;
};
goog.dom.TagName.prototype.toString = function () {
return this.tagName_;
};
goog.dom.TagName.A = new goog.dom.TagName("A");
goog.dom.TagName.ABBR = new goog.dom.TagName("ABBR");
goog.dom.TagName.ACRONYM = new goog.dom.TagName("ACRONYM");
goog.dom.TagName.ADDRESS = new goog.dom.TagName("ADDRESS");
goog.dom.TagName.APPLET = new goog.dom.TagName("APPLET");
goog.dom.TagName.AREA = new goog.dom.TagName("AREA");
goog.dom.TagName.ARTICLE = new goog.dom.TagName("ARTICLE");
goog.dom.TagName.ASIDE = new goog.dom.TagName("ASIDE");
goog.dom.TagName.AUDIO = new goog.dom.TagName("AUDIO");
goog.dom.TagName.B = new goog.dom.TagName("B");
goog.dom.TagName.BASE = new goog.dom.TagName("BASE");
goog.dom.TagName.BASEFONT = new goog.dom.TagName("BASEFONT");
goog.dom.TagName.BDI = new goog.dom.TagName("BDI");
goog.dom.TagName.BDO = new goog.dom.TagName("BDO");
goog.dom.TagName.BIG = new goog.dom.TagName("BIG");
goog.dom.TagName.BLOCKQUOTE = new goog.dom.TagName("BLOCKQUOTE");
goog.dom.TagName.BODY = new goog.dom.TagName("BODY");
goog.dom.TagName.BR = new goog.dom.TagName("BR");
goog.dom.TagName.BUTTON = new goog.dom.TagName("BUTTON");
goog.dom.TagName.CANVAS = new goog.dom.TagName("CANVAS");
goog.dom.TagName.CAPTION = new goog.dom.TagName("CAPTION");
goog.dom.TagName.CENTER = new goog.dom.TagName("CENTER");
goog.dom.TagName.CITE = new goog.dom.TagName("CITE");
goog.dom.TagName.CODE = new goog.dom.TagName("CODE");
goog.dom.TagName.COL = new goog.dom.TagName("COL");
goog.dom.TagName.COLGROUP = new goog.dom.TagName("COLGROUP");
goog.dom.TagName.COMMAND = new goog.dom.TagName("COMMAND");
goog.dom.TagName.DATA = new goog.dom.TagName("DATA");
goog.dom.TagName.DATALIST = new goog.dom.TagName("DATALIST");
goog.dom.TagName.DD = new goog.dom.TagName("DD");
goog.dom.TagName.DEL = new goog.dom.TagName("DEL");
goog.dom.TagName.DETAILS = new goog.dom.TagName("DETAILS");
goog.dom.TagName.DFN = new goog.dom.TagName("DFN");
goog.dom.TagName.DIALOG = new goog.dom.TagName("DIALOG");
goog.dom.TagName.DIR = new goog.dom.TagName("DIR");
goog.dom.TagName.DIV = new goog.dom.TagName("DIV");
goog.dom.TagName.DL = new goog.dom.TagName("DL");
goog.dom.TagName.DT = new goog.dom.TagName("DT");
goog.dom.TagName.EM = new goog.dom.TagName("EM");
goog.dom.TagName.EMBED = new goog.dom.TagName("EMBED");
goog.dom.TagName.FIELDSET = new goog.dom.TagName("FIELDSET");
goog.dom.TagName.FIGCAPTION = new goog.dom.TagName("FIGCAPTION");
goog.dom.TagName.FIGURE = new goog.dom.TagName("FIGURE");
goog.dom.TagName.FONT = new goog.dom.TagName("FONT");
goog.dom.TagName.FOOTER = new goog.dom.TagName("FOOTER");
goog.dom.TagName.FORM = new goog.dom.TagName("FORM");
goog.dom.TagName.FRAME = new goog.dom.TagName("FRAME");
goog.dom.TagName.FRAMESET = new goog.dom.TagName("FRAMESET");
goog.dom.TagName.H1 = new goog.dom.TagName("H1");
goog.dom.TagName.H2 = new goog.dom.TagName("H2");
goog.dom.TagName.H3 = new goog.dom.TagName("H3");
goog.dom.TagName.H4 = new goog.dom.TagName("H4");
goog.dom.TagName.H5 = new goog.dom.TagName("H5");
goog.dom.TagName.H6 = new goog.dom.TagName("H6");
goog.dom.TagName.HEAD = new goog.dom.TagName("HEAD");
goog.dom.TagName.HEADER = new goog.dom.TagName("HEADER");
goog.dom.TagName.HGROUP = new goog.dom.TagName("HGROUP");
goog.dom.TagName.HR = new goog.dom.TagName("HR");
goog.dom.TagName.HTML = new goog.dom.TagName("HTML");
goog.dom.TagName.I = new goog.dom.TagName("I");
goog.dom.TagName.IFRAME = new goog.dom.TagName("IFRAME");
goog.dom.TagName.IMG = new goog.dom.TagName("IMG");
goog.dom.TagName.INPUT = new goog.dom.TagName("INPUT");
goog.dom.TagName.INS = new goog.dom.TagName("INS");
goog.dom.TagName.ISINDEX = new goog.dom.TagName("ISINDEX");
goog.dom.TagName.KBD = new goog.dom.TagName("KBD");
goog.dom.TagName.KEYGEN = new goog.dom.TagName("KEYGEN");
goog.dom.TagName.LABEL = new goog.dom.TagName("LABEL");
goog.dom.TagName.LEGEND = new goog.dom.TagName("LEGEND");
goog.dom.TagName.LI = new goog.dom.TagName("LI");
goog.dom.TagName.LINK = new goog.dom.TagName("LINK");
goog.dom.TagName.MAIN = new goog.dom.TagName("MAIN");
goog.dom.TagName.MAP = new goog.dom.TagName("MAP");
goog.dom.TagName.MARK = new goog.dom.TagName("MARK");
goog.dom.TagName.MATH = new goog.dom.TagName("MATH");
goog.dom.TagName.MENU = new goog.dom.TagName("MENU");
goog.dom.TagName.MENUITEM = new goog.dom.TagName("MENUITEM");
goog.dom.TagName.META = new goog.dom.TagName("META");
goog.dom.TagName.METER = new goog.dom.TagName("METER");
goog.dom.TagName.NAV = new goog.dom.TagName("NAV");
goog.dom.TagName.NOFRAMES = new goog.dom.TagName("NOFRAMES");
goog.dom.TagName.NOSCRIPT = new goog.dom.TagName("NOSCRIPT");
goog.dom.TagName.OBJECT = new goog.dom.TagName("OBJECT");
goog.dom.TagName.OL = new goog.dom.TagName("OL");
goog.dom.TagName.OPTGROUP = new goog.dom.TagName("OPTGROUP");
goog.dom.TagName.OPTION = new goog.dom.TagName("OPTION");
goog.dom.TagName.OUTPUT = new goog.dom.TagName("OUTPUT");
goog.dom.TagName.P = new goog.dom.TagName("P");
goog.dom.TagName.PARAM = new goog.dom.TagName("PARAM");
goog.dom.TagName.PICTURE = new goog.dom.TagName("PICTURE");
goog.dom.TagName.PRE = new goog.dom.TagName("PRE");
goog.dom.TagName.PROGRESS = new goog.dom.TagName("PROGRESS");
goog.dom.TagName.Q = new goog.dom.TagName("Q");
goog.dom.TagName.RP = new goog.dom.TagName("RP");
goog.dom.TagName.RT = new goog.dom.TagName("RT");
goog.dom.TagName.RTC = new goog.dom.TagName("RTC");
goog.dom.TagName.RUBY = new goog.dom.TagName("RUBY");
goog.dom.TagName.S = new goog.dom.TagName("S");
goog.dom.TagName.SAMP = new goog.dom.TagName("SAMP");
goog.dom.TagName.SCRIPT = new goog.dom.TagName("SCRIPT");
goog.dom.TagName.SECTION = new goog.dom.TagName("SECTION");
goog.dom.TagName.SELECT = new goog.dom.TagName("SELECT");
goog.dom.TagName.SMALL = new goog.dom.TagName("SMALL");
goog.dom.TagName.SOURCE = new goog.dom.TagName("SOURCE");
goog.dom.TagName.SPAN = new goog.dom.TagName("SPAN");
goog.dom.TagName.STRIKE = new goog.dom.TagName("STRIKE");
goog.dom.TagName.STRONG = new goog.dom.TagName("STRONG");
goog.dom.TagName.STYLE = new goog.dom.TagName("STYLE");
goog.dom.TagName.SUB = new goog.dom.TagName("SUB");
goog.dom.TagName.SUMMARY = new goog.dom.TagName("SUMMARY");
goog.dom.TagName.SUP = new goog.dom.TagName("SUP");
goog.dom.TagName.SVG = new goog.dom.TagName("SVG");
goog.dom.TagName.TABLE = new goog.dom.TagName("TABLE");
goog.dom.TagName.TBODY = new goog.dom.TagName("TBODY");
goog.dom.TagName.TD = new goog.dom.TagName("TD");
goog.dom.TagName.TEMPLATE = new goog.dom.TagName("TEMPLATE");
goog.dom.TagName.TEXTAREA = new goog.dom.TagName("TEXTAREA");
goog.dom.TagName.TFOOT = new goog.dom.TagName("TFOOT");
goog.dom.TagName.TH = new goog.dom.TagName("TH");
goog.dom.TagName.THEAD = new goog.dom.TagName("THEAD");
goog.dom.TagName.TIME = new goog.dom.TagName("TIME");
goog.dom.TagName.TITLE = new goog.dom.TagName("TITLE");
goog.dom.TagName.TR = new goog.dom.TagName("TR");
goog.dom.TagName.TRACK = new goog.dom.TagName("TRACK");
goog.dom.TagName.TT = new goog.dom.TagName("TT");
goog.dom.TagName.U = new goog.dom.TagName("U");
goog.dom.TagName.UL = new goog.dom.TagName("UL");
goog.dom.TagName.VAR = new goog.dom.TagName("VAR");
goog.dom.TagName.VIDEO = new goog.dom.TagName("VIDEO");
goog.dom.TagName.WBR = new goog.dom.TagName("WBR");
goog.labs = {};
goog.labs.userAgent = {};
goog.labs.userAgent.util = {};
goog.labs.userAgent.util.getNativeUserAgentString_ = function () {
var a = goog.labs.userAgent.util.getNavigator_();
return a && (a = a.userAgent) ? a : "";
};
goog.labs.userAgent.util.getNavigator_ = function () {
return goog.global.navigator;
};
goog.labs.userAgent.util.userAgent_ = goog.labs.userAgent.util.getNativeUserAgentString_();
goog.labs.userAgent.util.setUserAgent = function (a) {
goog.labs.userAgent.util.userAgent_ = a || goog.labs.userAgent.util.getNativeUserAgentString_();
};
goog.labs.userAgent.util.getUserAgent = function () {
return goog.labs.userAgent.util.userAgent_;
};
goog.labs.userAgent.util.matchUserAgent = function (a) {
var b = goog.labs.userAgent.util.getUserAgent();
return goog.string.internal.contains(b, a);
};
goog.labs.userAgent.util.matchUserAgentIgnoreCase = function (a) {
var b = goog.labs.userAgent.util.getUserAgent();
return goog.string.internal.caseInsensitiveContains(b, a);
};
goog.labs.userAgent.util.extractVersionTuples = function (a) {
for (var b = /(\w[\w ]+)\/([^\s]+)\s*(?:\((.*?)\))?/g, c = [], d; d = b.exec(a);) c.push([d[1], d[2], d[3] || void 0]);
return c;
};
goog.labs.userAgent.browser = {};
goog.labs.userAgent.browser.matchOpera_ = function () {
return goog.labs.userAgent.util.matchUserAgent("Opera");
};
goog.labs.userAgent.browser.matchIE_ = function () {
return goog.labs.userAgent.util.matchUserAgent("Trident") || goog.labs.userAgent.util.matchUserAgent("MSIE");
};
goog.labs.userAgent.browser.matchEdgeHtml_ = function () {
return goog.labs.userAgent.util.matchUserAgent("Edge");
};
goog.labs.userAgent.browser.matchEdgeChromium_ = function () {
return goog.labs.userAgent.util.matchUserAgent("Edg/");
};
goog.labs.userAgent.browser.matchOperaChromium_ = function () {
return goog.labs.userAgent.util.matchUserAgent("OPR");
};
goog.labs.userAgent.browser.matchFirefox_ = function () {
return goog.labs.userAgent.util.matchUserAgent("Firefox") || goog.labs.userAgent.util.matchUserAgent("FxiOS");
};
goog.labs.userAgent.browser.matchSafari_ = function () {
return goog.labs.userAgent.util.matchUserAgent("Safari") && !(goog.labs.userAgent.browser.matchChrome_() || goog.labs.userAgent.browser.matchCoast_() || goog.labs.userAgent.browser.matchOpera_() || goog.labs.userAgent.browser.matchEdgeHtml_() || goog.labs.userAgent.browser.matchEdgeChromium_() || goog.labs.userAgent.browser.matchOperaChromium_() || goog.labs.userAgent.browser.matchFirefox_() || goog.labs.userAgent.browser.isSilk() || goog.labs.userAgent.util.matchUserAgent("Android"));
};
goog.labs.userAgent.browser.matchCoast_ = function () {
return goog.labs.userAgent.util.matchUserAgent("Coast");
};
goog.labs.userAgent.browser.matchIosWebview_ = function () {
return (goog.labs.userAgent.util.matchUserAgent("iPad") || goog.labs.userAgent.util.matchUserAgent("iPhone")) && !goog.labs.userAgent.browser.matchSafari_() && !goog.labs.userAgent.browser.matchChrome_() && !goog.labs.userAgent.browser.matchCoast_() && !goog.labs.userAgent.browser.matchFirefox_() && goog.labs.userAgent.util.matchUserAgent("AppleWebKit");
};
goog.labs.userAgent.browser.matchChrome_ = function () {
return (goog.labs.userAgent.util.matchUserAgent("Chrome") || goog.labs.userAgent.util.matchUserAgent("CriOS")) && !goog.labs.userAgent.browser.matchEdgeHtml_();
};
goog.labs.userAgent.browser.matchAndroidBrowser_ = function () {
return goog.labs.userAgent.util.matchUserAgent("Android") && !(goog.labs.userAgent.browser.isChrome() || goog.labs.userAgent.browser.isFirefox() || goog.labs.userAgent.browser.isOpera() || goog.labs.userAgent.browser.isSilk());
};
goog.labs.userAgent.browser.isOpera = goog.labs.userAgent.browser.matchOpera_;
goog.labs.userAgent.browser.isIE = goog.labs.userAgent.browser.matchIE_;
goog.labs.userAgent.browser.isEdge = goog.labs.userAgent.browser.matchEdgeHtml_;
goog.labs.userAgent.browser.isEdgeChromium = goog.labs.userAgent.browser.matchEdgeChromium_;
goog.labs.userAgent.browser.isOperaChromium = goog.labs.userAgent.browser.matchOperaChromium_;
goog.labs.userAgent.browser.isFirefox = goog.labs.userAgent.browser.matchFirefox_;
goog.labs.userAgent.browser.isSafari = goog.labs.userAgent.browser.matchSafari_;
goog.labs.userAgent.browser.isCoast = goog.labs.userAgent.browser.matchCoast_;
goog.labs.userAgent.browser.isIosWebview = goog.labs.userAgent.browser.matchIosWebview_;
goog.labs.userAgent.browser.isChrome = goog.labs.userAgent.browser.matchChrome_;
goog.labs.userAgent.browser.isAndroidBrowser = goog.labs.userAgent.browser.matchAndroidBrowser_;
goog.labs.userAgent.browser.isSilk = function () {
return goog.labs.userAgent.util.matchUserAgent("Silk");
};
goog.labs.userAgent.browser.getVersion = function () {
function a(a) {
a = goog.array.find(a, d);
return c[a] || "";
}
var b = goog.labs.userAgent.util.getUserAgent();
if (goog.labs.userAgent.browser.isIE()) return goog.labs.userAgent.browser.getIEVersion_(b);
b = goog.labs.userAgent.util.extractVersionTuples(b);
var c = {};
goog.array.forEach(b, function (a) {
c[a[0]] = a[1];
});
var d = goog.partial(goog.object.containsKey, c);
return goog.labs.userAgent.browser.isOpera() ? a(["Version", "Opera"]) : goog.labs.userAgent.browser.isEdge() ? a(["Edge"]) : goog.labs.userAgent.browser.isEdgeChromium() ? a(["Edg"]) : goog.labs.userAgent.browser.isChrome() ? a(["Chrome", "CriOS"]) : (b = b[2]) && b[1] || "";
};
goog.labs.userAgent.browser.isVersionOrHigher = function (a) {
return 0 <= goog.string.internal.compareVersions(goog.labs.userAgent.browser.getVersion(), a);
};
goog.labs.userAgent.browser.getIEVersion_ = function (a) {
var b = /rv: *([\d\.]*)/.exec(a);
if (b && b[1]) return b[1];
b = "";
var c = /MSIE +([\d\.]+)/.exec(a);
if (c && c[1]) if (a = /Trident\/(\d.\d)/.exec(a), "7.0" == c[1]) {
if (a && a[1]) switch (a[1]) {
case "4.0":
b = "8.0";
break;
case "5.0":
b = "9.0";
break;
case "6.0":
b = "10.0";
break;
case "7.0":
b = "11.0";
} else b = "7.0";
} else b = c[1];
return b;
};
goog.html.SafeHtml = function () {
this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = "";
this.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
this.dir_ = null;
};
goog.html.SafeHtml.prototype.implementsGoogI18nBidiDirectionalString = !0;
goog.html.SafeHtml.prototype.getDirection = function () {
return this.dir_;
};
goog.html.SafeHtml.prototype.implementsGoogStringTypedString = !0;
goog.html.SafeHtml.prototype.getTypedStringValue = function () {
return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_.toString();
};
goog.DEBUG && (goog.html.SafeHtml.prototype.toString = function () {
return "SafeHtml{" + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ + "}";
});
goog.html.SafeHtml.unwrap = function (a) {
return goog.html.SafeHtml.unwrapTrustedHTML(a).toString();
};
goog.html.SafeHtml.unwrapTrustedHTML = function (a) {
if (a instanceof goog.html.SafeHtml && a.constructor === goog.html.SafeHtml && a.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) return a.privateDoNotAccessOrElseSafeHtmlWrappedValue_;
goog.asserts.fail("expected object of type SafeHtml, got '" + a + "' of type " + goog.typeOf(a));
return "type_error:SafeHtml";
};
goog.html.SafeHtml.htmlEscape = function (a) {
if (a instanceof goog.html.SafeHtml) return a;
var b = "object" == typeof a,
c = null;
b && a.implementsGoogI18nBidiDirectionalString && (c = a.getDirection());
a = b && a.implementsGoogStringTypedString ? a.getTypedStringValue() : String(a);
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(goog.string.internal.htmlEscape(a), c);
};
goog.html.SafeHtml.htmlEscapePreservingNewlines = function (a) {
if (a instanceof goog.html.SafeHtml) return a;
a = goog.html.SafeHtml.htmlEscape(a);
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(goog.string.internal.newLineToBr(goog.html.SafeHtml.unwrap(a)), a.getDirection());
};
goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces = function (a) {
if (a instanceof goog.html.SafeHtml) return a;
a = goog.html.SafeHtml.htmlEscape(a);
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(goog.string.internal.whitespaceEscape(goog.html.SafeHtml.unwrap(a)), a.getDirection());
};
goog.html.SafeHtml.from = goog.html.SafeHtml.htmlEscape;
goog.html.SafeHtml.VALID_NAMES_IN_TAG_ = /^[a-zA-Z0-9-]+$/;
goog.html.SafeHtml.URL_ATTRIBUTES_ = {
action: !0,
cite: !0,
data: !0,
formaction: !0,
href: !0,
manifest: !0,
poster: !0,
src: !0
};
goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_ = {
APPLET: !0,
BASE: !0,
EMBED: !0,
IFRAME: !0,
LINK: !0,
MATH: !0,
META: !0,
OBJECT: !0,
SCRIPT: !0,
STYLE: !0,
SVG: !0,
TEMPLATE: !0
};
goog.html.SafeHtml.create = function (a, b, c) {
goog.html.SafeHtml.verifyTagName(String(a));
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(String(a), b, c);
};
goog.html.SafeHtml.verifyTagName = function (a) {
if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(a)) throw Error("Invalid tag name <" + a + ">.");
if (a.toUpperCase() in goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_) throw Error("Tag name <" + a + "> is not allowed for SafeHtml.");
};
goog.html.SafeHtml.createIframe = function (a, b, c, d) {
a && goog.html.TrustedResourceUrl.unwrap(a);
var e = {};
e.src = a || null;
e.srcdoc = b && goog.html.SafeHtml.unwrap(b);
a = goog.html.SafeHtml.combineAttributes(e, {
sandbox: ""
}, c);
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse("iframe", a, d);
};
goog.html.SafeHtml.createSandboxIframe = function (a, b, c, d) {
if (!goog.html.SafeHtml.canUseSandboxIframe()) throw Error("The browser does not support sandboxed iframes.");
var e = {};
e.src = a ? goog.html.SafeUrl.unwrap(goog.html.SafeUrl.sanitize(a)) : null;
e.srcdoc = b || null;
e.sandbox = "";
a = goog.html.SafeHtml.combineAttributes(e, {}, c);
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse("iframe", a, d);
};
goog.html.SafeHtml.canUseSandboxIframe = function () {
return goog.global.HTMLIFrameElement && "sandbox" in goog.global.HTMLIFrameElement.prototype;
};
goog.html.SafeHtml.createScriptSrc = function (a, b) {
goog.html.TrustedResourceUrl.unwrap(a);
a = goog.html.SafeHtml.combineAttributes({
src: a
}, {}, b);
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse("script", a);
};
goog.html.SafeHtml.createScript = function (a, b) {
for (var c in b) {
var d = c.toLowerCase();
if ("language" == d || "src" == d || "text" == d || "type" == d) throw Error('Cannot set "' + d + '" attribute');
}
c = "";
a = goog.array.concat(a);
for (d = 0; d < a.length; d++) c += goog.html.SafeScript.unwrap(a[d]);
a = goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(c, goog.i18n.bidi.Dir.NEUTRAL);
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse("script", b, a);
};
goog.html.SafeHtml.createStyle = function (a, b) {
b = goog.html.SafeHtml.combineAttributes({
type: "text/css"
}, {}, b);
var c = "";
a = goog.array.concat(a);
for (var d = 0; d < a.length; d++) c += goog.html.SafeStyleSheet.unwrap(a[d]);
a = goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(c, goog.i18n.bidi.Dir.NEUTRAL);
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse("style", b, a);
};
goog.html.SafeHtml.createMetaRefresh = function (a, b) {
a = goog.html.SafeUrl.unwrap(goog.html.SafeUrl.sanitize(a));
(goog.labs.userAgent.browser.isIE() || goog.labs.userAgent.browser.isEdge()) && goog.string.internal.contains(a, ";") && (a = "'" + a.replace(/'/g, "%27") + "'");
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse("meta", {
"http-equiv": "refresh",
content: (b || 0) + "; url=" + a
});
};
goog.html.SafeHtml.getAttrNameAndValue_ = function (a, b, c) {
if (c instanceof goog.string.Const) c = goog.string.Const.unwrap(c);else if ("style" == b.toLowerCase()) c = goog.html.SafeHtml.getStyleValue_(c);else {
if (/^on/i.test(b)) throw Error('Attribute "' + b + '" requires goog.string.Const value, "' + c + '" given.');
if (b.toLowerCase() in goog.html.SafeHtml.URL_ATTRIBUTES_) if (c instanceof goog.html.TrustedResourceUrl) c = goog.html.TrustedResourceUrl.unwrap(c);else if (c instanceof goog.html.SafeUrl) c = goog.html.SafeUrl.unwrap(c);else if (goog.isString(c)) c = goog.html.SafeUrl.sanitize(c).getTypedStringValue();else throw Error('Attribute "' + b + '" on tag "' + a + '" requires goog.html.SafeUrl, goog.string.Const, or string, value "' + c + '" given.');
}
c.implementsGoogStringTypedString && (c = c.getTypedStringValue());
goog.asserts.assert(goog.isString(c) || goog.isNumber(c), "String or number value expected, got " + typeof c + " with value: " + c);
return b + '="' + goog.string.internal.htmlEscape(String(c)) + '"';
};
goog.html.SafeHtml.getStyleValue_ = function (a) {
if (!goog.isObject(a)) throw Error('The "style" attribute requires goog.html.SafeStyle or map of style properties, ' + typeof a + " given: " + a);
a instanceof goog.html.SafeStyle || (a = goog.html.SafeStyle.create(a));
return goog.html.SafeStyle.unwrap(a);
};
goog.html.SafeHtml.createWithDir = function (a, b, c, d) {
b = goog.html.SafeHtml.create(b, c, d);
b.dir_ = a;
return b;
};
goog.html.SafeHtml.join = function (a, b) {
a = goog.html.SafeHtml.htmlEscape(a);
var c = a.getDirection(),
d = [],
e = function (a) {
goog.isArray(a) ? goog.array.forEach(a, e) : (a = goog.html.SafeHtml.htmlEscape(a), d.push(goog.html.SafeHtml.unwrap(a)), a = a.getDirection(), c == goog.i18n.bidi.Dir.NEUTRAL ? c = a : a != goog.i18n.bidi.Dir.NEUTRAL && c != a && (c = null));
};
goog.array.forEach(b, e);
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(d.join(goog.html.SafeHtml.unwrap(a)), c);
};
goog.html.SafeHtml.concat = function (a) {
return goog.html.SafeHtml.join(goog.html.SafeHtml.EMPTY, Array.prototype.slice.call(arguments));
};
goog.html.SafeHtml.concatWithDir = function (a, b) {
var c = goog.html.SafeHtml.concat(goog.array.slice(arguments, 1));
c.dir_ = a;
return c;
};
goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse = function (a, b) {
return new goog.html.SafeHtml().initSecurityPrivateDoNotAccessOrElse_(a, b);
};
goog.html.SafeHtml.prototype.initSecurityPrivateDoNotAccessOrElse_ = function (a, b) {
this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY ? goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY.createHTML(a) : a;
this.dir_ = b;
return this;
};
goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse = function (a, b, c) {
var d = null;
var e = "<" + a + goog.html.SafeHtml.stringifyAttributes(a, b);
goog.isDefAndNotNull(c) ? goog.isArray(c) || (c = [c]) : c = [];
goog.dom.tags.isVoidTag(a.toLowerCase()) ? (goog.asserts.assert(!c.length, "Void tag <" + a + "> does not allow content."), e += ">") : (d = goog.html.SafeHtml.concat(c), e += ">" + goog.html.SafeHtml.unwrap(d) + "</" + a + ">", d = d.getDirection());
(a = b && b.dir) && (d = /^(ltr|rtl|auto)$/i.test(a) ? goog.i18n.bidi.Dir.NEUTRAL : null);
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(e, d);
};
goog.html.SafeHtml.stringifyAttributes = function (a, b) {
var c = "";
if (b) for (var d in b) {
if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(d)) throw Error('Invalid attribute name "' + d + '".');
var e = b[d];
goog.isDefAndNotNull(e) && (c += " " + goog.html.SafeHtml.getAttrNameAndValue_(a, d, e));
}
return c;
};
goog.html.SafeHtml.combineAttributes = function (a, b, c) {
var d = {},
e;
for (e in a) goog.asserts.assert(e.toLowerCase() == e, "Must be lower case"), d[e] = a[e];
for (e in b) goog.asserts.assert(e.toLowerCase() == e, "Must be lower case"), d[e] = b[e];
for (e in c) {
var f = e.toLowerCase();
if (f in a) throw Error('Cannot override "' + f + '" attribute, got "' + e + '" with value "' + c[e] + '"');
f in b && delete d[f];
d[e] = c[e];
}
return d;
};
goog.html.SafeHtml.DOCTYPE_HTML = goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse("<!DOCTYPE html>", goog.i18n.bidi.Dir.NEUTRAL);
goog.html.SafeHtml.EMPTY = goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse("", goog.i18n.bidi.Dir.NEUTRAL);
goog.html.SafeHtml.BR = goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse("<br>", goog.i18n.bidi.Dir.NEUTRAL);
goog.html.uncheckedconversions = {};
goog.html.uncheckedconversions.safeHtmlFromStringKnownToSatisfyTypeContract = function (a, b, c) {
goog.asserts.assertString(goog.string.Const.unwrap(a), "must provide justification");
goog.asserts.assert(!goog.string.internal.isEmptyOrWhitespace(goog.string.Const.unwrap(a)), "must provide non-empty justification");
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(b, c || null);
};
goog.html.uncheckedconversions.safeScriptFromStringKnownToSatisfyTypeContract = function (a, b) {
goog.asserts.assertString(goog.string.Const.unwrap(a), "must provide justification");
goog.asserts.assert(!goog.string.internal.isEmptyOrWhitespace(goog.string.Const.unwrap(a)), "must provide non-empty justification");
return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(b);
};
goog.html.uncheckedconversions.safeStyleFromStringKnownToSatisfyTypeContract = function (a, b) {
goog.asserts.assertString(goog.string.Const.unwrap(a), "must provide justification");
goog.asserts.assert(!goog.string.internal.isEmptyOrWhitespace(goog.string.Const.unwrap(a)), "must provide non-empty justification");
return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(b);
};
goog.html.uncheckedconversions.safeStyleSheetFromStringKnownToSatisfyTypeContract = function (a, b) {
goog.asserts.assertString(goog.string.Const.unwrap(a), "must provide justification");
goog.asserts.assert(!goog.string.internal.isEmptyOrWhitespace(goog.string.Const.unwrap(a)), "must provide non-empty justification");
return goog.html.SafeStyleSheet.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(b);
};
goog.html.uncheckedconversions.safeUrlFromStringKnownToSatisfyTypeContract = function (a, b) {
goog.asserts.assertString(goog.string.Const.unwrap(a), "must provide justification");
goog.asserts.assert(!goog.string.internal.isEmptyOrWhitespace(goog.string.Const.unwrap(a)), "must provide non-empty justification");
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(b);
};
goog.html.uncheckedconversions.trustedResourceUrlFromStringKnownToSatisfyTypeContract = function (a, b) {
goog.asserts.assertString(goog.string.Const.unwrap(a), "must provide justification");
goog.asserts.assert(!goog.string.internal.isEmptyOrWhitespace(goog.string.Const.unwrap(a)), "must provide non-empty justification");
return goog.html.TrustedResourceUrl.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(b);
};
goog.dom.asserts = {};
goog.dom.asserts.assertIsLocation = function (a) {
if (goog.asserts.ENABLE_ASSERTS) {
var b = goog.dom.asserts.getWindow_(a);
b && (!a || !(a instanceof b.Location) && a instanceof b.Element) && goog.asserts.fail("Argument is not a Location (or a non-Element mock); got: %s", goog.dom.asserts.debugStringForType_(a));
}
return a;
};
goog.dom.asserts.assertIsElementType_ = function (a, b) {
if (goog.asserts.ENABLE_ASSERTS) {
var c = goog.dom.asserts.getWindow_(a);
c && "undefined" != typeof c[b] && (a && (a instanceof c[b] || !(a instanceof c.Location || a instanceof c.Element)) || goog.asserts.fail("Argument is not a %s (or a non-Element, non-Location mock); got: %s", b, goog.dom.asserts.debugStringForType_(a)));
}
return a;
};
goog.dom.asserts.assertIsHTMLAnchorElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLAnchorElement");
};
goog.dom.asserts.assertIsHTMLButtonElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLButtonElement");
};
goog.dom.asserts.assertIsHTMLLinkElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLLinkElement");
};
goog.dom.asserts.assertIsHTMLImageElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLImageElement");
};
goog.dom.asserts.assertIsHTMLAudioElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLAudioElement");
};
goog.dom.asserts.assertIsHTMLVideoElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLVideoElement");
};
goog.dom.asserts.assertIsHTMLInputElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLInputElement");
};
goog.dom.asserts.assertIsHTMLTextAreaElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLTextAreaElement");
};
goog.dom.asserts.assertIsHTMLCanvasElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLCanvasElement");
};
goog.dom.asserts.assertIsHTMLEmbedElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLEmbedElement");
};
goog.dom.asserts.assertIsHTMLFormElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLFormElement");
};
goog.dom.asserts.assertIsHTMLFrameElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLFrameElement");
};
goog.dom.asserts.assertIsHTMLIFrameElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLIFrameElement");
};
goog.dom.asserts.assertIsHTMLObjectElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLObjectElement");
};
goog.dom.asserts.assertIsHTMLScriptElement = function (a) {
return goog.dom.asserts.assertIsElementType_(a, "HTMLScriptElement");
};
goog.dom.asserts.debugStringForType_ = function (a) {
if (goog.isObject(a)) try {
return a.constructor.displayName || a.constructor.name || Object.prototype.toString.call(a);
} catch (b) {
return "<object could not be stringified>";
} else return void 0 === a ? "undefined" : null === a ? "null" : typeof a;
};
goog.dom.asserts.getWindow_ = function (a) {
try {
var b = a && a.ownerDocument,
c = b && (b.defaultView || b.parentWindow);
c = c || goog.global;
if (c.Element && c.Location) return c;
} catch (d) {}
return null;
};
goog.functions = {};
goog.functions.constant = function (a) {
return function () {
return a;
};
};
goog.functions.FALSE = function () {
return !1;
};
goog.functions.TRUE = function () {
return !0;
};
goog.functions.NULL = function () {
return null;
};
goog.functions.identity = function (a, b) {
return a;
};
goog.functions.error = function (a) {
return function () {
throw Error(a);
};
};
goog.functions.fail = function (a) {
return function () {
throw a;
};
};
goog.functions.lock = function (a, b) {
b = b || 0;
return function () {
return a.apply(this, Array.prototype.slice.call(arguments, 0, b));
};
};
goog.functions.nth = function (a) {
return function () {
return arguments[a];
};
};
goog.functions.partialRight = function (a, b) {
var c = Array.prototype.slice.call(arguments, 1);
return function () {
var b = Array.prototype.slice.call(arguments);
b.push.apply(b, c);
return a.apply(this, b);
};
};
goog.functions.withReturnValue = function (a, b) {
return goog.functions.sequence(a, goog.functions.constant(b));
};
goog.functions.equalTo = function (a, b) {
return function (c) {
return b ? a == c : a === c;
};
};
goog.functions.compose = function (a, b) {
var c = arguments,
d = c.length;
return function () {
var a;
d && (a = c[d - 1].apply(this, arguments));
for (var b = d - 2; 0 <= b; b--) a = c[b].call(this, a);
return a;
};
};
goog.functions.sequence = function (a) {
var b = arguments,
c = b.length;
return function () {
for (var a, e = 0; e < c; e++) a = b[e].apply(this, arguments);
return a;
};
};
goog.functions.and = function (a) {
var b = arguments,
c = b.length;
return function () {
for (var a = 0; a < c; a++) if (!b[a].apply(this, arguments)) return !1;
return !0;
};
};
goog.functions.or = function (a) {
var b = arguments,
c = b.length;
return function () {
for (var a = 0; a < c; a++) if (b[a].apply(this, arguments)) return !0;
return !1;
};
};
goog.functions.not = function (a) {
return function () {
return !a.apply(this, arguments);
};
};
goog.functions.create = function (a, b) {
var c = function () {};
c.prototype = a.prototype;
c = new c();
a.apply(c, Array.prototype.slice.call(arguments, 1));
return c;
};
goog.functions.CACHE_RETURN_VALUE = !0;
goog.functions.cacheReturnValue = function (a) {
var b = !1,
c;
return function () {
if (!goog.functions.CACHE_RETURN_VALUE) return a();
b || (c = a(), b = !0);
return c;
};
};
goog.functions.once = function (a) {
var b = a;
return function () {
if (b) {
var a = b;
b = null;
a();
}
};
};
goog.functions.debounce = function (a, b, c) {
var d = 0;
return function (e) {
goog.global.clearTimeout(d);
var f = arguments;
d = goog.global.setTimeout(function () {
a.apply(c, f);
}, b);
};
};
goog.functions.throttle = function (a, b, c) {
var d = 0,
e = !1,
f = [],
g = function () {
d = 0;
e && (e = !1, h());
},
h = function () {
d = goog.global.setTimeout(g, b);
a.apply(c, f);
};
return function (a) {
f = arguments;
d ? e = !0 : h();
};
};
goog.functions.rateLimit = function (a, b, c) {
var d = 0,
e = function () {
d = 0;
};
return function (f) {
d || (d = goog.global.setTimeout(e, b), a.apply(c, arguments));
};
};
goog.dom.safe = {};
goog.dom.safe.InsertAdjacentHtmlPosition = {
AFTERBEGIN: "afterbegin",
AFTEREND: "afterend",
BEFOREBEGIN: "beforebegin",
BEFOREEND: "beforeend"
};
goog.dom.safe.insertAdjacentHtml = function (a, b, c) {
a.insertAdjacentHTML(b, goog.html.SafeHtml.unwrapTrustedHTML(c));
};
goog.dom.safe.SET_INNER_HTML_DISALLOWED_TAGS_ = {
MATH: !0,
SCRIPT: !0,
STYLE: !0,
SVG: !0,
TEMPLATE: !0
};
goog.dom.safe.isInnerHtmlCleanupRecursive_ = goog.functions.cacheReturnValue(function () {
if (goog.DEBUG && "undefined" === typeof document) return !1;
var a = document.createElement("div"),
b = document.createElement("div");
b.appendChild(document.createElement("div"));
a.appendChild(b);
if (goog.DEBUG && !a.firstChild) return !1;
b = a.firstChild.firstChild;
a.innerHTML = goog.html.SafeHtml.unwrapTrustedHTML(goog.html.SafeHtml.EMPTY);
return !b.parentElement;
});
goog.dom.safe.unsafeSetInnerHtmlDoNotUseOrElse = function (a, b) {
if (goog.dom.safe.isInnerHtmlCleanupRecursive_()) for (; a.lastChild;) a.removeChild(a.lastChild);
a.innerHTML = goog.html.SafeHtml.unwrapTrustedHTML(b);
};
goog.dom.safe.setInnerHtml = function (a, b) {
if (goog.asserts.ENABLE_ASSERTS) {
var c = a.tagName.toUpperCase();
if (goog.dom.safe.SET_INNER_HTML_DISALLOWED_TAGS_[c]) throw Error("goog.dom.safe.setInnerHtml cannot be used to set content of " + a.tagName + ".");
}
goog.dom.safe.unsafeSetInnerHtmlDoNotUseOrElse(a, b);
};
goog.dom.safe.setOuterHtml = function (a, b) {
a.outerHTML = goog.html.SafeHtml.unwrapTrustedHTML(b);
};
goog.dom.safe.setFormElementAction = function (a, b) {
b = b instanceof goog.html.SafeUrl ? b : goog.html.SafeUrl.sanitizeAssertUnchanged(b);
goog.dom.asserts.assertIsHTMLFormElement(a).action = goog.html.SafeUrl.unwrapTrustedURL(b);
};
goog.dom.safe.setButtonFormAction = function (a, b) {
b = b instanceof goog.html.SafeUrl ? b : goog.html.SafeUrl.sanitizeAssertUnchanged(b);
goog.dom.asserts.assertIsHTMLButtonElement(a).formAction = goog.html.SafeUrl.unwrapTrustedURL(b);
};
goog.dom.safe.setInputFormAction = function (a, b) {
b = b instanceof goog.html.SafeUrl ? b : goog.html.SafeUrl.sanitizeAssertUnchanged(b);
goog.dom.asserts.assertIsHTMLInputElement(a).formAction = goog.html.SafeUrl.unwrapTrustedURL(b);
};
goog.dom.safe.setStyle = function (a, b) {
a.style.cssText = goog.html.SafeStyle.unwrap(b);
};
goog.dom.safe.documentWrite = function (a, b) {
a.write(goog.html.SafeHtml.unwrapTrustedHTML(b));
};
goog.dom.safe.setAnchorHref = function (a, b) {
goog.dom.asserts.assertIsHTMLAnchorElement(a);
b = b instanceof goog.html.SafeUrl ? b : goog.html.SafeUrl.sanitizeAssertUnchanged(b);
a.href = goog.html.SafeUrl.unwrapTrustedURL(b);
};
goog.dom.safe.setImageSrc = function (a, b) {
goog.dom.asserts.assertIsHTMLImageElement(a);
if (!(b instanceof goog.html.SafeUrl)) {
var c = /^data:image\//i.test(b);
b = goog.html.SafeUrl.sanitizeAssertUnchanged(b, c);
}
a.src = goog.html.SafeUrl.unwrapTrustedURL(b);
};
goog.dom.safe.setAudioSrc = function (a, b) {
goog.dom.asserts.assertIsHTMLAudioElement(a);
if (!(b instanceof goog.html.SafeUrl)) {
var c = /^data:audio\//i.test(b);
b = goog.html.SafeUrl.sanitizeAssertUnchanged(b, c);
}
a.src = goog.html.SafeUrl.unwrapTrustedURL(b);
};
goog.dom.safe.setVideoSrc = function (a, b) {
goog.dom.asserts.assertIsHTMLVideoElement(a);
if (!(b instanceof goog.html.SafeUrl)) {
var c = /^data:video\//i.test(b);
b = goog.html.SafeUrl.sanitizeAssertUnchanged(b, c);
}
a.src = goog.html.SafeUrl.unwrapTrustedURL(b);
};
goog.dom.safe.setEmbedSrc = function (a, b) {
goog.dom.asserts.assertIsHTMLEmbedElement(a);
a.src = goog.html.TrustedResourceUrl.unwrapTrustedScriptURL(b);
};
goog.dom.safe.setFrameSrc = function (a, b) {
goog.dom.asserts.assertIsHTMLFrameElement(a);
a.src = goog.html.TrustedResourceUrl.unwrapTrustedURL(b);
};
goog.dom.safe.setIframeSrc = function (a, b) {
goog.dom.asserts.assertIsHTMLIFrameElement(a);
a.src = goog.html.TrustedResourceUrl.unwrapTrustedURL(b);
};
goog.dom.safe.setIframeSrcdoc = function (a, b) {
goog.dom.asserts.assertIsHTMLIFrameElement(a);
a.srcdoc = goog.html.SafeHtml.unwrapTrustedHTML(b);
};
goog.dom.safe.setLinkHrefAndRel = function (a, b, c) {
goog.dom.asserts.assertIsHTMLLinkElement(a);
a.rel = c;
goog.string.internal.caseInsensitiveContains(c, "stylesheet") ? (goog.asserts.assert(b instanceof goog.html.TrustedResourceUrl, 'URL must be TrustedResourceUrl because "rel" contains "stylesheet"'), a.href = goog.html.TrustedResourceUrl.unwrapTrustedURL(b)) : a.href = b instanceof goog.html.TrustedResourceUrl ? goog.html.TrustedResourceUrl.unwrapTrustedURL(b) : b instanceof goog.html.SafeUrl ? goog.html.SafeUrl.unwrapTrustedURL(b) : goog.html.SafeUrl.unwrapTrustedURL(goog.html.SafeUrl.sanitizeAssertUnchanged(b));
};
goog.dom.safe.setObjectData = function (a, b) {
goog.dom.asserts.assertIsHTMLObjectElement(a);
a.data = goog.html.TrustedResourceUrl.unwrapTrustedScriptURL(b);
};
goog.dom.safe.setScriptSrc = function (a, b) {
goog.dom.asserts.assertIsHTMLScriptElement(a);
a.src = goog.html.TrustedResourceUrl.unwrapTrustedScriptURL(b);
(b = goog.getScriptNonce()) && a.setAttribute("nonce", b);
};
goog.dom.safe.setScriptContent = function (a, b) {
goog.dom.asserts.assertIsHTMLScriptElement(a);
a.text = goog.html.SafeScript.unwrapTrustedScript(b);
(b = goog.getScriptNonce()) && a.setAttribute("nonce", b);
};
goog.dom.safe.setLocationHref = function (a, b) {
goog.dom.asserts.assertIsLocation(a);
b = b instanceof goog.html.SafeUrl ? b : goog.html.SafeUrl.sanitizeAssertUnchanged(b);
a.href = goog.html.SafeUrl.unwrapTrustedURL(b);
};
goog.dom.safe.assignLocation = function (a, b) {
goog.dom.asserts.assertIsLocation(a);
b = b instanceof goog.html.SafeUrl ? b : goog.html.SafeUrl.sanitizeAssertUnchanged(b);
a.assign(goog.html.SafeUrl.unwrapTrustedURL(b));
};
goog.dom.safe.replaceLocation = function (a, b) {
goog.dom.asserts.assertIsLocation(a);
b = b instanceof goog.html.SafeUrl ? b : goog.html.SafeUrl.sanitizeAssertUnchanged(b);
a.replace(goog.html.SafeUrl.unwrapTrustedURL(b));
};
goog.dom.safe.openInWindow = function (a, b, c, d, e) {
a = a instanceof goog.html.SafeUrl ? a : goog.html.SafeUrl.sanitizeAssertUnchanged(a);
return (b || goog.global).open(goog.html.SafeUrl.unwrapTrustedURL(a), c ? goog.string.Const.unwrap(c) : "", d, e);
};
goog.dom.safe.parseFromStringHtml = function (a, b) {
return goog.dom.safe.parseFromString(a, b, "text/html");
};
goog.dom.safe.parseFromString = function (a, b, c) {
return a.parseFromString(goog.html.SafeHtml.unwrapTrustedHTML(b), c);
};
goog.dom.safe.createImageFromBlob = function (a) {
if (!/^image\/.*/g.test(a.type)) throw Error("goog.dom.safe.createImageFromBlob only accepts MIME type image/.*.");
var b = goog.global.URL.createObjectURL(a);
a = new goog.global.Image();
a.onload = function () {
goog.global.URL.revokeObjectURL(b);
};
goog.dom.safe.setImageSrc(a, goog.html.uncheckedconversions.safeUrlFromStringKnownToSatisfyTypeContract(goog.string.Const.from("Image blob URL."), b));
return a;
};
goog.string.DETECT_DOUBLE_ESCAPING = !1;
goog.string.FORCE_NON_DOM_HTML_UNESCAPING = !1;
goog.string.Unicode = {
NBSP: "\u00a0"
};
goog.string.startsWith = goog.string.internal.startsWith;
goog.string.endsWith = goog.string.internal.endsWith;
goog.string.caseInsensitiveStartsWith = goog.string.internal.caseInsensitiveStartsWith;
goog.string.caseInsensitiveEndsWith = goog.string.internal.caseInsensitiveEndsWith;
goog.string.caseInsensitiveEquals = goog.string.internal.caseInsensitiveEquals;
goog.string.subs = function (a, b) {
for (var c = a.split("%s"), d = "", e = Array.prototype.slice.call(arguments, 1); e.length && 1 < c.length;) d += c.shift() + e.shift();
return d + c.join("%s");
};
goog.string.collapseWhitespace = function (a) {
return a.replace(/[\s\xa0]+/g, " ").replace(/^\s+|\s+$/g, "");
};
goog.string.isEmptyOrWhitespace = goog.string.internal.isEmptyOrWhitespace;
goog.string.isEmptyString = function (a) {
return 0 == a.length;
};
goog.string.isEmpty = goog.string.isEmptyOrWhitespace;
goog.string.isEmptyOrWhitespaceSafe = function (a) {
return goog.string.isEmptyOrWhitespace(goog.string.makeSafe(a));
};
goog.string.isEmptySafe = goog.string.isEmptyOrWhitespaceSafe;
goog.string.isBreakingWhitespace = function (a) {
return !/[^\t\n\r ]/.test(a);
};
goog.string.isAlpha = function (a) {
return !/[^a-zA-Z]/.test(a);
};
goog.string.isNumeric = function (a) {
return !/[^0-9]/.test(a);
};
goog.string.isAlphaNumeric = function (a) {
return !/[^a-zA-Z0-9]/.test(a);
};
goog.string.isSpace = function (a) {
return " " == a;
};
goog.string.isUnicodeChar = function (a) {
return 1 == a.length && " " <= a && "~" >= a || "\u0080" <= a && "\ufffd" >= a;
};
goog.string.stripNewlines = function (a) {
return a.replace(/(\r\n|\r|\n)+/g, " ");
};
goog.string.canonicalizeNewlines = function (a) {
return a.replace(/(\r\n|\r|\n)/g, "\n");
};
goog.string.normalizeWhitespace = function (a) {
return a.replace(/\xa0|\s/g, " ");
};
goog.string.normalizeSpaces = function (a) {
return a.replace(/\xa0|[ \t]+/g, " ");
};
goog.string.collapseBreakingSpaces = function (a) {
return a.replace(/[\t\r\n ]+/g, " ").replace(/^[\t\r\n ]+|[\t\r\n ]+$/g, "");
};
goog.string.trim = goog.string.internal.trim;
goog.string.trimLeft = function (a) {
return a.replace(/^[\s\xa0]+/, "");
};
goog.string.trimRight = function (a) {
return a.replace(/[\s\xa0]+$/, "");
};
goog.string.caseInsensitiveCompare = goog.string.internal.caseInsensitiveCompare;
goog.string.numberAwareCompare_ = function (a, b, c) {
if (a == b) return 0;
if (!a) return -1;
if (!b) return 1;
for (var d = a.toLowerCase().match(c), e = b.toLowerCase().match(c), f = Math.min(d.length, e.length), g = 0; g < f; g++) {
c = d[g];
var h = e[g];
if (c != h) return a = parseInt(c, 10), !isNaN(a) && (b = parseInt(h, 10), !isNaN(b) && a - b) ? a - b : c < h ? -1 : 1;
}
return d.length != e.length ? d.length - e.length : a < b ? -1 : 1;
};
goog.string.intAwareCompare = function (a, b) {
return goog.string.numberAwareCompare_(a, b, /\d+|\D+/g);
};
goog.string.floatAwareCompare = function (a, b) {
return goog.string.numberAwareCompare_(a, b, /\d+|\.\d+|\D+/g);
};
goog.string.numerateCompare = goog.string.floatAwareCompare;
goog.string.urlEncode = function (a) {
return encodeURIComponent(String(a));
};
goog.string.urlDecode = function (a) {
return decodeURIComponent(a.replace(/\+/g, " "));
};
goog.string.newLineToBr = goog.string.internal.newLineToBr;
goog.string.htmlEscape = function (a, b) {
a = goog.string.internal.htmlEscape(a, b);
goog.string.DETECT_DOUBLE_ESCAPING && (a = a.replace(goog.string.E_RE_, "&#101;"));
return a;
};
goog.string.E_RE_ = /e/g;
goog.string.unescapeEntities = function (a) {
return goog.string.contains(a, "&") ? !goog.string.FORCE_NON_DOM_HTML_UNESCAPING && "document" in goog.global ? goog.string.unescapeEntitiesUsingDom_(a) : goog.string.unescapePureXmlEntities_(a) : a;
};
goog.string.unescapeEntitiesWithDocument = function (a, b) {
return goog.string.contains(a, "&") ? goog.string.unescapeEntitiesUsingDom_(a, b) : a;
};
goog.string.unescapeEntitiesUsingDom_ = function (a, b) {
var c = {
"&amp;": "&",
"&lt;": "<",
"&gt;": ">",
"&quot;": '"'
};
var d = b ? b.createElement("div") : goog.global.document.createElement("div");
return a.replace(goog.string.HTML_ENTITY_PATTERN_, function (a, b) {
var e = c[a];
if (e) return e;
"#" == b.charAt(0) && (b = Number("0" + b.substr(1)), isNaN(b) || (e = String.fromCharCode(b)));
e || (goog.dom.safe.setInnerHtml(d, goog.html.uncheckedconversions.safeHtmlFromStringKnownToSatisfyTypeContract(goog.string.Const.from("Single HTML entity."), a + " ")), e = d.firstChild.nodeValue.slice(0, -1));
return c[a] = e;
});
};
goog.string.unescapePureXmlEntities_ = function (a) {
return a.replace(/&([^;]+);/g, function (a, c) {
switch (c) {
case "amp":
return "&";
case "lt":
return "<";
case "gt":
return ">";
case "quot":
return '"';
default:
return "#" != c.charAt(0) || (c = Number("0" + c.substr(1)), isNaN(c)) ? a : String.fromCharCode(c);
}
});
};
goog.string.HTML_ENTITY_PATTERN_ = /&([^;\s<&]+);?/g;
goog.string.whitespaceEscape = function (a, b) {
return goog.string.newLineToBr(a.replace(/ /g, " &#160;"), b);
};
goog.string.preserveSpaces = function (a) {
return a.replace(/(^|[\n ]) /g, "$1" + goog.string.Unicode.NBSP);
};
goog.string.stripQuotes = function (a, b) {
for (var c = b.length, d = 0; d < c; d++) {
var e = 1 == c ? b : b.charAt(d);
if (a.charAt(0) == e && a.charAt(a.length - 1) == e) return a.substring(1, a.length - 1);
}
return a;
};
goog.string.truncate = function (a, b, c) {
c && (a = goog.string.unescapeEntities(a));
a.length > b && (a = a.substring(0, b - 3) + "...");
c && (a = goog.string.htmlEscape(a));
return a;
};
goog.string.truncateMiddle = function (a, b, c, d) {
c && (a = goog.string.unescapeEntities(a));
if (d && a.length > b) {
d > b && (d = b);
var e = a.length - d;
a = a.substring(0, b - d) + "..." + a.substring(e);
} else a.length > b && (d = Math.floor(b / 2), e = a.length - d, a = a.substring(0, d + b % 2) + "..." + a.substring(e));
c && (a = goog.string.htmlEscape(a));
return a;
};
goog.string.specialEscapeChars_ = {
"\x00": "\\0",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
"\t": "\\t",
"\x0B": "\\x0B",
'"': '\\"',
"\\": "\\\\",
"<": "\\u003C"
};
goog.string.jsEscapeCache_ = {
"'": "\\'"
};
goog.string.quote = function (a) {
a = String(a);
for (var b = ['"'], c = 0; c < a.length; c++) {
var d = a.charAt(c),
e = d.charCodeAt(0);
b[c + 1] = goog.string.specialEscapeChars_[d] || (31 < e && 127 > e ? d : goog.string.escapeChar(d));
}
b.push('"');
return b.join("");
};
goog.string.escapeString = function (a) {
for (var b = [], c = 0; c < a.length; c++) b[c] = goog.string.escapeChar(a.charAt(c));
return b.join("");
};
goog.string.escapeChar = function (a) {
if (a in goog.string.jsEscapeCache_) return goog.string.jsEscapeCache_[a];
if (a in goog.string.specialEscapeChars_) return goog.string.jsEscapeCache_[a] = goog.string.specialEscapeChars_[a];
var b = a.charCodeAt(0);
if (31 < b && 127 > b) var c = a;else {
if (256 > b) {
if (c = "\\x", 16 > b || 256 < b) c += "0";
} else c = "\\u", 4096 > b && (c += "0");
c += b.toString(16).toUpperCase();
}
return goog.string.jsEscapeCache_[a] = c;
};
goog.string.contains = goog.string.internal.contains;
goog.string.caseInsensitiveContains = goog.string.internal.caseInsensitiveContains;
goog.string.countOf = function (a, b) {
return a && b ? a.split(b).length - 1 : 0;
};
goog.string.removeAt = function (a, b, c) {
var d = a;
0 <= b && b < a.length && 0 < c && (d = a.substr(0, b) + a.substr(b + c, a.length - b - c));
return d;
};
goog.string.remove = function (a, b) {
return a.replace(b, "");
};
goog.string.removeAll = function (a, b) {
b = new RegExp(goog.string.regExpEscape(b), "g");
return a.replace(b, "");
};
goog.string.replaceAll = function (a, b, c) {
b = new RegExp(goog.string.regExpEscape(b), "g");
return a.replace(b, c.replace(/\$/g, "$$$$"));
};
goog.string.regExpEscape = function (a) {
return String(a).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, "\\$1").replace(/\x08/g, "\\x08");
};
goog.string.repeat = String.prototype.repeat ? function (a, b) {
return a.repeat(b);
} : function (a, b) {
return Array(b + 1).join(a);
};
goog.string.padNumber = function (a, b, c) {
a = goog.isDef(c) ? a.toFixed(c) : String(a);
c = a.indexOf(".");
-1 == c && (c = a.length);
return goog.string.repeat("0", Math.max(0, b - c)) + a;
};
goog.string.makeSafe = function (a) {
return null == a ? "" : String(a);
};
goog.string.buildString = function (a) {
return Array.prototype.join.call(arguments, "");
};
goog.string.getRandomString = function () {
return Math.floor(2147483648 * Math.random()).toString(36) + Math.abs(Math.floor(2147483648 * Math.random()) ^ goog.now()).toString(36);
};
goog.string.compareVersions = goog.string.internal.compareVersions;
goog.string.hashCode = function (a) {
for (var b = 0, c = 0; c < a.length; ++c) b = 31 * b + a.charCodeAt(c) >>> 0;
return b;
};
goog.string.uniqueStringCounter_ = 2147483648 * Math.random() | 0;
goog.string.createUniqueString = function () {
return "goog_" + goog.string.uniqueStringCounter_++;
};
goog.string.toNumber = function (a) {
var b = Number(a);
return 0 == b && goog.string.isEmptyOrWhitespace(a) ? NaN : b;
};
goog.string.isLowerCamelCase = function (a) {
return /^[a-z]+([A-Z][a-z]*)*$/.test(a);
};
goog.string.isUpperCamelCase = function (a) {
return /^([A-Z][a-z]*)+$/.test(a);
};
goog.string.toCamelCase = function (a) {
return String(a).replace(/\-([a-z])/g, function (a, c) {
return c.toUpperCase();
});
};
goog.string.toSelectorCase = function (a) {
return String(a).replace(/([A-Z])/g, "-$1").toLowerCase();
};
goog.string.toTitleCase = function (a, b) {
b = goog.isString(b) ? goog.string.regExpEscape(b) : "\\s";
return a.replace(new RegExp("(^" + (b ? "|[" + b + "]+" : "") + ")([a-z])", "g"), function (a, b, e) {
return b + e.toUpperCase();
});
};
goog.string.capitalize = function (a) {
return String(a.charAt(0)).toUpperCase() + String(a.substr(1)).toLowerCase();
};
goog.string.parseInt = function (a) {
isFinite(a) && (a = String(a));
return goog.isString(a) ? /^\s*-?0x/i.test(a) ? parseInt(a, 16) : parseInt(a, 10) : NaN;
};
goog.string.splitLimit = function (a, b, c) {
a = a.split(b);
for (var d = []; 0 < c && a.length;) d.push(a.shift()), c--;
a.length && d.push(a.join(b));
return d;
};
goog.string.lastComponent = function (a, b) {
if (b) "string" == typeof b && (b = [b]);else return a;
for (var c = -1, d = 0; d < b.length; d++) if ("" != b[d]) {
var e = a.lastIndexOf(b[d]);
e > c && (c = e);
}
return -1 == c ? a : a.slice(c + 1);
};
goog.string.editDistance = function (a, b) {
var c = [],
d = [];
if (a == b) return 0;
if (!a.length || !b.length) return Math.max(a.length, b.length);
for (var e = 0; e < b.length + 1; e++) c[e] = e;
for (e = 0; e < a.length; e++) {
d[0] = e + 1;
for (var f = 0; f < b.length; f++) d[f + 1] = Math.min(d[f] + 1, c[f + 1] + 1, c[f] + Number(a[e] != b[f]));
for (f = 0; f < c.length; f++) c[f] = d[f];
}
return d[b.length];
};
goog.labs.userAgent.platform = {};
goog.labs.userAgent.platform.isAndroid = function () {
return goog.labs.userAgent.util.matchUserAgent("Android");
};
goog.labs.userAgent.platform.isIpod = function () {
return goog.labs.userAgent.util.matchUserAgent("iPod");
};
goog.labs.userAgent.platform.isIphone = function () {
return goog.labs.userAgent.util.matchUserAgent("iPhone") && !goog.labs.userAgent.util.matchUserAgent("iPod") && !goog.labs.userAgent.util.matchUserAgent("iPad");
};
goog.labs.userAgent.platform.isIpad = function () {
return goog.labs.userAgent.util.matchUserAgent("iPad");
};
goog.labs.userAgent.platform.isIos = function () {
return goog.labs.userAgent.platform.isIphone() || goog.labs.userAgent.platform.isIpad() || goog.labs.userAgent.platform.isIpod();
};
goog.labs.userAgent.platform.isMacintosh = function () {
return goog.labs.userAgent.util.matchUserAgent("Macintosh");
};
goog.labs.userAgent.platform.isLinux = function () {
return goog.labs.userAgent.util.matchUserAgent("Linux");
};
goog.labs.userAgent.platform.isWindows = function () {
return goog.labs.userAgent.util.matchUserAgent("Windows");
};
goog.labs.userAgent.platform.isChromeOS = function () {
return goog.labs.userAgent.util.matchUserAgent("CrOS");
};
goog.labs.userAgent.platform.isChromecast = function () {
return goog.labs.userAgent.util.matchUserAgent("CrKey");
};
goog.labs.userAgent.platform.isKaiOS = function () {
return goog.labs.userAgent.util.matchUserAgentIgnoreCase("KaiOS");
};
goog.labs.userAgent.platform.isGo2Phone = function () {
return goog.labs.userAgent.util.matchUserAgentIgnoreCase("GAFP");
};
goog.labs.userAgent.platform.getVersion = function () {
var a = goog.labs.userAgent.util.getUserAgent(),
b = "";
goog.labs.userAgent.platform.isWindows() ? (b = /Windows (?:NT|Phone) ([0-9.]+)/, b = (a = b.exec(a)) ? a[1] : "0.0") : goog.labs.userAgent.platform.isIos() ? (b = /(?:iPhone|iPod|iPad|CPU)\s+OS\s+(\S+)/, b = (a = b.exec(a)) && a[1].replace(/_/g, ".")) : goog.labs.userAgent.platform.isMacintosh() ? (b = /Mac OS X ([0-9_.]+)/, b = (a = b.exec(a)) ? a[1].replace(/_/g, ".") : "10") : goog.labs.userAgent.platform.isKaiOS() ? (b = /(?:KaiOS)\/(\S+)/i, b = (a = b.exec(a)) && a[1]) : goog.labs.userAgent.platform.isAndroid() ? (b = /Android\s+([^\);]+)(\)|;)/, b = (a = b.exec(a)) && a[1]) : goog.labs.userAgent.platform.isChromeOS() && (b = /(?:CrOS\s+(?:i686|x86_64)\s+([0-9.]+))/, b = (a = b.exec(a)) && a[1]);
return b || "";
};
goog.labs.userAgent.platform.isVersionOrHigher = function (a) {
return 0 <= goog.string.compareVersions(goog.labs.userAgent.platform.getVersion(), a);
};
goog.reflect = {};
goog.reflect.object = function (a, b) {
return b;
};
goog.reflect.objectProperty = function (a, b) {
return a;
};
goog.reflect.sinkValue = function (a) {
goog.reflect.sinkValue[" "](a);
return a;
};
goog.reflect.sinkValue[" "] = goog.nullFunction;
goog.reflect.canAccessProperty = function (a, b) {
try {
return goog.reflect.sinkValue(a[b]), !0;
} catch (c) {}
return !1;
};
goog.reflect.cache = function (a, b, c, d) {
d = d ? d(b) : b;
return Object.prototype.hasOwnProperty.call(a, d) ? a[d] : a[d] = c(b);
};
goog.labs.userAgent.engine = {};
goog.labs.userAgent.engine.isPresto = function () {
return goog.labs.userAgent.util.matchUserAgent("Presto");
};
goog.labs.userAgent.engine.isTrident = function () {
return goog.labs.userAgent.util.matchUserAgent("Trident") || goog.labs.userAgent.util.matchUserAgent("MSIE");
};
goog.labs.userAgent.engine.isEdge = function () {
return goog.labs.userAgent.util.matchUserAgent("Edge");
};
goog.labs.userAgent.engine.isWebKit = function () {
return goog.labs.userAgent.util.matchUserAgentIgnoreCase("WebKit") && !goog.labs.userAgent.engine.isEdge();
};
goog.labs.userAgent.engine.isGecko = function () {
return goog.labs.userAgent.util.matchUserAgent("Gecko") && !goog.labs.userAgent.engine.isWebKit() && !goog.labs.userAgent.engine.isTrident() && !goog.labs.userAgent.engine.isEdge();
};
goog.labs.userAgent.engine.getVersion = function () {
var a = goog.labs.userAgent.util.getUserAgent();
if (a) {
a = goog.labs.userAgent.util.extractVersionTuples(a);
var b = goog.labs.userAgent.engine.getEngineTuple_(a);
if (b) return "Gecko" == b[0] ? goog.labs.userAgent.engine.getVersionForKey_(a, "Firefox") : b[1];
a = a[0];
var c;
if (a && (c = a[2]) && (c = /Trident\/([^\s;]+)/.exec(c))) return c[1];
}
return "";
};
goog.labs.userAgent.engine.getEngineTuple_ = function (a) {
if (!goog.labs.userAgent.engine.isEdge()) return a[1];
for (var b = 0; b < a.length; b++) {
var c = a[b];
if ("Edge" == c[0]) return c;
}
};
goog.labs.userAgent.engine.isVersionOrHigher = function (a) {
return 0 <= goog.string.compareVersions(goog.labs.userAgent.engine.getVersion(), a);
};
goog.labs.userAgent.engine.getVersionForKey_ = function (a, b) {
return (a = goog.array.find(a, function (a) {
return b == a[0];
})) && a[1] || "";
};
goog.userAgent = {};
goog.userAgent.ASSUME_IE = !1;
goog.userAgent.ASSUME_EDGE = !1;
goog.userAgent.ASSUME_GECKO = !1;
goog.userAgent.ASSUME_WEBKIT = !1;
goog.userAgent.ASSUME_MOBILE_WEBKIT = !1;
goog.userAgent.ASSUME_OPERA = !1;
goog.userAgent.ASSUME_ANY_VERSION = !1;
goog.userAgent.BROWSER_KNOWN_ = goog.userAgent.ASSUME_IE || goog.userAgent.ASSUME_EDGE || goog.userAgent.ASSUME_GECKO || goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_OPERA;
goog.userAgent.getUserAgentString = function () {
return goog.labs.userAgent.util.getUserAgent();
};
goog.userAgent.getNavigatorTyped = function () {
return goog.global.navigator || null;
};
goog.userAgent.getNavigator = function () {
return goog.userAgent.getNavigatorTyped();
};
goog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ? goog.userAgent.ASSUME_OPERA : goog.labs.userAgent.browser.isOpera();
goog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ? goog.userAgent.ASSUME_IE : goog.labs.userAgent.browser.isIE();
goog.userAgent.EDGE = goog.userAgent.BROWSER_KNOWN_ ? goog.userAgent.ASSUME_EDGE : goog.labs.userAgent.engine.isEdge();
goog.userAgent.EDGE_OR_IE = goog.userAgent.EDGE || goog.userAgent.IE;
goog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ? goog.userAgent.ASSUME_GECKO : goog.labs.userAgent.engine.isGecko();
goog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ? goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT : goog.labs.userAgent.engine.isWebKit();
goog.userAgent.isMobile_ = function () {
return goog.userAgent.WEBKIT && goog.labs.userAgent.util.matchUserAgent("Mobile");
};
goog.userAgent.MOBILE = goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.isMobile_();
goog.userAgent.SAFARI = goog.userAgent.WEBKIT;
goog.userAgent.determinePlatform_ = function () {
var a = goog.userAgent.getNavigatorTyped();
return a && a.platform || "";
};
goog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();
goog.userAgent.ASSUME_MAC = !1;
goog.userAgent.ASSUME_WINDOWS = !1;
goog.userAgent.ASSUME_LINUX = !1;
goog.userAgent.ASSUME_X11 = !1;
goog.userAgent.ASSUME_ANDROID = !1;
goog.userAgent.ASSUME_IPHONE = !1;
goog.userAgent.ASSUME_IPAD = !1;
goog.userAgent.ASSUME_IPOD = !1;
goog.userAgent.ASSUME_KAIOS = !1;
goog.userAgent.ASSUME_GO2PHONE = !1;
goog.userAgent.PLATFORM_KNOWN_ = goog.userAgent.ASSUME_MAC || goog.userAgent.ASSUME_WINDOWS || goog.userAgent.ASSUME_LINUX || goog.userAgent.ASSUME_X11 || goog.userAgent.ASSUME_ANDROID || goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD || goog.userAgent.ASSUME_IPOD;
goog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_MAC : goog.labs.userAgent.platform.isMacintosh();
goog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_WINDOWS : goog.labs.userAgent.platform.isWindows();
goog.userAgent.isLegacyLinux_ = function () {
return goog.labs.userAgent.platform.isLinux() || goog.labs.userAgent.platform.isChromeOS();
};
goog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_LINUX : goog.userAgent.isLegacyLinux_();
goog.userAgent.isX11_ = function () {
var a = goog.userAgent.getNavigatorTyped();
return !!a && goog.string.contains(a.appVersion || "", "X11");
};
goog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_X11 : goog.userAgent.isX11_();
goog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_ANDROID : goog.labs.userAgent.platform.isAndroid();
goog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_IPHONE : goog.labs.userAgent.platform.isIphone();
goog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_IPAD : goog.labs.userAgent.platform.isIpad();
goog.userAgent.IPOD = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_IPOD : goog.labs.userAgent.platform.isIpod();
goog.userAgent.IOS = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD || goog.userAgent.ASSUME_IPOD : goog.labs.userAgent.platform.isIos();
goog.userAgent.KAIOS = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_KAIOS : goog.labs.userAgent.platform.isKaiOS();
goog.userAgent.GO2PHONE = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_GO2PHONE : goog.labs.userAgent.platform.isGo2Phone();
goog.userAgent.determineVersion_ = function () {
var a = "",
b = goog.userAgent.getVersionRegexResult_();
b && (a = b ? b[1] : "");
return goog.userAgent.IE && (b = goog.userAgent.getDocumentMode_(), null != b && b > parseFloat(a)) ? String(b) : a;
};
goog.userAgent.getVersionRegexResult_ = function () {
var a = goog.userAgent.getUserAgentString();
if (goog.userAgent.GECKO) return /rv:([^\);]+)(\)|;)/.exec(a);
if (goog.userAgent.EDGE) return /Edge\/([\d\.]+)/.exec(a);
if (goog.userAgent.IE) return /\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(a);
if (goog.userAgent.WEBKIT) return /WebKit\/(\S+)/.exec(a);
if (goog.userAgent.OPERA) return /(?:Version)[ \/]?(\S+)/.exec(a);
};
goog.userAgent.getDocumentMode_ = function () {
var a = goog.global.document;
return a ? a.documentMode : void 0;
};
goog.userAgent.VERSION = goog.userAgent.determineVersion_();
goog.userAgent.compare = function (a, b) {
return goog.string.compareVersions(a, b);
};
goog.userAgent.isVersionOrHigherCache_ = {};
goog.userAgent.isVersionOrHigher = function (a) {
return goog.userAgent.ASSUME_ANY_VERSION || goog.reflect.cache(goog.userAgent.isVersionOrHigherCache_, a, function () {
return 0 <= goog.string.compareVersions(goog.userAgent.VERSION, a);
});
};
goog.userAgent.isVersion = goog.userAgent.isVersionOrHigher;
goog.userAgent.isDocumentModeOrHigher = function (a) {
return Number(goog.userAgent.DOCUMENT_MODE) >= a;
};
goog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher;
goog.userAgent.DOCUMENT_MODE = function () {
if (goog.global.document && goog.userAgent.IE) return goog.userAgent.getDocumentMode_();
}();
goog.userAgent.product = {};
goog.userAgent.product.ASSUME_FIREFOX = !1;
goog.userAgent.product.ASSUME_IPHONE = !1;
goog.userAgent.product.ASSUME_IPAD = !1;
goog.userAgent.product.ASSUME_ANDROID = !1;
goog.userAgent.product.ASSUME_CHROME = !1;
goog.userAgent.product.ASSUME_SAFARI = !1;
goog.userAgent.product.PRODUCT_KNOWN_ = goog.userAgent.ASSUME_IE || goog.userAgent.ASSUME_EDGE || goog.userAgent.ASSUME_OPERA || goog.userAgent.product.ASSUME_FIREFOX || goog.userAgent.product.ASSUME_IPHONE || goog.userAgent.product.ASSUME_IPAD || goog.userAgent.product.ASSUME_ANDROID || goog.userAgent.product.ASSUME_CHROME || goog.userAgent.product.ASSUME_SAFARI;
goog.userAgent.product.OPERA = goog.userAgent.OPERA;
goog.userAgent.product.IE = goog.userAgent.IE;
goog.userAgent.product.EDGE = goog.userAgent.EDGE;
goog.userAgent.product.FIREFOX = goog.userAgent.product.PRODUCT_KNOWN_ ? goog.userAgent.product.ASSUME_FIREFOX : goog.labs.userAgent.browser.isFirefox();
goog.userAgent.product.isIphoneOrIpod_ = function () {
return goog.labs.userAgent.platform.isIphone() || goog.labs.userAgent.platform.isIpod();
};
goog.userAgent.product.IPHONE = goog.userAgent.product.PRODUCT_KNOWN_ ? goog.userAgent.product.ASSUME_IPHONE : goog.userAgent.product.isIphoneOrIpod_();
goog.userAgent.product.IPAD = goog.userAgent.product.PRODUCT_KNOWN_ ? goog.userAgent.product.ASSUME_IPAD : goog.labs.userAgent.platform.isIpad();
goog.userAgent.product.ANDROID = goog.userAgent.product.PRODUCT_KNOWN_ ? goog.userAgent.product.ASSUME_ANDROID : goog.labs.userAgent.browser.isAndroidBrowser();
goog.userAgent.product.CHROME = goog.userAgent.product.PRODUCT_KNOWN_ ? goog.userAgent.product.ASSUME_CHROME : goog.labs.userAgent.browser.isChrome();
goog.userAgent.product.isSafariDesktop_ = function () {
return goog.labs.userAgent.browser.isSafari() && !goog.labs.userAgent.platform.isIos();
};
goog.userAgent.product.SAFARI = goog.userAgent.product.PRODUCT_KNOWN_ ? goog.userAgent.product.ASSUME_SAFARI : goog.userAgent.product.isSafariDesktop_();
goog.crypt.base64 = {};
goog.crypt.base64.DEFAULT_ALPHABET_COMMON_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
goog.crypt.base64.ENCODED_VALS = goog.crypt.base64.DEFAULT_ALPHABET_COMMON_ + "+/=";
goog.crypt.base64.ENCODED_VALS_WEBSAFE = goog.crypt.base64.DEFAULT_ALPHABET_COMMON_ + "-_.";
goog.crypt.base64.Alphabet = {
DEFAULT: 0,
NO_PADDING: 1,
WEBSAFE: 2,
WEBSAFE_DOT_PADDING: 3,
WEBSAFE_NO_PADDING: 4
};
goog.crypt.base64.paddingChars_ = "=.";
goog.crypt.base64.isPadding_ = function (a) {
return goog.string.contains(goog.crypt.base64.paddingChars_, a);
};
goog.crypt.base64.byteToCharMaps_ = {};
goog.crypt.base64.charToByteMap_ = null;
goog.crypt.base64.ASSUME_NATIVE_SUPPORT_ = goog.userAgent.GECKO || goog.userAgent.WEBKIT && !goog.userAgent.product.SAFARI || goog.userAgent.OPERA;
goog.crypt.base64.HAS_NATIVE_ENCODE_ = goog.crypt.base64.ASSUME_NATIVE_SUPPORT_ || "function" == typeof goog.global.btoa;
goog.crypt.base64.HAS_NATIVE_DECODE_ = goog.crypt.base64.ASSUME_NATIVE_SUPPORT_ || !goog.userAgent.product.SAFARI && !goog.userAgent.IE && "function" == typeof goog.global.atob;
goog.crypt.base64.encodeByteArray = function (a, b) {
goog.asserts.assert(goog.isArrayLike(a), "encodeByteArray takes an array as a parameter");
void 0 === b && (b = goog.crypt.base64.Alphabet.DEFAULT);
goog.crypt.base64.init_();
b = goog.crypt.base64.byteToCharMaps_[b];
for (var c = [], d = 0; d < a.length; d += 3) {
var e = a[d],
f = d + 1 < a.length,
g = f ? a[d + 1] : 0,
h = d + 2 < a.length,
k = h ? a[d + 2] : 0,
l = e >> 2;
e = (e & 3) << 4 | g >> 4;
g = (g & 15) << 2 | k >> 6;
k &= 63;
h || (k = 64, f || (g = 64));
c.push(b[l], b[e], b[g] || "", b[k] || "");
}
return c.join("");
};
goog.crypt.base64.encodeString = function (a, b) {
return goog.crypt.base64.HAS_NATIVE_ENCODE_ && !b ? goog.global.btoa(a) : goog.crypt.base64.encodeByteArray(goog.crypt.stringToByteArray(a), b);
};
goog.crypt.base64.decodeString = function (a, b) {
if (goog.crypt.base64.HAS_NATIVE_DECODE_ && !b) return goog.global.atob(a);
var c = "";
goog.crypt.base64.decodeStringInternal_(a, function (a) {
c += String.fromCharCode(a);
});
return c;
};
goog.crypt.base64.decodeStringToByteArray = function (a, b) {
var c = [];
goog.crypt.base64.decodeStringInternal_(a, function (a) {
c.push(a);
});
return c;
};
goog.crypt.base64.decodeStringToUint8Array = function (a) {
goog.asserts.assert(!goog.userAgent.IE || goog.userAgent.isVersionOrHigher("10"), "Browser does not support typed arrays");
var b = a.length,
c = 3 * b / 4;
c % 3 ? c = Math.floor(c) : goog.crypt.base64.isPadding_(a[b - 1]) && (c = goog.crypt.base64.isPadding_(a[b - 2]) ? c - 2 : c - 1);
var d = new Uint8Array(c),
e = 0;
goog.crypt.base64.decodeStringInternal_(a, function (a) {
d[e++] = a;
});
return d.subarray(0, e);
};
goog.crypt.base64.decodeStringInternal_ = function (a, b) {
function c(b) {
for (; d < a.length;) {
var c = a.charAt(d++),
e = goog.crypt.base64.charToByteMap_[c];
if (null != e) return e;
if (!goog.string.isEmptyOrWhitespace(c)) throw Error("Unknown base64 encoding at char: " + c);
}
return b;
}
goog.crypt.base64.init_();
for (var d = 0;;) {
var e = c(-1),
f = c(0),
g = c(64),
h = c(64);
if (64 === h && -1 === e) break;
b(e << 2 | f >> 4);
64 != g && (b(f << 4 & 240 | g >> 2), 64 != h && b(g << 6 & 192 | h));
}
};
goog.crypt.base64.init_ = function () {
if (!goog.crypt.base64.charToByteMap_) {
goog.crypt.base64.charToByteMap_ = {};
for (var a = goog.crypt.base64.DEFAULT_ALPHABET_COMMON_.split(""), b = ["+/=", "+/", "-_=", "-_.", "-_"], c = 0; 5 > c; c++) {
var d = a.concat(b[c].split(""));
goog.crypt.base64.byteToCharMaps_[c] = d;
for (var e = 0; e < d.length; e++) {
var f = d[e],
g = goog.crypt.base64.charToByteMap_[f];
void 0 === g ? goog.crypt.base64.charToByteMap_[f] = e : goog.asserts.assert(g === e);
}
}
}
};
jspb.utils = {};
jspb.utils.split64Low = 0;
jspb.utils.split64High = 0;
jspb.utils.splitUint64 = function (a) {
var b = a >>> 0;
a = Math.floor((a - b) / jspb.BinaryConstants.TWO_TO_32) >>> 0;
jspb.utils.split64Low = b;
jspb.utils.split64High = a;
};
jspb.utils.splitInt64 = function (a) {
var b = 0 > a;
a = Math.abs(a);
var c = a >>> 0;
a = Math.floor((a - c) / jspb.BinaryConstants.TWO_TO_32);
a >>>= 0;
b && (a = ~a >>> 0, c = (~c >>> 0) + 1, 4294967295 < c && (c = 0, a++, 4294967295 < a && (a = 0)));
jspb.utils.split64Low = c;
jspb.utils.split64High = a;
};
jspb.utils.splitZigzag64 = function (a) {
var b = 0 > a;
a = 2 * Math.abs(a);
jspb.utils.splitUint64(a);
a = jspb.utils.split64Low;
var c = jspb.utils.split64High;
b && (0 == a ? 0 == c ? c = a = 4294967295 : (c--, a = 4294967295) : a--);
jspb.utils.split64Low = a;
jspb.utils.split64High = c;
};
jspb.utils.splitFloat32 = function (a) {
var b = 0 > a ? 1 : 0;
a = b ? -a : a;
if (0 === a) 0 < 1 / a ? (jspb.utils.split64High = 0, jspb.utils.split64Low = 0) : (jspb.utils.split64High = 0, jspb.utils.split64Low = 2147483648);else if (isNaN(a)) jspb.utils.split64High = 0, jspb.utils.split64Low = 2147483647;else if (a > jspb.BinaryConstants.FLOAT32_MAX) jspb.utils.split64High = 0, jspb.utils.split64Low = (b << 31 | 2139095040) >>> 0;else if (a < jspb.BinaryConstants.FLOAT32_MIN) a = Math.round(a / Math.pow(2, -149)), jspb.utils.split64High = 0, jspb.utils.split64Low = (b << 31 | a) >>> 0;else {
var c = Math.floor(Math.log(a) / Math.LN2);
a *= Math.pow(2, -c);
a = Math.round(a * jspb.BinaryConstants.TWO_TO_23) & 8388607;
jspb.utils.split64High = 0;
jspb.utils.split64Low = (b << 31 | c + 127 << 23 | a) >>> 0;
}
};
jspb.utils.splitFloat64 = function (a) {
var b = 0 > a ? 1 : 0;
a = b ? -a : a;
if (0 === a) jspb.utils.split64High = 0 < 1 / a ? 0 : 2147483648, jspb.utils.split64Low = 0;else if (isNaN(a)) jspb.utils.split64High = 2147483647, jspb.utils.split64Low = 4294967295;else if (a > jspb.BinaryConstants.FLOAT64_MAX) jspb.utils.split64High = (b << 31 | 2146435072) >>> 0, jspb.utils.split64Low = 0;else if (a < jspb.BinaryConstants.FLOAT64_MIN) {
var c = a / Math.pow(2, -1074);
a = c / jspb.BinaryConstants.TWO_TO_32;
jspb.utils.split64High = (b << 31 | a) >>> 0;
jspb.utils.split64Low = c >>> 0;
} else {
c = a;
var d = 0;
if (2 <= c) for (; 2 <= c && 1023 > d;) d++, c /= 2;else for (; 1 > c && -1022 < d;) c *= 2, d--;
c = a * Math.pow(2, -d);
a = c * jspb.BinaryConstants.TWO_TO_20 & 1048575;
c = c * jspb.BinaryConstants.TWO_TO_52 >>> 0;
jspb.utils.split64High = (b << 31 | d + 1023 << 20 | a) >>> 0;
jspb.utils.split64Low = c;
}
};
jspb.utils.splitHash64 = function (a) {
var b = a.charCodeAt(0),
c = a.charCodeAt(1),
d = a.charCodeAt(2),
e = a.charCodeAt(3),
f = a.charCodeAt(4),
g = a.charCodeAt(5),
h = a.charCodeAt(6);
a = a.charCodeAt(7);
jspb.utils.split64Low = b + (c << 8) + (d << 16) + (e << 24) >>> 0;
jspb.utils.split64High = f + (g << 8) + (h << 16) + (a << 24) >>> 0;
};
jspb.utils.joinUint64 = function (a, b) {
return b * jspb.BinaryConstants.TWO_TO_32 + (a >>> 0);
};
jspb.utils.joinInt64 = function (a, b) {
var c = b & 2147483648;
c && (a = ~a + 1 >>> 0, b = ~b >>> 0, 0 == a && (b = b + 1 >>> 0));
a = jspb.utils.joinUint64(a, b);
return c ? -a : a;
};
jspb.utils.toZigzag64 = function (a, b, c) {
var d = b >> 31;
return c(a << 1 ^ d, (b << 1 | a >>> 31) ^ d);
};
jspb.utils.joinZigzag64 = function (a, b) {
return jspb.utils.fromZigzag64(a, b, jspb.utils.joinInt64);
};
jspb.utils.fromZigzag64 = function (a, b, c) {
var d = -(a & 1);
return c((a >>> 1 | b << 31) ^ d, b >>> 1 ^ d);
};
jspb.utils.joinFloat32 = function (a, b) {
b = 2 * (a >> 31) + 1;
var c = a >>> 23 & 255;
a &= 8388607;
return 255 == c ? a ? NaN : Infinity * b : 0 == c ? b * Math.pow(2, -149) * a : b * Math.pow(2, c - 150) * (a + Math.pow(2, 23));
};
jspb.utils.joinFloat64 = function (a, b) {
var c = 2 * (b >> 31) + 1,
d = b >>> 20 & 2047;
a = jspb.BinaryConstants.TWO_TO_32 * (b & 1048575) + a;
return 2047 == d ? a ? NaN : Infinity * c : 0 == d ? c * Math.pow(2, -1074) * a : c * Math.pow(2, d - 1075) * (a + jspb.BinaryConstants.TWO_TO_52);
};
jspb.utils.joinHash64 = function (a, b) {
return String.fromCharCode(a >>> 0 & 255, a >>> 8 & 255, a >>> 16 & 255, a >>> 24 & 255, b >>> 0 & 255, b >>> 8 & 255, b >>> 16 & 255, b >>> 24 & 255);
};
jspb.utils.DIGITS = "0123456789abcdef".split("");
jspb.utils.ZERO_CHAR_CODE_ = 48;
jspb.utils.A_CHAR_CODE_ = 97;
jspb.utils.joinUnsignedDecimalString = function (a, b) {
function c(a, b) {
a = a ? String(a) : "";
return b ? "0000000".slice(a.length) + a : a;
}
if (2097151 >= b) return "" + (jspb.BinaryConstants.TWO_TO_32 * b + a);
var d = (a >>> 24 | b << 8) >>> 0 & 16777215;
b = b >> 16 & 65535;
a = (a & 16777215) + 6777216 * d + 6710656 * b;
d += 8147497 * b;
b *= 2;
1E7 <= a && (d += Math.floor(a / 1E7), a %= 1E7);
1E7 <= d && (b += Math.floor(d / 1E7), d %= 1E7);
return c(b, 0) + c(d, b) + c(a, 1);
};
jspb.utils.joinSignedDecimalString = function (a, b) {
var c = b & 2147483648;
c && (a = ~a + 1 >>> 0, b = ~b + (0 == a ? 1 : 0) >>> 0);
a = jspb.utils.joinUnsignedDecimalString(a, b);
return c ? "-" + a : a;
};
jspb.utils.hash64ToDecimalString = function (a, b) {
jspb.utils.splitHash64(a);
a = jspb.utils.split64Low;
var c = jspb.utils.split64High;
return b ? jspb.utils.joinSignedDecimalString(a, c) : jspb.utils.joinUnsignedDecimalString(a, c);
};
jspb.utils.hash64ArrayToDecimalStrings = function (a, b) {
for (var c = Array(a.length), d = 0; d < a.length; d++) c[d] = jspb.utils.hash64ToDecimalString(a[d], b);
return c;
};
jspb.utils.decimalStringToHash64 = function (a) {
function b(a, b) {
for (var c = 0; 8 > c && (1 !== a || 0 < b); c++) b = a * e[c] + b, e[c] = b & 255, b >>>= 8;
}
function c() {
for (var a = 0; 8 > a; a++) e[a] = ~e[a] & 255;
}
goog.asserts.assert(0 < a.length);
var d = !1;
"-" === a[0] && (d = !0, a = a.slice(1));
for (var e = [0, 0, 0, 0, 0, 0, 0, 0], f = 0; f < a.length; f++) b(10, a.charCodeAt(f) - jspb.utils.ZERO_CHAR_CODE_);
d && (c(), b(1, 1));
return goog.crypt.byteArrayToString(e);
};
jspb.utils.splitDecimalString = function (a) {
jspb.utils.splitHash64(jspb.utils.decimalStringToHash64(a));
};
jspb.utils.toHexDigit_ = function (a) {
return String.fromCharCode(10 > a ? jspb.utils.ZERO_CHAR_CODE_ + a : jspb.utils.A_CHAR_CODE_ - 10 + a);
};
jspb.utils.fromHexCharCode_ = function (a) {
return a >= jspb.utils.A_CHAR_CODE_ ? a - jspb.utils.A_CHAR_CODE_ + 10 : a - jspb.utils.ZERO_CHAR_CODE_;
};
jspb.utils.hash64ToHexString = function (a) {
var b = Array(18);
b[0] = "0";
b[1] = "x";
for (var c = 0; 8 > c; c++) {
var d = a.charCodeAt(7 - c);
b[2 * c + 2] = jspb.utils.toHexDigit_(d >> 4);
b[2 * c + 3] = jspb.utils.toHexDigit_(d & 15);
}
return b.join("");
};
jspb.utils.hexStringToHash64 = function (a) {
a = a.toLowerCase();
goog.asserts.assert(18 == a.length);
goog.asserts.assert("0" == a[0]);
goog.asserts.assert("x" == a[1]);
for (var b = "", c = 0; 8 > c; c++) {
var d = jspb.utils.fromHexCharCode_(a.charCodeAt(2 * c + 2)),
e = jspb.utils.fromHexCharCode_(a.charCodeAt(2 * c + 3));
b = String.fromCharCode(16 * d + e) + b;
}
return b;
};
jspb.utils.hash64ToNumber = function (a, b) {
jspb.utils.splitHash64(a);
a = jspb.utils.split64Low;
var c = jspb.utils.split64High;
return b ? jspb.utils.joinInt64(a, c) : jspb.utils.joinUint64(a, c);
};
jspb.utils.numberToHash64 = function (a) {
jspb.utils.splitInt64(a);
return jspb.utils.joinHash64(jspb.utils.split64Low, jspb.utils.split64High);
};
jspb.utils.countVarints = function (a, b, c) {
for (var d = 0, e = b; e < c; e++) d += a[e] >> 7;
return c - b - d;
};
jspb.utils.countVarintFields = function (a, b, c, d) {
var e = 0;
d = 8 * d + jspb.BinaryConstants.WireType.VARINT;
if (128 > d) for (; b < c && a[b++] == d;) for (e++;;) {
var f = a[b++];
if (0 == (f & 128)) break;
} else for (; b < c;) {
for (f = d; 128 < f;) {
if (a[b] != (f & 127 | 128)) return e;
b++;
f >>= 7;
}
if (a[b++] != f) break;
for (e++; f = a[b++], 0 != (f & 128););
}
return e;
};
jspb.utils.countFixedFields_ = function (a, b, c, d, e) {
var f = 0;
if (128 > d) for (; b < c && a[b++] == d;) f++, b += e;else for (; b < c;) {
for (var g = d; 128 < g;) {
if (a[b++] != (g & 127 | 128)) return f;
g >>= 7;
}
if (a[b++] != g) break;
f++;
b += e;
}
return f;
};
jspb.utils.countFixed32Fields = function (a, b, c, d) {
return jspb.utils.countFixedFields_(a, b, c, 8 * d + jspb.BinaryConstants.WireType.FIXED32, 4);
};
jspb.utils.countFixed64Fields = function (a, b, c, d) {
return jspb.utils.countFixedFields_(a, b, c, 8 * d + jspb.BinaryConstants.WireType.FIXED64, 8);
};
jspb.utils.countDelimitedFields = function (a, b, c, d) {
var e = 0;
for (d = 8 * d + jspb.BinaryConstants.WireType.DELIMITED; b < c;) {
for (var f = d; 128 < f;) {
if (a[b++] != (f & 127 | 128)) return e;
f >>= 7;
}
if (a[b++] != f) break;
e++;
for (var g = 0, h = 1; f = a[b++], g += (f & 127) * h, h *= 128, 0 != (f & 128););
b += g;
}
return e;
};
jspb.utils.debugBytesToTextFormat = function (a) {
var b = '"';
if (a) {
a = jspb.utils.byteSourceToUint8Array(a);
for (var c = 0; c < a.length; c++) b += "\\x", 16 > a[c] && (b += "0"), b += a[c].toString(16);
}
return b + '"';
};
jspb.utils.debugScalarToTextFormat = function (a) {
return "string" === typeof a ? goog.string.quote(a) : a.toString();
};
jspb.utils.stringToByteArray = function (a) {
for (var b = new Uint8Array(a.length), c = 0; c < a.length; c++) {
var d = a.charCodeAt(c);
if (255 < d) throw Error("Conversion error: string contains codepoint outside of byte range");
b[c] = d;
}
return b;
};
jspb.utils.byteSourceToUint8Array = function (a) {
if (a.constructor === Uint8Array) return a;
if (a.constructor === ArrayBuffer || "undefined" != typeof Buffer && a.constructor === Buffer || a.constructor === Array) return new Uint8Array(a);
if (a.constructor === String) return goog.crypt.base64.decodeStringToUint8Array(a);
goog.asserts.fail("Type not convertible to Uint8Array.");
return new Uint8Array(0);
};
jspb.BinaryDecoder = function (a, b, c) {
this.bytes_ = null;
this.cursor_ = this.end_ = this.start_ = 0;
this.error_ = !1;
a && this.setBlock(a, b, c);
};
jspb.BinaryDecoder.instanceCache_ = [];
jspb.BinaryDecoder.alloc = function (a, b, c) {
if (jspb.BinaryDecoder.instanceCache_.length) {
var d = jspb.BinaryDecoder.instanceCache_.pop();
a && d.setBlock(a, b, c);
return d;
}
return new jspb.BinaryDecoder(a, b, c);
};
jspb.BinaryDecoder.prototype.free = function () {
this.clear();
100 > jspb.BinaryDecoder.instanceCache_.length && jspb.BinaryDecoder.instanceCache_.push(this);
};
jspb.BinaryDecoder.prototype.clone = function () {
return jspb.BinaryDecoder.alloc(this.bytes_, this.start_, this.end_ - this.start_);
};
jspb.BinaryDecoder.prototype.clear = function () {
this.bytes_ = null;
this.cursor_ = this.end_ = this.start_ = 0;
this.error_ = !1;
};
jspb.BinaryDecoder.prototype.getBuffer = function () {
return this.bytes_;
};
jspb.BinaryDecoder.prototype.setBlock = function (a, b, c) {
this.bytes_ = jspb.utils.byteSourceToUint8Array(a);
this.start_ = void 0 !== b ? b : 0;
this.end_ = void 0 !== c ? this.start_ + c : this.bytes_.length;
this.cursor_ = this.start_;
};
jspb.BinaryDecoder.prototype.getEnd = function () {
return this.end_;
};
jspb.BinaryDecoder.prototype.setEnd = function (a) {
this.end_ = a;
};
jspb.BinaryDecoder.prototype.reset = function () {
this.cursor_ = this.start_;
};
jspb.BinaryDecoder.prototype.getCursor = function () {
return this.cursor_;
};
jspb.BinaryDecoder.prototype.setCursor = function (a) {
this.cursor_ = a;
};
jspb.BinaryDecoder.prototype.advance = function (a) {
this.cursor_ += a;
goog.asserts.assert(this.cursor_ <= this.end_);
};
jspb.BinaryDecoder.prototype.atEnd = function () {
return this.cursor_ == this.end_;
};
jspb.BinaryDecoder.prototype.pastEnd = function () {
return this.cursor_ > this.end_;
};
jspb.BinaryDecoder.prototype.getError = function () {
return this.error_ || 0 > this.cursor_ || this.cursor_ > this.end_;
};
jspb.BinaryDecoder.prototype.readSplitVarint64 = function (a) {
for (var b = 128, c = 0, d = 0, e = 0; 4 > e && 128 <= b; e++) b = this.bytes_[this.cursor_++], c |= (b & 127) << 7 * e;
128 <= b && (b = this.bytes_[this.cursor_++], c |= (b & 127) << 28, d |= (b & 127) >> 4);
if (128 <= b) for (e = 0; 5 > e && 128 <= b; e++) b = this.bytes_[this.cursor_++], d |= (b & 127) << 7 * e + 3;
if (128 > b) return a(c >>> 0, d >>> 0);
goog.asserts.fail("Failed to read varint, encoding is invalid.");
this.error_ = !0;
};
jspb.BinaryDecoder.prototype.readSplitZigzagVarint64 = function (a) {
return this.readSplitVarint64(function (b, c) {
return jspb.utils.fromZigzag64(b, c, a);
});
};
jspb.BinaryDecoder.prototype.readSplitFixed64 = function (a) {
var b = this.bytes_,
c = this.cursor_;
this.cursor_ += 8;
for (var d = 0, e = 0, f = c + 7; f >= c; f--) d = d << 8 | b[f], e = e << 8 | b[f + 4];
return a(d, e);
};
jspb.BinaryDecoder.prototype.skipVarint = function () {
for (; this.bytes_[this.cursor_] & 128;) this.cursor_++;
this.cursor_++;
};
jspb.BinaryDecoder.prototype.unskipVarint = function (a) {
for (; 128 < a;) this.cursor_--, a >>>= 7;
this.cursor_--;
};
jspb.BinaryDecoder.prototype.readUnsignedVarint32 = function () {
var a = this.bytes_;
var b = a[this.cursor_ + 0];
var c = b & 127;
if (128 > b) return this.cursor_ += 1, goog.asserts.assert(this.cursor_ <= this.end_), c;
b = a[this.cursor_ + 1];
c |= (b & 127) << 7;
if (128 > b) return this.cursor_ += 2, goog.asserts.assert(this.cursor_ <= this.end_), c;
b = a[this.cursor_ + 2];
c |= (b & 127) << 14;
if (128 > b) return this.cursor_ += 3, goog.asserts.assert(this.cursor_ <= this.end_), c;
b = a[this.cursor_ + 3];
c |= (b & 127) << 21;
if (128 > b) return this.cursor_ += 4, goog.asserts.assert(this.cursor_ <= this.end_), c;
b = a[this.cursor_ + 4];
c |= (b & 15) << 28;
if (128 > b) return this.cursor_ += 5, goog.asserts.assert(this.cursor_ <= this.end_), c >>> 0;
this.cursor_ += 5;
128 <= a[this.cursor_++] && 128 <= a[this.cursor_++] && 128 <= a[this.cursor_++] && 128 <= a[this.cursor_++] && 128 <= a[this.cursor_++] && goog.asserts.assert(!1);
goog.asserts.assert(this.cursor_ <= this.end_);
return c;
};
jspb.BinaryDecoder.prototype.readSignedVarint32 = jspb.BinaryDecoder.prototype.readUnsignedVarint32;
jspb.BinaryDecoder.prototype.readUnsignedVarint32String = function () {
return this.readUnsignedVarint32().toString();
};
jspb.BinaryDecoder.prototype.readSignedVarint32String = function () {
return this.readSignedVarint32().toString();
};
jspb.BinaryDecoder.prototype.readZigzagVarint32 = function () {
var a = this.readUnsignedVarint32();
return a >>> 1 ^ -(a & 1);
};
jspb.BinaryDecoder.prototype.readUnsignedVarint64 = function () {
return this.readSplitVarint64(jspb.utils.joinUint64);
};
jspb.BinaryDecoder.prototype.readUnsignedVarint64String = function () {
return this.readSplitVarint64(jspb.utils.joinUnsignedDecimalString);
};
jspb.BinaryDecoder.prototype.readSignedVarint64 = function () {
return this.readSplitVarint64(jspb.utils.joinInt64);
};
jspb.BinaryDecoder.prototype.readSignedVarint64String = function () {
return this.readSplitVarint64(jspb.utils.joinSignedDecimalString);
};
jspb.BinaryDecoder.prototype.readZigzagVarint64 = function () {
return this.readSplitVarint64(jspb.utils.joinZigzag64);
};
jspb.BinaryDecoder.prototype.readZigzagVarintHash64 = function () {
return this.readSplitZigzagVarint64(jspb.utils.joinHash64);
};
jspb.BinaryDecoder.prototype.readZigzagVarint64String = function () {
return this.readSplitZigzagVarint64(jspb.utils.joinSignedDecimalString);
};
jspb.BinaryDecoder.prototype.readUint8 = function () {
var a = this.bytes_[this.cursor_ + 0];
this.cursor_ += 1;
goog.asserts.assert(this.cursor_ <= this.end_);
return a;
};
jspb.BinaryDecoder.prototype.readUint16 = function () {
var a = this.bytes_[this.cursor_ + 0],
b = this.bytes_[this.cursor_ + 1];
this.cursor_ += 2;
goog.asserts.assert(this.cursor_ <= this.end_);
return a << 0 | b << 8;
};
jspb.BinaryDecoder.prototype.readUint32 = function () {
var a = this.bytes_[this.cursor_ + 0],
b = this.bytes_[this.cursor_ + 1],
c = this.bytes_[this.cursor_ + 2],
d = this.bytes_[this.cursor_ + 3];
this.cursor_ += 4;
goog.asserts.assert(this.cursor_ <= this.end_);
return (a << 0 | b << 8 | c << 16 | d << 24) >>> 0;
};
jspb.BinaryDecoder.prototype.readUint64 = function () {
var a = this.readUint32(),
b = this.readUint32();
return jspb.utils.joinUint64(a, b);
};
jspb.BinaryDecoder.prototype.readUint64String = function () {
var a = this.readUint32(),
b = this.readUint32();
return jspb.utils.joinUnsignedDecimalString(a, b);
};
jspb.BinaryDecoder.prototype.readInt8 = function () {
var a = this.bytes_[this.cursor_ + 0];
this.cursor_ += 1;
goog.asserts.assert(this.cursor_ <= this.end_);
return a << 24 >> 24;
};
jspb.BinaryDecoder.prototype.readInt16 = function () {
var a = this.bytes_[this.cursor_ + 0],
b = this.bytes_[this.cursor_ + 1];
this.cursor_ += 2;
goog.asserts.assert(this.cursor_ <= this.end_);
return (a << 0 | b << 8) << 16 >> 16;
};
jspb.BinaryDecoder.prototype.readInt32 = function () {
var a = this.bytes_[this.cursor_ + 0],
b = this.bytes_[this.cursor_ + 1],
c = this.bytes_[this.cursor_ + 2],
d = this.bytes_[this.cursor_ + 3];
this.cursor_ += 4;
goog.asserts.assert(this.cursor_ <= this.end_);
return a << 0 | b << 8 | c << 16 | d << 24;
};
jspb.BinaryDecoder.prototype.readInt64 = function () {
var a = this.readUint32(),
b = this.readUint32();
return jspb.utils.joinInt64(a, b);
};
jspb.BinaryDecoder.prototype.readInt64String = function () {
var a = this.readUint32(),
b = this.readUint32();
return jspb.utils.joinSignedDecimalString(a, b);
};
jspb.BinaryDecoder.prototype.readFloat = function () {
var a = this.readUint32();
return jspb.utils.joinFloat32(a, 0);
};
jspb.BinaryDecoder.prototype.readDouble = function () {
var a = this.readUint32(),
b = this.readUint32();
return jspb.utils.joinFloat64(a, b);
};
jspb.BinaryDecoder.prototype.readBool = function () {
return !!this.bytes_[this.cursor_++];
};
jspb.BinaryDecoder.prototype.readEnum = function () {
return this.readSignedVarint32();
};
jspb.BinaryDecoder.prototype.readString = function (a) {
var b = this.bytes_,
c = this.cursor_;
a = c + a;
for (var d = [], e = ""; c < a;) {
var f = b[c++];
if (128 > f) d.push(f);else if (192 > f) continue;else if (224 > f) {
var g = b[c++];
d.push((f & 31) << 6 | g & 63);
} else if (240 > f) {
g = b[c++];
var h = b[c++];
d.push((f & 15) << 12 | (g & 63) << 6 | h & 63);
} else if (248 > f) {
g = b[c++];
h = b[c++];
var k = b[c++];
f = (f & 7) << 18 | (g & 63) << 12 | (h & 63) << 6 | k & 63;
f -= 65536;
d.push((f >> 10 & 1023) + 55296, (f & 1023) + 56320);
}
8192 <= d.length && (e += String.fromCharCode.apply(null, d), d.length = 0);
}
e += goog.crypt.byteArrayToString(d);
this.cursor_ = c;
return e;
};
jspb.BinaryDecoder.prototype.readStringWithLength = function () {
var a = this.readUnsignedVarint32();
return this.readString(a);
};
jspb.BinaryDecoder.prototype.readBytes = function (a) {
if (0 > a || this.cursor_ + a > this.bytes_.length) return this.error_ = !0, goog.asserts.fail("Invalid byte length!"), new Uint8Array(0);
var b = this.bytes_.subarray(this.cursor_, this.cursor_ + a);
this.cursor_ += a;
goog.asserts.assert(this.cursor_ <= this.end_);
return b;
};
jspb.BinaryDecoder.prototype.readVarintHash64 = function () {
return this.readSplitVarint64(jspb.utils.joinHash64);
};
jspb.BinaryDecoder.prototype.readFixedHash64 = function () {
var a = this.bytes_,
b = this.cursor_,
c = a[b + 0],
d = a[b + 1],
e = a[b + 2],
f = a[b + 3],
g = a[b + 4],
h = a[b + 5],
k = a[b + 6];
a = a[b + 7];
this.cursor_ += 8;
return String.fromCharCode(c, d, e, f, g, h, k, a);
};
jspb.BinaryReader = function (a, b, c) {
this.decoder_ = jspb.BinaryDecoder.alloc(a, b, c);
this.fieldCursor_ = this.decoder_.getCursor();
this.nextField_ = jspb.BinaryConstants.INVALID_FIELD_NUMBER;
this.nextWireType_ = jspb.BinaryConstants.WireType.INVALID;
this.error_ = !1;
this.readCallbacks_ = null;
};
jspb.BinaryReader.instanceCache_ = [];
jspb.BinaryReader.alloc = function (a, b, c) {
if (jspb.BinaryReader.instanceCache_.length) {
var d = jspb.BinaryReader.instanceCache_.pop();
a && d.decoder_.setBlock(a, b, c);
return d;
}
return new jspb.BinaryReader(a, b, c);
};
jspb.BinaryReader.prototype.alloc = jspb.BinaryReader.alloc;
jspb.BinaryReader.prototype.free = function () {
this.decoder_.clear();
this.nextField_ = jspb.BinaryConstants.INVALID_FIELD_NUMBER;
this.nextWireType_ = jspb.BinaryConstants.WireType.INVALID;
this.error_ = !1;
this.readCallbacks_ = null;
100 > jspb.BinaryReader.instanceCache_.length && jspb.BinaryReader.instanceCache_.push(this);
};
jspb.BinaryReader.prototype.getFieldCursor = function () {
return this.fieldCursor_;
};
jspb.BinaryReader.prototype.getCursor = function () {
return this.decoder_.getCursor();
};
jspb.BinaryReader.prototype.getBuffer = function () {
return this.decoder_.getBuffer();
};
jspb.BinaryReader.prototype.getFieldNumber = function () {
return this.nextField_;
};
jspb.BinaryReader.prototype.getWireType = function () {
return this.nextWireType_;
};
jspb.BinaryReader.prototype.isEndGroup = function () {
return this.nextWireType_ == jspb.BinaryConstants.WireType.END_GROUP;
};
jspb.BinaryReader.prototype.getError = function () {
return this.error_ || this.decoder_.getError();
};
jspb.BinaryReader.prototype.setBlock = function (a, b, c) {
this.decoder_.setBlock(a, b, c);
this.nextField_ = jspb.BinaryConstants.INVALID_FIELD_NUMBER;
this.nextWireType_ = jspb.BinaryConstants.WireType.INVALID;
};
jspb.BinaryReader.prototype.reset = function () {
this.decoder_.reset();
this.nextField_ = jspb.BinaryConstants.INVALID_FIELD_NUMBER;
this.nextWireType_ = jspb.BinaryConstants.WireType.INVALID;
};
jspb.BinaryReader.prototype.advance = function (a) {
this.decoder_.advance(a);
};
jspb.BinaryReader.prototype.nextField = function () {
if (this.decoder_.atEnd()) return !1;
if (this.getError()) return goog.asserts.fail("Decoder hit an error"), !1;
this.fieldCursor_ = this.decoder_.getCursor();
var a = this.decoder_.readUnsignedVarint32(),
b = a >>> 3;
a &= 7;
if (a != jspb.BinaryConstants.WireType.VARINT && a != jspb.BinaryConstants.WireType.FIXED32 && a != jspb.BinaryConstants.WireType.FIXED64 && a != jspb.BinaryConstants.WireType.DELIMITED && a != jspb.BinaryConstants.WireType.START_GROUP && a != jspb.BinaryConstants.WireType.END_GROUP) return goog.asserts.fail("Invalid wire type: %s (at position %s)", a, this.fieldCursor_), this.error_ = !0, !1;
this.nextField_ = b;
this.nextWireType_ = a;
return !0;
};
jspb.BinaryReader.prototype.unskipHeader = function () {
this.decoder_.unskipVarint(this.nextField_ << 3 | this.nextWireType_);
};
jspb.BinaryReader.prototype.skipMatchingFields = function () {
var a = this.nextField_;
for (this.unskipHeader(); this.nextField() && this.getFieldNumber() == a;) this.skipField();
this.decoder_.atEnd() || this.unskipHeader();
};
jspb.BinaryReader.prototype.skipVarintField = function () {
this.nextWireType_ != jspb.BinaryConstants.WireType.VARINT ? (goog.asserts.fail("Invalid wire type for skipVarintField"), this.skipField()) : this.decoder_.skipVarint();
};
jspb.BinaryReader.prototype.skipDelimitedField = function () {
if (this.nextWireType_ != jspb.BinaryConstants.WireType.DELIMITED) goog.asserts.fail("Invalid wire type for skipDelimitedField"), this.skipField();else {
var a = this.decoder_.readUnsignedVarint32();
this.decoder_.advance(a);
}
};
jspb.BinaryReader.prototype.skipFixed32Field = function () {
this.nextWireType_ != jspb.BinaryConstants.WireType.FIXED32 ? (goog.asserts.fail("Invalid wire type for skipFixed32Field"), this.skipField()) : this.decoder_.advance(4);
};
jspb.BinaryReader.prototype.skipFixed64Field = function () {
this.nextWireType_ != jspb.BinaryConstants.WireType.FIXED64 ? (goog.asserts.fail("Invalid wire type for skipFixed64Field"), this.skipField()) : this.decoder_.advance(8);
};
jspb.BinaryReader.prototype.skipGroup = function () {
var a = this.nextField_;
do {
if (!this.nextField()) {
goog.asserts.fail("Unmatched start-group tag: stream EOF");
this.error_ = !0;
break;
}
if (this.nextWireType_ == jspb.BinaryConstants.WireType.END_GROUP) {
this.nextField_ != a && (goog.asserts.fail("Unmatched end-group tag"), this.error_ = !0);
break;
}
this.skipField();
} while (1);
};
jspb.BinaryReader.prototype.skipField = function () {
switch (this.nextWireType_) {
case jspb.BinaryConstants.WireType.VARINT:
this.skipVarintField();
break;
case jspb.BinaryConstants.WireType.FIXED64:
this.skipFixed64Field();
break;
case jspb.BinaryConstants.WireType.DELIMITED:
this.skipDelimitedField();
break;
case jspb.BinaryConstants.WireType.FIXED32:
this.skipFixed32Field();
break;
case jspb.BinaryConstants.WireType.START_GROUP:
this.skipGroup();
break;
default:
goog.asserts.fail("Invalid wire encoding for field.");
}
};
jspb.BinaryReader.prototype.registerReadCallback = function (a, b) {
null === this.readCallbacks_ && (this.readCallbacks_ = {});
goog.asserts.assert(!this.readCallbacks_[a]);
this.readCallbacks_[a] = b;
};
jspb.BinaryReader.prototype.runReadCallback = function (a) {
goog.asserts.assert(null !== this.readCallbacks_);
a = this.readCallbacks_[a];
goog.asserts.assert(a);
return a(this);
};
jspb.BinaryReader.prototype.readAny = function (a) {
this.nextWireType_ = jspb.BinaryConstants.FieldTypeToWireType(a);
var b = jspb.BinaryConstants.FieldType;
switch (a) {
case b.DOUBLE:
return this.readDouble();
case b.FLOAT:
return this.readFloat();
case b.INT64:
return this.readInt64();
case b.UINT64:
return this.readUint64();
case b.INT32:
return this.readInt32();
case b.FIXED64:
return this.readFixed64();
case b.FIXED32:
return this.readFixed32();
case b.BOOL:
return this.readBool();
case b.STRING:
return this.readString();
case b.GROUP:
goog.asserts.fail("Group field type not supported in readAny()");
case b.MESSAGE:
goog.asserts.fail("Message field type not supported in readAny()");
case b.BYTES:
return this.readBytes();
case b.UINT32:
return this.readUint32();
case b.ENUM:
return this.readEnum();
case b.SFIXED32:
return this.readSfixed32();
case b.SFIXED64:
return this.readSfixed64();
case b.SINT32:
return this.readSint32();
case b.SINT64:
return this.readSint64();
case b.FHASH64:
return this.readFixedHash64();
case b.VHASH64:
return this.readVarintHash64();
default:
goog.asserts.fail("Invalid field type in readAny()");
}
return 0;
};
jspb.BinaryReader.prototype.readMessage = function (a, b) {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.DELIMITED);
var c = this.decoder_.getEnd(),
d = this.decoder_.readUnsignedVarint32();
d = this.decoder_.getCursor() + d;
this.decoder_.setEnd(d);
b(a, this);
this.decoder_.setCursor(d);
this.decoder_.setEnd(c);
};
jspb.BinaryReader.prototype.readGroup = function (a, b, c) {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.START_GROUP);
goog.asserts.assert(this.nextField_ == a);
c(b, this);
this.error_ || this.nextWireType_ == jspb.BinaryConstants.WireType.END_GROUP || (goog.asserts.fail("Group submessage did not end with an END_GROUP tag"), this.error_ = !0);
};
jspb.BinaryReader.prototype.getFieldDecoder = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.DELIMITED);
var a = this.decoder_.readUnsignedVarint32(),
b = this.decoder_.getCursor(),
c = b + a;
a = jspb.BinaryDecoder.alloc(this.decoder_.getBuffer(), b, a);
this.decoder_.setCursor(c);
return a;
};
jspb.BinaryReader.prototype.readInt32 = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readSignedVarint32();
};
jspb.BinaryReader.prototype.readInt32String = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readSignedVarint32String();
};
jspb.BinaryReader.prototype.readInt64 = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readSignedVarint64();
};
jspb.BinaryReader.prototype.readInt64String = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readSignedVarint64String();
};
jspb.BinaryReader.prototype.readUint32 = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readUnsignedVarint32();
};
jspb.BinaryReader.prototype.readUint32String = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readUnsignedVarint32String();
};
jspb.BinaryReader.prototype.readUint64 = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readUnsignedVarint64();
};
jspb.BinaryReader.prototype.readUint64String = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readUnsignedVarint64String();
};
jspb.BinaryReader.prototype.readSint32 = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readZigzagVarint32();
};
jspb.BinaryReader.prototype.readSint64 = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readZigzagVarint64();
};
jspb.BinaryReader.prototype.readSint64String = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readZigzagVarint64String();
};
jspb.BinaryReader.prototype.readFixed32 = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED32);
return this.decoder_.readUint32();
};
jspb.BinaryReader.prototype.readFixed64 = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64);
return this.decoder_.readUint64();
};
jspb.BinaryReader.prototype.readFixed64String = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64);
return this.decoder_.readUint64String();
};
jspb.BinaryReader.prototype.readSfixed32 = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED32);
return this.decoder_.readInt32();
};
jspb.BinaryReader.prototype.readSfixed32String = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED32);
return this.decoder_.readInt32().toString();
};
jspb.BinaryReader.prototype.readSfixed64 = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64);
return this.decoder_.readInt64();
};
jspb.BinaryReader.prototype.readSfixed64String = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64);
return this.decoder_.readInt64String();
};
jspb.BinaryReader.prototype.readFloat = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED32);
return this.decoder_.readFloat();
};
jspb.BinaryReader.prototype.readDouble = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64);
return this.decoder_.readDouble();
};
jspb.BinaryReader.prototype.readBool = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return !!this.decoder_.readUnsignedVarint32();
};
jspb.BinaryReader.prototype.readEnum = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readSignedVarint64();
};
jspb.BinaryReader.prototype.readString = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.DELIMITED);
var a = this.decoder_.readUnsignedVarint32();
return this.decoder_.readString(a);
};
jspb.BinaryReader.prototype.readBytes = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.DELIMITED);
var a = this.decoder_.readUnsignedVarint32();
return this.decoder_.readBytes(a);
};
jspb.BinaryReader.prototype.readVarintHash64 = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readVarintHash64();
};
jspb.BinaryReader.prototype.readSintHash64 = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readZigzagVarintHash64();
};
jspb.BinaryReader.prototype.readSplitVarint64 = function (a) {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readSplitVarint64(a);
};
jspb.BinaryReader.prototype.readSplitZigzagVarint64 = function (a) {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT);
return this.decoder_.readSplitVarint64(function (b, c) {
return jspb.utils.fromZigzag64(b, c, a);
});
};
jspb.BinaryReader.prototype.readFixedHash64 = function () {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64);
return this.decoder_.readFixedHash64();
};
jspb.BinaryReader.prototype.readSplitFixed64 = function (a) {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64);
return this.decoder_.readSplitFixed64(a);
};
jspb.BinaryReader.prototype.readPackedField_ = function (a) {
goog.asserts.assert(this.nextWireType_ == jspb.BinaryConstants.WireType.DELIMITED);
var b = this.decoder_.readUnsignedVarint32();
b = this.decoder_.getCursor() + b;
for (var c = []; this.decoder_.getCursor() < b;) c.push(a.call(this.decoder_));
return c;
};
jspb.BinaryReader.prototype.readPackedInt32 = function () {
return this.readPackedField_(this.decoder_.readSignedVarint32);
};
jspb.BinaryReader.prototype.readPackedInt32String = function () {
return this.readPackedField_(this.decoder_.readSignedVarint32String);
};
jspb.BinaryReader.prototype.readPackedInt64 = function () {
return this.readPackedField_(this.decoder_.readSignedVarint64);
};
jspb.BinaryReader.prototype.readPackedInt64String = function () {
return this.readPackedField_(this.decoder_.readSignedVarint64String);
};
jspb.BinaryReader.prototype.readPackedUint32 = function () {
return this.readPackedField_(this.decoder_.readUnsignedVarint32);
};
jspb.BinaryReader.prototype.readPackedUint32String = function () {
return this.readPackedField_(this.decoder_.readUnsignedVarint32String);
};
jspb.BinaryReader.prototype.readPackedUint64 = function () {
return this.readPackedField_(this.decoder_.readUnsignedVarint64);
};
jspb.BinaryReader.prototype.readPackedUint64String = function () {
return this.readPackedField_(this.decoder_.readUnsignedVarint64String);
};
jspb.BinaryReader.prototype.readPackedSint32 = function () {
return this.readPackedField_(this.decoder_.readZigzagVarint32);
};
jspb.BinaryReader.prototype.readPackedSint64 = function () {
return this.readPackedField_(this.decoder_.readZigzagVarint64);
};
jspb.BinaryReader.prototype.readPackedSint64String = function () {
return this.readPackedField_(this.decoder_.readZigzagVarint64String);
};
jspb.BinaryReader.prototype.readPackedFixed32 = function () {
return this.readPackedField_(this.decoder_.readUint32);
};
jspb.BinaryReader.prototype.readPackedFixed64 = function () {
return this.readPackedField_(this.decoder_.readUint64);
};
jspb.BinaryReader.prototype.readPackedFixed64String = function () {
return this.readPackedField_(this.decoder_.readUint64String);
};
jspb.BinaryReader.prototype.readPackedSfixed32 = function () {
return this.readPackedField_(this.decoder_.readInt32);
};
jspb.BinaryReader.prototype.readPackedSfixed64 = function () {
return this.readPackedField_(this.decoder_.readInt64);
};
jspb.BinaryReader.prototype.readPackedSfixed64String = function () {
return this.readPackedField_(this.decoder_.readInt64String);
};
jspb.BinaryReader.prototype.readPackedFloat = function () {
return this.readPackedField_(this.decoder_.readFloat);
};
jspb.BinaryReader.prototype.readPackedDouble = function () {
return this.readPackedField_(this.decoder_.readDouble);
};
jspb.BinaryReader.prototype.readPackedBool = function () {
return this.readPackedField_(this.decoder_.readBool);
};
jspb.BinaryReader.prototype.readPackedEnum = function () {
return this.readPackedField_(this.decoder_.readEnum);
};
jspb.BinaryReader.prototype.readPackedVarintHash64 = function () {
return this.readPackedField_(this.decoder_.readVarintHash64);
};
jspb.BinaryReader.prototype.readPackedFixedHash64 = function () {
return this.readPackedField_(this.decoder_.readFixedHash64);
};
jspb.Map = function (a, b) {
this.arr_ = a;
this.valueCtor_ = b;
this.map_ = {};
this.arrClean = !0;
0 < this.arr_.length && this.loadFromArray_();
};
jspb.Map.prototype.loadFromArray_ = function () {
for (var a = 0; a < this.arr_.length; a++) {
var b = this.arr_[a],
c = b[0];
this.map_[c.toString()] = new jspb.Map.Entry_(c, b[1]);
}
this.arrClean = !0;
};
jspb.Map.prototype.toArray = function () {
if (this.arrClean) {
if (this.valueCtor_) {
var a = this.map_,
b;
for (b in a) if (Object.prototype.hasOwnProperty.call(a, b)) {
var c = a[b].valueWrapper;
c && c.toArray();
}
}
} else {
this.arr_.length = 0;
a = this.stringKeys_();
a.sort();
for (b = 0; b < a.length; b++) {
var d = this.map_[a[b]];
(c = d.valueWrapper) && c.toArray();
this.arr_.push([d.key, d.value]);
}
this.arrClean = !0;
}
return this.arr_;
};
jspb.Map.prototype.toObject = function (a, b) {
for (var c = this.toArray(), d = [], e = 0; e < c.length; e++) {
var f = this.map_[c[e][0].toString()];
this.wrapEntry_(f);
var g = f.valueWrapper;
g ? (goog.asserts.assert(b), d.push([f.key, b(a, g)])) : d.push([f.key, f.value]);
}
return d;
};
jspb.Map.fromObject = function (a, b, c) {
b = new jspb.Map([], b);
for (var d = 0; d < a.length; d++) {
var e = a[d][0],
f = c(a[d][1]);
b.set(e, f);
}
return b;
};
jspb.Map.ArrayIteratorIterable_ = function (a) {
this.idx_ = 0;
this.arr_ = a;
};
jspb.Map.ArrayIteratorIterable_.prototype.next = function () {
return this.idx_ < this.arr_.length ? {
done: !1,
value: this.arr_[this.idx_++]
} : {
done: !0,
value: void 0
};
};
"undefined" != typeof Symbol && (jspb.Map.ArrayIteratorIterable_.prototype[Symbol.iterator] = function () {
return this;
});
jspb.Map.prototype.getLength = function () {
return this.stringKeys_().length;
};
jspb.Map.prototype.clear = function () {
this.map_ = {};
this.arrClean = !1;
};
jspb.Map.prototype.del = function (a) {
a = a.toString();
var b = this.map_.hasOwnProperty(a);
delete this.map_[a];
this.arrClean = !1;
return b;
};
jspb.Map.prototype.getEntryList = function () {
var a = [],
b = this.stringKeys_();
b.sort();
for (var c = 0; c < b.length; c++) {
var d = this.map_[b[c]];
a.push([d.key, d.value]);
}
return a;
};
jspb.Map.prototype.entries = function () {
var a = [],
b = this.stringKeys_();
b.sort();
for (var c = 0; c < b.length; c++) {
var d = this.map_[b[c]];
a.push([d.key, this.wrapEntry_(d)]);
}
return new jspb.Map.ArrayIteratorIterable_(a);
};
jspb.Map.prototype.keys = function () {
var a = [],
b = this.stringKeys_();
b.sort();
for (var c = 0; c < b.length; c++) a.push(this.map_[b[c]].key);
return new jspb.Map.ArrayIteratorIterable_(a);
};
jspb.Map.prototype.values = function () {
var a = [],
b = this.stringKeys_();
b.sort();
for (var c = 0; c < b.length; c++) a.push(this.wrapEntry_(this.map_[b[c]]));
return new jspb.Map.ArrayIteratorIterable_(a);
};
jspb.Map.prototype.forEach = function (a, b) {
var c = this.stringKeys_();
c.sort();
for (var d = 0; d < c.length; d++) {
var e = this.map_[c[d]];
a.call(b, this.wrapEntry_(e), e.key, this);
}
};
jspb.Map.prototype.set = function (a, b) {
var c = new jspb.Map.Entry_(a);
this.valueCtor_ ? (c.valueWrapper = b, c.value = b.toArray()) : c.value = b;
this.map_[a.toString()] = c;
this.arrClean = !1;
return this;
};
jspb.Map.prototype.wrapEntry_ = function (a) {
return this.valueCtor_ ? (a.valueWrapper || (a.valueWrapper = new this.valueCtor_(a.value)), a.valueWrapper) : a.value;
};
jspb.Map.prototype.get = function (a) {
if (a = this.map_[a.toString()]) return this.wrapEntry_(a);
};
jspb.Map.prototype.has = function (a) {
return a.toString() in this.map_;
};
jspb.Map.prototype.serializeBinary = function (a, b, c, d, e) {
var f = this.stringKeys_();
f.sort();
for (var g = 0; g < f.length; g++) {
var h = this.map_[f[g]];
b.beginSubMessage(a);
c.call(b, 1, h.key);
this.valueCtor_ ? d.call(b, 2, this.wrapEntry_(h), e) : d.call(b, 2, h.value);
b.endSubMessage();
}
};
jspb.Map.deserializeBinary = function (a, b, c, d, e, f, g) {
for (; b.nextField() && !b.isEndGroup();) {
var h = b.getFieldNumber();
1 == h ? f = c.call(b) : 2 == h && (a.valueCtor_ ? (goog.asserts.assert(e), g || (g = new a.valueCtor_()), d.call(b, g, e)) : g = d.call(b));
}
goog.asserts.assert(void 0 != f);
goog.asserts.assert(void 0 != g);
a.set(f, g);
};
jspb.Map.prototype.stringKeys_ = function () {
var a = this.map_,
b = [],
c;
for (c in a) Object.prototype.hasOwnProperty.call(a, c) && b.push(c);
return b;
};
jspb.Map.Entry_ = function (a, b) {
this.key = a;
this.value = b;
this.valueWrapper = void 0;
};
jspb.ExtensionFieldInfo = function (a, b, c, d, e) {
this.fieldIndex = a;
this.fieldName = b;
this.ctor = c;
this.toObjectFn = d;
this.isRepeated = e;
};
jspb.ExtensionFieldBinaryInfo = function (a, b, c, d, e, f) {
this.fieldInfo = a;
this.binaryReaderFn = b;
this.binaryWriterFn = c;
this.binaryMessageSerializeFn = d;
this.binaryMessageDeserializeFn = e;
this.isPacked = f;
};
jspb.ExtensionFieldInfo.prototype.isMessageType = function () {
return !!this.ctor;
};
jspb.Message = function () {};
jspb.Message.GENERATE_TO_OBJECT = !0;
jspb.Message.GENERATE_FROM_OBJECT = !goog.DISALLOW_TEST_ONLY_CODE;
jspb.Message.GENERATE_TO_STRING = !0;
jspb.Message.ASSUME_LOCAL_ARRAYS = !1;
jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS = !0;
jspb.Message.SUPPORTS_UINT8ARRAY_ = "function" == typeof Uint8Array;
jspb.Message.prototype.getJsPbMessageId = function () {
return this.messageId_;
};
jspb.Message.getIndex_ = function (a, b) {
return b + a.arrayIndexOffset_;
};
jspb.Message.hiddenES6Property_ = function () {};
jspb.Message.getFieldNumber_ = function (a, b) {
return b - a.arrayIndexOffset_;
};
jspb.Message.initialize = function (a, b, c, d, e, f) {
a.wrappers_ = null;
b || (b = c ? [c] : []);
a.messageId_ = c ? String(c) : void 0;
a.arrayIndexOffset_ = 0 === c ? -1 : 0;
a.array = b;
jspb.Message.initPivotAndExtensionObject_(a, d);
a.convertedPrimitiveFields_ = {};
jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS || (a.repeatedFields = e);
if (e) for (b = 0; b < e.length; b++) c = e[b], c < a.pivot_ ? (c = jspb.Message.getIndex_(a, c), a.array[c] = a.array[c] || jspb.Message.EMPTY_LIST_SENTINEL_) : (jspb.Message.maybeInitEmptyExtensionObject_(a), a.extensionObject_[c] = a.extensionObject_[c] || jspb.Message.EMPTY_LIST_SENTINEL_);
if (f && f.length) for (b = 0; b < f.length; b++) jspb.Message.computeOneofCase(a, f[b]);
};
jspb.Message.EMPTY_LIST_SENTINEL_ = goog.DEBUG && Object.freeze ? Object.freeze([]) : [];
jspb.Message.isArray_ = function (a) {
return jspb.Message.ASSUME_LOCAL_ARRAYS ? a instanceof Array : goog.isArray(a);
};
jspb.Message.isExtensionObject_ = function (a) {
return null !== a && "object" == typeof a && !jspb.Message.isArray_(a) && !(jspb.Message.SUPPORTS_UINT8ARRAY_ && a instanceof Uint8Array);
};
jspb.Message.initPivotAndExtensionObject_ = function (a, b) {
var c = a.array.length,
d = -1;
if (c && (d = c - 1, c = a.array[d], jspb.Message.isExtensionObject_(c))) {
a.pivot_ = jspb.Message.getFieldNumber_(a, d);
a.extensionObject_ = c;
return;
}
-1 < b ? (a.pivot_ = Math.max(b, jspb.Message.getFieldNumber_(a, d + 1)), a.extensionObject_ = null) : a.pivot_ = Number.MAX_VALUE;
};
jspb.Message.maybeInitEmptyExtensionObject_ = function (a) {
var b = jspb.Message.getIndex_(a, a.pivot_);
a.array[b] || (a.extensionObject_ = a.array[b] = {});
};
jspb.Message.toObjectList = function (a, b, c) {
for (var d = [], e = 0; e < a.length; e++) d[e] = b.call(a[e], c, a[e]);
return d;
};
jspb.Message.toObjectExtension = function (a, b, c, d, e) {
for (var f in c) {
var g = c[f],
h = d.call(a, g);
if (null != h) {
for (var k in g.fieldName) if (g.fieldName.hasOwnProperty(k)) break;
b[k] = g.toObjectFn ? g.isRepeated ? jspb.Message.toObjectList(h, g.toObjectFn, e) : g.toObjectFn(e, h) : h;
}
}
};
jspb.Message.serializeBinaryExtensions = function (a, b, c, d) {
for (var e in c) {
var f = c[e],
g = f.fieldInfo;
if (!f.binaryWriterFn) throw Error("Message extension present that was generated without binary serialization support");
var h = d.call(a, g);
if (null != h) if (g.isMessageType()) {
if (f.binaryMessageSerializeFn) f.binaryWriterFn.call(b, g.fieldIndex, h, f.binaryMessageSerializeFn);else throw Error("Message extension present holding submessage without binary support enabled, and message is being serialized to binary format");
} else f.binaryWriterFn.call(b, g.fieldIndex, h);
}
};
jspb.Message.readBinaryExtension = function (a, b, c, d, e) {
var f = c[b.getFieldNumber()];
if (f) {
c = f.fieldInfo;
if (!f.binaryReaderFn) throw Error("Deserializing extension whose generated code does not support binary format");
if (c.isMessageType()) {
var g = new c.ctor();
f.binaryReaderFn.call(b, g, f.binaryMessageDeserializeFn);
} else g = f.binaryReaderFn.call(b);
c.isRepeated && !f.isPacked ? (b = d.call(a, c)) ? b.push(g) : e.call(a, c, [g]) : e.call(a, c, g);
} else b.skipField();
};
jspb.Message.getField = function (a, b) {
if (b < a.pivot_) {
b = jspb.Message.getIndex_(a, b);
var c = a.array[b];
return c === jspb.Message.EMPTY_LIST_SENTINEL_ ? a.array[b] = [] : c;
}
if (a.extensionObject_) return c = a.extensionObject_[b], c === jspb.Message.EMPTY_LIST_SENTINEL_ ? a.extensionObject_[b] = [] : c;
};
jspb.Message.getRepeatedField = function (a, b) {
return jspb.Message.getField(a, b);
};
jspb.Message.getOptionalFloatingPointField = function (a, b) {
a = jspb.Message.getField(a, b);
return null == a ? a : +a;
};
jspb.Message.getBooleanField = function (a, b) {
a = jspb.Message.getField(a, b);
return null == a ? a : !!a;
};
jspb.Message.getRepeatedFloatingPointField = function (a, b) {
var c = jspb.Message.getRepeatedField(a, b);
a.convertedPrimitiveFields_ || (a.convertedPrimitiveFields_ = {});
if (!a.convertedPrimitiveFields_[b]) {
for (var d = 0; d < c.length; d++) c[d] = +c[d];
a.convertedPrimitiveFields_[b] = !0;
}
return c;
};
jspb.Message.getRepeatedBooleanField = function (a, b) {
var c = jspb.Message.getRepeatedField(a, b);
a.convertedPrimitiveFields_ || (a.convertedPrimitiveFields_ = {});
if (!a.convertedPrimitiveFields_[b]) {
for (var d = 0; d < c.length; d++) c[d] = !!c[d];
a.convertedPrimitiveFields_[b] = !0;
}
return c;
};
jspb.Message.bytesAsB64 = function (a) {
if (null == a || "string" === typeof a) return a;
if (jspb.Message.SUPPORTS_UINT8ARRAY_ && a instanceof Uint8Array) return goog.crypt.base64.encodeByteArray(a);
goog.asserts.fail("Cannot coerce to b64 string: " + goog.typeOf(a));
return null;
};
jspb.Message.bytesAsU8 = function (a) {
if (null == a || a instanceof Uint8Array) return a;
if ("string" === typeof a) return goog.crypt.base64.decodeStringToUint8Array(a);
goog.asserts.fail("Cannot coerce to Uint8Array: " + goog.typeOf(a));
return null;
};
jspb.Message.bytesListAsB64 = function (a) {
jspb.Message.assertConsistentTypes_(a);
return a.length && "string" !== typeof a[0] ? goog.array.map(a, jspb.Message.bytesAsB64) : a;
};
jspb.Message.bytesListAsU8 = function (a) {
jspb.Message.assertConsistentTypes_(a);
return !a.length || a[0] instanceof Uint8Array ? a : goog.array.map(a, jspb.Message.bytesAsU8);
};
jspb.Message.assertConsistentTypes_ = function (a) {
if (goog.DEBUG && a && 1 < a.length) {
var b = goog.typeOf(a[0]);
goog.array.forEach(a, function (a) {
goog.typeOf(a) != b && goog.asserts.fail("Inconsistent type in JSPB repeated field array. Got " + goog.typeOf(a) + " expected " + b);
});
}
};
jspb.Message.getFieldWithDefault = function (a, b, c) {
a = jspb.Message.getField(a, b);
return null == a ? c : a;
};
jspb.Message.getBooleanFieldWithDefault = function (a, b, c) {
a = jspb.Message.getBooleanField(a, b);
return null == a ? c : a;
};
jspb.Message.getFloatingPointFieldWithDefault = function (a, b, c) {
a = jspb.Message.getOptionalFloatingPointField(a, b);
return null == a ? c : a;
};
jspb.Message.getFieldProto3 = jspb.Message.getFieldWithDefault;
jspb.Message.getMapField = function (a, b, c, d) {
a.wrappers_ || (a.wrappers_ = {});
if (b in a.wrappers_) return a.wrappers_[b];
var e = jspb.Message.getField(a, b);
if (!e) {
if (c) return;
e = [];
jspb.Message.setField(a, b, e);
}
return a.wrappers_[b] = new jspb.Map(e, d);
};
jspb.Message.setField = function (a, b, c) {
goog.asserts.assertInstanceof(a, jspb.Message);
b < a.pivot_ ? a.array[jspb.Message.getIndex_(a, b)] = c : (jspb.Message.maybeInitEmptyExtensionObject_(a), a.extensionObject_[b] = c);
return a;
};
jspb.Message.setProto3IntField = function (a, b, c) {
return jspb.Message.setFieldIgnoringDefault_(a, b, c, 0);
};
jspb.Message.setProto3FloatField = function (a, b, c) {
return jspb.Message.setFieldIgnoringDefault_(a, b, c, 0);
};
jspb.Message.setProto3BooleanField = function (a, b, c) {
return jspb.Message.setFieldIgnoringDefault_(a, b, c, !1);
};
jspb.Message.setProto3StringField = function (a, b, c) {
return jspb.Message.setFieldIgnoringDefault_(a, b, c, "");
};
jspb.Message.setProto3BytesField = function (a, b, c) {
return jspb.Message.setFieldIgnoringDefault_(a, b, c, "");
};
jspb.Message.setProto3EnumField = function (a, b, c) {
return jspb.Message.setFieldIgnoringDefault_(a, b, c, 0);
};
jspb.Message.setProto3StringIntField = function (a, b, c) {
return jspb.Message.setFieldIgnoringDefault_(a, b, c, "0");
};
jspb.Message.setFieldIgnoringDefault_ = function (a, b, c, d) {
goog.asserts.assertInstanceof(a, jspb.Message);
c !== d ? jspb.Message.setField(a, b, c) : b < a.pivot_ ? a.array[jspb.Message.getIndex_(a, b)] = null : (jspb.Message.maybeInitEmptyExtensionObject_(a), delete a.extensionObject_[b]);
return a;
};
jspb.Message.addToRepeatedField = function (a, b, c, d) {
goog.asserts.assertInstanceof(a, jspb.Message);
b = jspb.Message.getRepeatedField(a, b);
void 0 != d ? b.splice(d, 0, c) : b.push(c);
return a;
};
jspb.Message.setOneofField = function (a, b, c, d) {
goog.asserts.assertInstanceof(a, jspb.Message);
(c = jspb.Message.computeOneofCase(a, c)) && c !== b && void 0 !== d && (a.wrappers_ && c in a.wrappers_ && (a.wrappers_[c] = void 0), jspb.Message.setField(a, c, void 0));
return jspb.Message.setField(a, b, d);
};
jspb.Message.computeOneofCase = function (a, b) {
for (var c, d, e = 0; e < b.length; e++) {
var f = b[e],
g = jspb.Message.getField(a, f);
null != g && (c = f, d = g, jspb.Message.setField(a, f, void 0));
}
return c ? (jspb.Message.setField(a, c, d), c) : 0;
};
jspb.Message.getWrapperField = function (a, b, c, d) {
a.wrappers_ || (a.wrappers_ = {});
if (!a.wrappers_[c]) {
var e = jspb.Message.getField(a, c);
if (d || e) a.wrappers_[c] = new b(e);
}
return a.wrappers_[c];
};
jspb.Message.getRepeatedWrapperField = function (a, b, c) {
jspb.Message.wrapRepeatedField_(a, b, c);
b = a.wrappers_[c];
b == jspb.Message.EMPTY_LIST_SENTINEL_ && (b = a.wrappers_[c] = []);
return b;
};
jspb.Message.wrapRepeatedField_ = function (a, b, c) {
a.wrappers_ || (a.wrappers_ = {});
if (!a.wrappers_[c]) {
for (var d = jspb.Message.getRepeatedField(a, c), e = [], f = 0; f < d.length; f++) e[f] = new b(d[f]);
a.wrappers_[c] = e;
}
};
jspb.Message.setWrapperField = function (a, b, c) {
goog.asserts.assertInstanceof(a, jspb.Message);
a.wrappers_ || (a.wrappers_ = {});
var d = c ? c.toArray() : c;
a.wrappers_[b] = c;
return jspb.Message.setField(a, b, d);
};
jspb.Message.setOneofWrapperField = function (a, b, c, d) {
goog.asserts.assertInstanceof(a, jspb.Message);
a.wrappers_ || (a.wrappers_ = {});
var e = d ? d.toArray() : d;
a.wrappers_[b] = d;
return jspb.Message.setOneofField(a, b, c, e);
};
jspb.Message.setRepeatedWrapperField = function (a, b, c) {
goog.asserts.assertInstanceof(a, jspb.Message);
a.wrappers_ || (a.wrappers_ = {});
c = c || [];
for (var d = [], e = 0; e < c.length; e++) d[e] = c[e].toArray();
a.wrappers_[b] = c;
return jspb.Message.setField(a, b, d);
};
jspb.Message.addToRepeatedWrapperField = function (a, b, c, d, e) {
jspb.Message.wrapRepeatedField_(a, d, b);
var f = a.wrappers_[b];
f || (f = a.wrappers_[b] = []);
c = c ? c : new d();
a = jspb.Message.getRepeatedField(a, b);
void 0 != e ? (f.splice(e, 0, c), a.splice(e, 0, c.toArray())) : (f.push(c), a.push(c.toArray()));
return c;
};
jspb.Message.toMap = function (a, b, c, d) {
for (var e = {}, f = 0; f < a.length; f++) e[b.call(a[f])] = c ? c.call(a[f], d, a[f]) : a[f];
return e;
};
jspb.Message.prototype.syncMapFields_ = function () {
if (this.wrappers_) for (var a in this.wrappers_) {
var b = this.wrappers_[a];
if (goog.isArray(b)) for (var c = 0; c < b.length; c++) b[c] && b[c].toArray();else b && b.toArray();
}
};
jspb.Message.prototype.toArray = function () {
this.syncMapFields_();
return this.array;
};
jspb.Message.GENERATE_TO_STRING && (jspb.Message.prototype.toString = function () {
this.syncMapFields_();
return this.array.toString();
});
jspb.Message.prototype.getExtension = function (a) {
if (this.extensionObject_) {
this.wrappers_ || (this.wrappers_ = {});
var b = a.fieldIndex;
if (a.isRepeated) {
if (a.isMessageType()) return this.wrappers_[b] || (this.wrappers_[b] = goog.array.map(this.extensionObject_[b] || [], function (b) {
return new a.ctor(b);
})), this.wrappers_[b];
} else if (a.isMessageType()) return !this.wrappers_[b] && this.extensionObject_[b] && (this.wrappers_[b] = new a.ctor(this.extensionObject_[b])), this.wrappers_[b];
return this.extensionObject_[b];
}
};
jspb.Message.prototype.setExtension = function (a, b) {
this.wrappers_ || (this.wrappers_ = {});
jspb.Message.maybeInitEmptyExtensionObject_(this);
var c = a.fieldIndex;
a.isRepeated ? (b = b || [], a.isMessageType() ? (this.wrappers_[c] = b, this.extensionObject_[c] = goog.array.map(b, function (a) {
return a.toArray();
})) : this.extensionObject_[c] = b) : a.isMessageType() ? (this.wrappers_[c] = b, this.extensionObject_[c] = b ? b.toArray() : b) : this.extensionObject_[c] = b;
return this;
};
jspb.Message.difference = function (a, b) {
if (!(a instanceof b.constructor)) throw Error("Messages have different types.");
var c = a.toArray();
b = b.toArray();
var d = [],
e = 0,
f = c.length > b.length ? c.length : b.length;
a.getJsPbMessageId() && (d[0] = a.getJsPbMessageId(), e = 1);
for (; e < f; e++) jspb.Message.compareFields(c[e], b[e]) || (d[e] = b[e]);
return new a.constructor(d);
};
jspb.Message.equals = function (a, b) {
return a == b || !(!a || !b) && a instanceof b.constructor && jspb.Message.compareFields(a.toArray(), b.toArray());
};
jspb.Message.compareExtensions = function (a, b) {
a = a || {};
b = b || {};
var c = {},
d;
for (d in a) c[d] = 0;
for (d in b) c[d] = 0;
for (d in c) if (!jspb.Message.compareFields(a[d], b[d])) return !1;
return !0;
};
jspb.Message.compareFields = function (a, b) {
if (a == b) return !0;
if (!goog.isObject(a) || !goog.isObject(b)) return "number" === typeof a && isNaN(a) || "number" === typeof b && isNaN(b) ? String(a) == String(b) : !1;
if (a.constructor != b.constructor) return !1;
if (jspb.Message.SUPPORTS_UINT8ARRAY_ && a.constructor === Uint8Array) {
if (a.length != b.length) return !1;
for (var c = 0; c < a.length; c++) if (a[c] != b[c]) return !1;
return !0;
}
if (a.constructor === Array) {
var d = void 0,
e = void 0,
f = Math.max(a.length, b.length);
for (c = 0; c < f; c++) {
var g = a[c],
h = b[c];
g && g.constructor == Object && (goog.asserts.assert(void 0 === d), goog.asserts.assert(c === a.length - 1), d = g, g = void 0);
h && h.constructor == Object && (goog.asserts.assert(void 0 === e), goog.asserts.assert(c === b.length - 1), e = h, h = void 0);
if (!jspb.Message.compareFields(g, h)) return !1;
}
return d || e ? (d = d || {}, e = e || {}, jspb.Message.compareExtensions(d, e)) : !0;
}
if (a.constructor === Object) return jspb.Message.compareExtensions(a, b);
throw Error("Invalid type in JSPB array");
};
jspb.Message.prototype.cloneMessage = function () {
return jspb.Message.cloneMessage(this);
};
jspb.Message.prototype.clone = function () {
return jspb.Message.cloneMessage(this);
};
jspb.Message.clone = function (a) {
return jspb.Message.cloneMessage(a);
};
jspb.Message.cloneMessage = function (a) {
return new a.constructor(jspb.Message.clone_(a.toArray()));
};
jspb.Message.copyInto = function (a, b) {
goog.asserts.assertInstanceof(a, jspb.Message);
goog.asserts.assertInstanceof(b, jspb.Message);
goog.asserts.assert(a.constructor == b.constructor, "Copy source and target message should have the same type.");
a = jspb.Message.clone(a);
for (var c = b.toArray(), d = a.toArray(), e = c.length = 0; e < d.length; e++) c[e] = d[e];
b.wrappers_ = a.wrappers_;
b.extensionObject_ = a.extensionObject_;
};
jspb.Message.clone_ = function (a) {
if (goog.isArray(a)) {
for (var b = Array(a.length), c = 0; c < a.length; c++) {
var d = a[c];
null != d && (b[c] = "object" == typeof d ? jspb.Message.clone_(goog.asserts.assert(d)) : d);
}
return b;
}
if (jspb.Message.SUPPORTS_UINT8ARRAY_ && a instanceof Uint8Array) return new Uint8Array(a);
b = {};
for (c in a) d = a[c], null != d && (b[c] = "object" == typeof d ? jspb.Message.clone_(goog.asserts.assert(d)) : d);
return b;
};
jspb.Message.registerMessageType = function (a, b) {
b.messageId = a;
};
jspb.Message.messageSetExtensions = {};
jspb.Message.messageSetExtensionsBinary = {};
jspb.arith = {};
jspb.arith.UInt64 = function (a, b) {
this.lo = a;
this.hi = b;
};
jspb.arith.UInt64.prototype.cmp = function (a) {
return this.hi < a.hi || this.hi == a.hi && this.lo < a.lo ? -1 : this.hi == a.hi && this.lo == a.lo ? 0 : 1;
};
jspb.arith.UInt64.prototype.rightShift = function () {
return new jspb.arith.UInt64((this.lo >>> 1 | (this.hi & 1) << 31) >>> 0, this.hi >>> 1 >>> 0);
};
jspb.arith.UInt64.prototype.leftShift = function () {
return new jspb.arith.UInt64(this.lo << 1 >>> 0, (this.hi << 1 | this.lo >>> 31) >>> 0);
};
jspb.arith.UInt64.prototype.msb = function () {
return !!(this.hi & 2147483648);
};
jspb.arith.UInt64.prototype.lsb = function () {
return !!(this.lo & 1);
};
jspb.arith.UInt64.prototype.zero = function () {
return 0 == this.lo && 0 == this.hi;
};
jspb.arith.UInt64.prototype.add = function (a) {
return new jspb.arith.UInt64((this.lo + a.lo & 4294967295) >>> 0 >>> 0, ((this.hi + a.hi & 4294967295) >>> 0) + (4294967296 <= this.lo + a.lo ? 1 : 0) >>> 0);
};
jspb.arith.UInt64.prototype.sub = function (a) {
return new jspb.arith.UInt64((this.lo - a.lo & 4294967295) >>> 0 >>> 0, ((this.hi - a.hi & 4294967295) >>> 0) - (0 > this.lo - a.lo ? 1 : 0) >>> 0);
};
jspb.arith.UInt64.mul32x32 = function (a, b) {
var c = a & 65535;
a >>>= 16;
var d = b & 65535,
e = b >>> 16;
b = c * d + 65536 * (c * e & 65535) + 65536 * (a * d & 65535);
for (c = a * e + (c * e >>> 16) + (a * d >>> 16); 4294967296 <= b;) b -= 4294967296, c += 1;
return new jspb.arith.UInt64(b >>> 0, c >>> 0);
};
jspb.arith.UInt64.prototype.mul = function (a) {
var b = jspb.arith.UInt64.mul32x32(this.lo, a);
a = jspb.arith.UInt64.mul32x32(this.hi, a);
a.hi = a.lo;
a.lo = 0;
return b.add(a);
};
jspb.arith.UInt64.prototype.div = function (a) {
if (0 == a) return [];
var b = new jspb.arith.UInt64(0, 0),
c = new jspb.arith.UInt64(this.lo, this.hi);
a = new jspb.arith.UInt64(a, 0);
for (var d = new jspb.arith.UInt64(1, 0); !a.msb();) a = a.leftShift(), d = d.leftShift();
for (; !d.zero();) 0 >= a.cmp(c) && (b = b.add(d), c = c.sub(a)), a = a.rightShift(), d = d.rightShift();
return [b, c];
};
jspb.arith.UInt64.prototype.toString = function () {
for (var a = "", b = this; !b.zero();) {
b = b.div(10);
var c = b[0];
a = b[1].lo + a;
b = c;
}
"" == a && (a = "0");
return a;
};
jspb.arith.UInt64.fromString = function (a) {
for (var b = new jspb.arith.UInt64(0, 0), c = new jspb.arith.UInt64(0, 0), d = 0; d < a.length; d++) {
if ("0" > a[d] || "9" < a[d]) return null;
var e = parseInt(a[d], 10);
c.lo = e;
b = b.mul(10).add(c);
}
return b;
};
jspb.arith.UInt64.prototype.clone = function () {
return new jspb.arith.UInt64(this.lo, this.hi);
};
jspb.arith.Int64 = function (a, b) {
this.lo = a;
this.hi = b;
};
jspb.arith.Int64.prototype.add = function (a) {
return new jspb.arith.Int64((this.lo + a.lo & 4294967295) >>> 0 >>> 0, ((this.hi + a.hi & 4294967295) >>> 0) + (4294967296 <= this.lo + a.lo ? 1 : 0) >>> 0);
};
jspb.arith.Int64.prototype.sub = function (a) {
return new jspb.arith.Int64((this.lo - a.lo & 4294967295) >>> 0 >>> 0, ((this.hi - a.hi & 4294967295) >>> 0) - (0 > this.lo - a.lo ? 1 : 0) >>> 0);
};
jspb.arith.Int64.prototype.clone = function () {
return new jspb.arith.Int64(this.lo, this.hi);
};
jspb.arith.Int64.prototype.toString = function () {
var a = 0 != (this.hi & 2147483648),
b = new jspb.arith.UInt64(this.lo, this.hi);
a && (b = new jspb.arith.UInt64(0, 0).sub(b));
return (a ? "-" : "") + b.toString();
};
jspb.arith.Int64.fromString = function (a) {
var b = 0 < a.length && "-" == a[0];
b && (a = a.substring(1));
a = jspb.arith.UInt64.fromString(a);
if (null === a) return null;
b && (a = new jspb.arith.UInt64(0, 0).sub(a));
return new jspb.arith.Int64(a.lo, a.hi);
};
jspb.BinaryEncoder = function () {
this.buffer_ = [];
};
jspb.BinaryEncoder.prototype.length = function () {
return this.buffer_.length;
};
jspb.BinaryEncoder.prototype.end = function () {
var a = this.buffer_;
this.buffer_ = [];
return a;
};
jspb.BinaryEncoder.prototype.writeSplitVarint64 = function (a, b) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(b == Math.floor(b));
goog.asserts.assert(0 <= a && a < jspb.BinaryConstants.TWO_TO_32);
for (goog.asserts.assert(0 <= b && b < jspb.BinaryConstants.TWO_TO_32); 0 < b || 127 < a;) this.buffer_.push(a & 127 | 128), a = (a >>> 7 | b << 25) >>> 0, b >>>= 7;
this.buffer_.push(a);
};
jspb.BinaryEncoder.prototype.writeSplitFixed64 = function (a, b) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(b == Math.floor(b));
goog.asserts.assert(0 <= a && a < jspb.BinaryConstants.TWO_TO_32);
goog.asserts.assert(0 <= b && b < jspb.BinaryConstants.TWO_TO_32);
this.writeUint32(a);
this.writeUint32(b);
};
jspb.BinaryEncoder.prototype.writeUnsignedVarint32 = function (a) {
goog.asserts.assert(a == Math.floor(a));
for (goog.asserts.assert(0 <= a && a < jspb.BinaryConstants.TWO_TO_32); 127 < a;) this.buffer_.push(a & 127 | 128), a >>>= 7;
this.buffer_.push(a);
};
jspb.BinaryEncoder.prototype.writeSignedVarint32 = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(a >= -jspb.BinaryConstants.TWO_TO_31 && a < jspb.BinaryConstants.TWO_TO_31);
if (0 <= a) this.writeUnsignedVarint32(a);else {
for (var b = 0; 9 > b; b++) this.buffer_.push(a & 127 | 128), a >>= 7;
this.buffer_.push(1);
}
};
jspb.BinaryEncoder.prototype.writeUnsignedVarint64 = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(0 <= a && a < jspb.BinaryConstants.TWO_TO_64);
jspb.utils.splitInt64(a);
this.writeSplitVarint64(jspb.utils.split64Low, jspb.utils.split64High);
};
jspb.BinaryEncoder.prototype.writeSignedVarint64 = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(a >= -jspb.BinaryConstants.TWO_TO_63 && a < jspb.BinaryConstants.TWO_TO_63);
jspb.utils.splitInt64(a);
this.writeSplitVarint64(jspb.utils.split64Low, jspb.utils.split64High);
};
jspb.BinaryEncoder.prototype.writeZigzagVarint32 = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(a >= -jspb.BinaryConstants.TWO_TO_31 && a < jspb.BinaryConstants.TWO_TO_31);
this.writeUnsignedVarint32((a << 1 ^ a >> 31) >>> 0);
};
jspb.BinaryEncoder.prototype.writeZigzagVarint64 = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(a >= -jspb.BinaryConstants.TWO_TO_63 && a < jspb.BinaryConstants.TWO_TO_63);
jspb.utils.splitZigzag64(a);
this.writeSplitVarint64(jspb.utils.split64Low, jspb.utils.split64High);
};
jspb.BinaryEncoder.prototype.writeZigzagVarint64String = function (a) {
this.writeZigzagVarintHash64(jspb.utils.decimalStringToHash64(a));
};
jspb.BinaryEncoder.prototype.writeZigzagVarintHash64 = function (a) {
var b = this;
jspb.utils.splitHash64(a);
jspb.utils.toZigzag64(jspb.utils.split64Low, jspb.utils.split64High, function (a, d) {
b.writeSplitVarint64(a >>> 0, d >>> 0);
});
};
jspb.BinaryEncoder.prototype.writeUint8 = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(0 <= a && 256 > a);
this.buffer_.push(a >>> 0 & 255);
};
jspb.BinaryEncoder.prototype.writeUint16 = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(0 <= a && 65536 > a);
this.buffer_.push(a >>> 0 & 255);
this.buffer_.push(a >>> 8 & 255);
};
jspb.BinaryEncoder.prototype.writeUint32 = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(0 <= a && a < jspb.BinaryConstants.TWO_TO_32);
this.buffer_.push(a >>> 0 & 255);
this.buffer_.push(a >>> 8 & 255);
this.buffer_.push(a >>> 16 & 255);
this.buffer_.push(a >>> 24 & 255);
};
jspb.BinaryEncoder.prototype.writeUint64 = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(0 <= a && a < jspb.BinaryConstants.TWO_TO_64);
jspb.utils.splitUint64(a);
this.writeUint32(jspb.utils.split64Low);
this.writeUint32(jspb.utils.split64High);
};
jspb.BinaryEncoder.prototype.writeInt8 = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(-128 <= a && 128 > a);
this.buffer_.push(a >>> 0 & 255);
};
jspb.BinaryEncoder.prototype.writeInt16 = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(-32768 <= a && 32768 > a);
this.buffer_.push(a >>> 0 & 255);
this.buffer_.push(a >>> 8 & 255);
};
jspb.BinaryEncoder.prototype.writeInt32 = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(a >= -jspb.BinaryConstants.TWO_TO_31 && a < jspb.BinaryConstants.TWO_TO_31);
this.buffer_.push(a >>> 0 & 255);
this.buffer_.push(a >>> 8 & 255);
this.buffer_.push(a >>> 16 & 255);
this.buffer_.push(a >>> 24 & 255);
};
jspb.BinaryEncoder.prototype.writeInt64 = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(a >= -jspb.BinaryConstants.TWO_TO_63 && a < jspb.BinaryConstants.TWO_TO_63);
jspb.utils.splitInt64(a);
this.writeSplitFixed64(jspb.utils.split64Low, jspb.utils.split64High);
};
jspb.BinaryEncoder.prototype.writeInt64String = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(+a >= -jspb.BinaryConstants.TWO_TO_63 && +a < jspb.BinaryConstants.TWO_TO_63);
jspb.utils.splitHash64(jspb.utils.decimalStringToHash64(a));
this.writeSplitFixed64(jspb.utils.split64Low, jspb.utils.split64High);
};
jspb.BinaryEncoder.prototype.writeFloat = function (a) {
goog.asserts.assert(Infinity === a || -Infinity === a || isNaN(a) || a >= -jspb.BinaryConstants.FLOAT32_MAX && a <= jspb.BinaryConstants.FLOAT32_MAX);
jspb.utils.splitFloat32(a);
this.writeUint32(jspb.utils.split64Low);
};
jspb.BinaryEncoder.prototype.writeDouble = function (a) {
goog.asserts.assert(Infinity === a || -Infinity === a || isNaN(a) || a >= -jspb.BinaryConstants.FLOAT64_MAX && a <= jspb.BinaryConstants.FLOAT64_MAX);
jspb.utils.splitFloat64(a);
this.writeUint32(jspb.utils.split64Low);
this.writeUint32(jspb.utils.split64High);
};
jspb.BinaryEncoder.prototype.writeBool = function (a) {
goog.asserts.assert("boolean" === typeof a || "number" === typeof a);
this.buffer_.push(a ? 1 : 0);
};
jspb.BinaryEncoder.prototype.writeEnum = function (a) {
goog.asserts.assert(a == Math.floor(a));
goog.asserts.assert(a >= -jspb.BinaryConstants.TWO_TO_31 && a < jspb.BinaryConstants.TWO_TO_31);
this.writeSignedVarint32(a);
};
jspb.BinaryEncoder.prototype.writeBytes = function (a) {
this.buffer_.push.apply(this.buffer_, a);
};
jspb.BinaryEncoder.prototype.writeVarintHash64 = function (a) {
jspb.utils.splitHash64(a);
this.writeSplitVarint64(jspb.utils.split64Low, jspb.utils.split64High);
};
jspb.BinaryEncoder.prototype.writeFixedHash64 = function (a) {
jspb.utils.splitHash64(a);
this.writeUint32(jspb.utils.split64Low);
this.writeUint32(jspb.utils.split64High);
};
jspb.BinaryEncoder.prototype.writeString = function (a) {
for (var b = this.buffer_.length, c = 0; c < a.length; c++) {
var d = a.charCodeAt(c);
if (128 > d) this.buffer_.push(d);else if (2048 > d) this.buffer_.push(d >> 6 | 192), this.buffer_.push(d & 63 | 128);else if (65536 > d) if (55296 <= d && 56319 >= d && c + 1 < a.length) {
var e = a.charCodeAt(c + 1);
56320 <= e && 57343 >= e && (d = 1024 * (d - 55296) + e - 56320 + 65536, this.buffer_.push(d >> 18 | 240), this.buffer_.push(d >> 12 & 63 | 128), this.buffer_.push(d >> 6 & 63 | 128), this.buffer_.push(d & 63 | 128), c++);
} else this.buffer_.push(d >> 12 | 224), this.buffer_.push(d >> 6 & 63 | 128), this.buffer_.push(d & 63 | 128);
}
return this.buffer_.length - b;
};
jspb.BinaryWriter = function () {
this.blocks_ = [];
this.totalLength_ = 0;
this.encoder_ = new jspb.BinaryEncoder();
this.bookmarks_ = [];
};
jspb.BinaryWriter.prototype.appendUint8Array_ = function (a) {
var b = this.encoder_.end();
this.blocks_.push(b);
this.blocks_.push(a);
this.totalLength_ += b.length + a.length;
};
jspb.BinaryWriter.prototype.beginDelimited_ = function (a) {
this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.DELIMITED);
a = this.encoder_.end();
this.blocks_.push(a);
this.totalLength_ += a.length;
a.push(this.totalLength_);
return a;
};
jspb.BinaryWriter.prototype.endDelimited_ = function (a) {
var b = a.pop();
b = this.totalLength_ + this.encoder_.length() - b;
for (goog.asserts.assert(0 <= b); 127 < b;) a.push(b & 127 | 128), b >>>= 7, this.totalLength_++;
a.push(b);
this.totalLength_++;
};
jspb.BinaryWriter.prototype.writeSerializedMessage = function (a, b, c) {
this.appendUint8Array_(a.subarray(b, c));
};
jspb.BinaryWriter.prototype.maybeWriteSerializedMessage = function (a, b, c) {
null != a && null != b && null != c && this.writeSerializedMessage(a, b, c);
};
jspb.BinaryWriter.prototype.reset = function () {
this.blocks_ = [];
this.encoder_.end();
this.totalLength_ = 0;
this.bookmarks_ = [];
};
jspb.BinaryWriter.prototype.getResultBuffer = function () {
goog.asserts.assert(0 == this.bookmarks_.length);
for (var a = new Uint8Array(this.totalLength_ + this.encoder_.length()), b = this.blocks_, c = b.length, d = 0, e = 0; e < c; e++) {
var f = b[e];
a.set(f, d);
d += f.length;
}
b = this.encoder_.end();
a.set(b, d);
d += b.length;
goog.asserts.assert(d == a.length);
this.blocks_ = [a];
return a;
};
jspb.BinaryWriter.prototype.getResultBase64String = function (a) {
return goog.crypt.base64.encodeByteArray(this.getResultBuffer(), a);
};
jspb.BinaryWriter.prototype.beginSubMessage = function (a) {
this.bookmarks_.push(this.beginDelimited_(a));
};
jspb.BinaryWriter.prototype.endSubMessage = function () {
goog.asserts.assert(0 <= this.bookmarks_.length);
this.endDelimited_(this.bookmarks_.pop());
};
jspb.BinaryWriter.prototype.writeFieldHeader_ = function (a, b) {
goog.asserts.assert(1 <= a && a == Math.floor(a));
this.encoder_.writeUnsignedVarint32(8 * a + b);
};
jspb.BinaryWriter.prototype.writeAny = function (a, b, c) {
var d = jspb.BinaryConstants.FieldType;
switch (a) {
case d.DOUBLE:
this.writeDouble(b, c);
break;
case d.FLOAT:
this.writeFloat(b, c);
break;
case d.INT64:
this.writeInt64(b, c);
break;
case d.UINT64:
this.writeUint64(b, c);
break;
case d.INT32:
this.writeInt32(b, c);
break;
case d.FIXED64:
this.writeFixed64(b, c);
break;
case d.FIXED32:
this.writeFixed32(b, c);
break;
case d.BOOL:
this.writeBool(b, c);
break;
case d.STRING:
this.writeString(b, c);
break;
case d.GROUP:
goog.asserts.fail("Group field type not supported in writeAny()");
break;
case d.MESSAGE:
goog.asserts.fail("Message field type not supported in writeAny()");
break;
case d.BYTES:
this.writeBytes(b, c);
break;
case d.UINT32:
this.writeUint32(b, c);
break;
case d.ENUM:
this.writeEnum(b, c);
break;
case d.SFIXED32:
this.writeSfixed32(b, c);
break;
case d.SFIXED64:
this.writeSfixed64(b, c);
break;
case d.SINT32:
this.writeSint32(b, c);
break;
case d.SINT64:
this.writeSint64(b, c);
break;
case d.FHASH64:
this.writeFixedHash64(b, c);
break;
case d.VHASH64:
this.writeVarintHash64(b, c);
break;
default:
goog.asserts.fail("Invalid field type in writeAny()");
}
};
jspb.BinaryWriter.prototype.writeUnsignedVarint32_ = function (a, b) {
null != b && (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeUnsignedVarint32(b));
};
jspb.BinaryWriter.prototype.writeSignedVarint32_ = function (a, b) {
null != b && (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeSignedVarint32(b));
};
jspb.BinaryWriter.prototype.writeUnsignedVarint64_ = function (a, b) {
null != b && (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeUnsignedVarint64(b));
};
jspb.BinaryWriter.prototype.writeSignedVarint64_ = function (a, b) {
null != b && (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeSignedVarint64(b));
};
jspb.BinaryWriter.prototype.writeZigzagVarint32_ = function (a, b) {
null != b && (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeZigzagVarint32(b));
};
jspb.BinaryWriter.prototype.writeZigzagVarint64_ = function (a, b) {
null != b && (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeZigzagVarint64(b));
};
jspb.BinaryWriter.prototype.writeZigzagVarint64String_ = function (a, b) {
null != b && (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeZigzagVarint64String(b));
};
jspb.BinaryWriter.prototype.writeZigzagVarintHash64_ = function (a, b) {
null != b && (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeZigzagVarintHash64(b));
};
jspb.BinaryWriter.prototype.writeInt32 = function (a, b) {
null != b && (goog.asserts.assert(b >= -jspb.BinaryConstants.TWO_TO_31 && b < jspb.BinaryConstants.TWO_TO_31), this.writeSignedVarint32_(a, b));
};
jspb.BinaryWriter.prototype.writeInt32String = function (a, b) {
null != b && (b = parseInt(b, 10), goog.asserts.assert(b >= -jspb.BinaryConstants.TWO_TO_31 && b < jspb.BinaryConstants.TWO_TO_31), this.writeSignedVarint32_(a, b));
};
jspb.BinaryWriter.prototype.writeInt64 = function (a, b) {
null != b && (goog.asserts.assert(b >= -jspb.BinaryConstants.TWO_TO_63 && b < jspb.BinaryConstants.TWO_TO_63), this.writeSignedVarint64_(a, b));
};
jspb.BinaryWriter.prototype.writeInt64String = function (a, b) {
null != b && (b = jspb.arith.Int64.fromString(b), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeSplitVarint64(b.lo, b.hi));
};
jspb.BinaryWriter.prototype.writeUint32 = function (a, b) {
null != b && (goog.asserts.assert(0 <= b && b < jspb.BinaryConstants.TWO_TO_32), this.writeUnsignedVarint32_(a, b));
};
jspb.BinaryWriter.prototype.writeUint32String = function (a, b) {
null != b && (b = parseInt(b, 10), goog.asserts.assert(0 <= b && b < jspb.BinaryConstants.TWO_TO_32), this.writeUnsignedVarint32_(a, b));
};
jspb.BinaryWriter.prototype.writeUint64 = function (a, b) {
null != b && (goog.asserts.assert(0 <= b && b < jspb.BinaryConstants.TWO_TO_64), this.writeUnsignedVarint64_(a, b));
};
jspb.BinaryWriter.prototype.writeUint64String = function (a, b) {
null != b && (b = jspb.arith.UInt64.fromString(b), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeSplitVarint64(b.lo, b.hi));
};
jspb.BinaryWriter.prototype.writeSint32 = function (a, b) {
null != b && (goog.asserts.assert(b >= -jspb.BinaryConstants.TWO_TO_31 && b < jspb.BinaryConstants.TWO_TO_31), this.writeZigzagVarint32_(a, b));
};
jspb.BinaryWriter.prototype.writeSint64 = function (a, b) {
null != b && (goog.asserts.assert(b >= -jspb.BinaryConstants.TWO_TO_63 && b < jspb.BinaryConstants.TWO_TO_63), this.writeZigzagVarint64_(a, b));
};
jspb.BinaryWriter.prototype.writeSintHash64 = function (a, b) {
null != b && this.writeZigzagVarintHash64_(a, b);
};
jspb.BinaryWriter.prototype.writeSint64String = function (a, b) {
null != b && this.writeZigzagVarint64String_(a, b);
};
jspb.BinaryWriter.prototype.writeFixed32 = function (a, b) {
null != b && (goog.asserts.assert(0 <= b && b < jspb.BinaryConstants.TWO_TO_32), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.FIXED32), this.encoder_.writeUint32(b));
};
jspb.BinaryWriter.prototype.writeFixed64 = function (a, b) {
null != b && (goog.asserts.assert(0 <= b && b < jspb.BinaryConstants.TWO_TO_64), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.FIXED64), this.encoder_.writeUint64(b));
};
jspb.BinaryWriter.prototype.writeFixed64String = function (a, b) {
null != b && (b = jspb.arith.UInt64.fromString(b), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.FIXED64), this.encoder_.writeSplitFixed64(b.lo, b.hi));
};
jspb.BinaryWriter.prototype.writeSfixed32 = function (a, b) {
null != b && (goog.asserts.assert(b >= -jspb.BinaryConstants.TWO_TO_31 && b < jspb.BinaryConstants.TWO_TO_31), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.FIXED32), this.encoder_.writeInt32(b));
};
jspb.BinaryWriter.prototype.writeSfixed64 = function (a, b) {
null != b && (goog.asserts.assert(b >= -jspb.BinaryConstants.TWO_TO_63 && b < jspb.BinaryConstants.TWO_TO_63), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.FIXED64), this.encoder_.writeInt64(b));
};
jspb.BinaryWriter.prototype.writeSfixed64String = function (a, b) {
null != b && (b = jspb.arith.Int64.fromString(b), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.FIXED64), this.encoder_.writeSplitFixed64(b.lo, b.hi));
};
jspb.BinaryWriter.prototype.writeFloat = function (a, b) {
null != b && (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.FIXED32), this.encoder_.writeFloat(b));
};
jspb.BinaryWriter.prototype.writeDouble = function (a, b) {
null != b && (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.FIXED64), this.encoder_.writeDouble(b));
};
jspb.BinaryWriter.prototype.writeBool = function (a, b) {
null != b && (goog.asserts.assert("boolean" === typeof b || "number" === typeof b), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeBool(b));
};
jspb.BinaryWriter.prototype.writeEnum = function (a, b) {
null != b && (goog.asserts.assert(b >= -jspb.BinaryConstants.TWO_TO_31 && b < jspb.BinaryConstants.TWO_TO_31), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeSignedVarint32(b));
};
jspb.BinaryWriter.prototype.writeString = function (a, b) {
null != b && (a = this.beginDelimited_(a), this.encoder_.writeString(b), this.endDelimited_(a));
};
jspb.BinaryWriter.prototype.writeBytes = function (a, b) {
null != b && (b = jspb.utils.byteSourceToUint8Array(b), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.DELIMITED), this.encoder_.writeUnsignedVarint32(b.length), this.appendUint8Array_(b));
};
jspb.BinaryWriter.prototype.writeMessage = function (a, b, c) {
null != b && (a = this.beginDelimited_(a), c(b, this), this.endDelimited_(a));
};
jspb.BinaryWriter.prototype.writeMessageSet = function (a, b, c) {
null != b && (this.writeFieldHeader_(1, jspb.BinaryConstants.WireType.START_GROUP), this.writeFieldHeader_(2, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeSignedVarint32(a), a = this.beginDelimited_(3), c(b, this), this.endDelimited_(a), this.writeFieldHeader_(1, jspb.BinaryConstants.WireType.END_GROUP));
};
jspb.BinaryWriter.prototype.writeGroup = function (a, b, c) {
null != b && (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.START_GROUP), c(b, this), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.END_GROUP));
};
jspb.BinaryWriter.prototype.writeFixedHash64 = function (a, b) {
null != b && (goog.asserts.assert(8 == b.length), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.FIXED64), this.encoder_.writeFixedHash64(b));
};
jspb.BinaryWriter.prototype.writeVarintHash64 = function (a, b) {
null != b && (goog.asserts.assert(8 == b.length), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT), this.encoder_.writeVarintHash64(b));
};
jspb.BinaryWriter.prototype.writeSplitFixed64 = function (a, b, c) {
this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.FIXED64);
this.encoder_.writeSplitFixed64(b, c);
};
jspb.BinaryWriter.prototype.writeSplitVarint64 = function (a, b, c) {
this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT);
this.encoder_.writeSplitVarint64(b, c);
};
jspb.BinaryWriter.prototype.writeSplitZigzagVarint64 = function (a, b, c) {
this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.VARINT);
var d = this.encoder_;
jspb.utils.toZigzag64(b, c, function (a, b) {
d.writeSplitVarint64(a >>> 0, b >>> 0);
});
};
jspb.BinaryWriter.prototype.writeRepeatedInt32 = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeSignedVarint32_(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedInt32String = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeInt32String(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedInt64 = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeSignedVarint64_(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedSplitFixed64 = function (a, b, c, d) {
if (null != b) for (var e = 0; e < b.length; e++) this.writeSplitFixed64(a, c(b[e]), d(b[e]));
};
jspb.BinaryWriter.prototype.writeRepeatedSplitVarint64 = function (a, b, c, d) {
if (null != b) for (var e = 0; e < b.length; e++) this.writeSplitVarint64(a, c(b[e]), d(b[e]));
};
jspb.BinaryWriter.prototype.writeRepeatedSplitZigzagVarint64 = function (a, b, c, d) {
if (null != b) for (var e = 0; e < b.length; e++) this.writeSplitZigzagVarint64(a, c(b[e]), d(b[e]));
};
jspb.BinaryWriter.prototype.writeRepeatedInt64String = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeInt64String(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedUint32 = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeUnsignedVarint32_(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedUint32String = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeUint32String(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedUint64 = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeUnsignedVarint64_(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedUint64String = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeUint64String(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedSint32 = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeZigzagVarint32_(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedSint64 = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeZigzagVarint64_(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedSint64String = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeZigzagVarint64String_(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedSintHash64 = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeZigzagVarintHash64_(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedFixed32 = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeFixed32(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedFixed64 = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeFixed64(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedFixed64String = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeFixed64String(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedSfixed32 = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeSfixed32(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedSfixed64 = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeSfixed64(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedSfixed64String = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeSfixed64String(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedFloat = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeFloat(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedDouble = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeDouble(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedBool = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeBool(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedEnum = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeEnum(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedString = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeString(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedBytes = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeBytes(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedMessage = function (a, b, c) {
if (null != b) for (var d = 0; d < b.length; d++) {
var e = this.beginDelimited_(a);
c(b[d], this);
this.endDelimited_(e);
}
};
jspb.BinaryWriter.prototype.writeRepeatedGroup = function (a, b, c) {
if (null != b) for (var d = 0; d < b.length; d++) this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.START_GROUP), c(b[d], this), this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.END_GROUP);
};
jspb.BinaryWriter.prototype.writeRepeatedFixedHash64 = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeFixedHash64(a, b[c]);
};
jspb.BinaryWriter.prototype.writeRepeatedVarintHash64 = function (a, b) {
if (null != b) for (var c = 0; c < b.length; c++) this.writeVarintHash64(a, b[c]);
};
jspb.BinaryWriter.prototype.writePackedInt32 = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) this.encoder_.writeSignedVarint32(b[c]);
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedInt32String = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) this.encoder_.writeSignedVarint32(parseInt(b[c], 10));
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedInt64 = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) this.encoder_.writeSignedVarint64(b[c]);
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedSplitFixed64 = function (a, b, c, d) {
if (null != b) {
a = this.beginDelimited_(a);
for (var e = 0; e < b.length; e++) this.encoder_.writeSplitFixed64(c(b[e]), d(b[e]));
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedSplitVarint64 = function (a, b, c, d) {
if (null != b) {
a = this.beginDelimited_(a);
for (var e = 0; e < b.length; e++) this.encoder_.writeSplitVarint64(c(b[e]), d(b[e]));
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedSplitZigzagVarint64 = function (a, b, c, d) {
if (null != b) {
a = this.beginDelimited_(a);
for (var e = this.encoder_, f = 0; f < b.length; f++) jspb.utils.toZigzag64(c(b[f]), d(b[f]), function (a, b) {
e.writeSplitVarint64(a >>> 0, b >>> 0);
});
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedInt64String = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) {
var d = jspb.arith.Int64.fromString(b[c]);
this.encoder_.writeSplitVarint64(d.lo, d.hi);
}
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedUint32 = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) this.encoder_.writeUnsignedVarint32(b[c]);
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedUint32String = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) this.encoder_.writeUnsignedVarint32(parseInt(b[c], 10));
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedUint64 = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) this.encoder_.writeUnsignedVarint64(b[c]);
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedUint64String = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) {
var d = jspb.arith.UInt64.fromString(b[c]);
this.encoder_.writeSplitVarint64(d.lo, d.hi);
}
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedSint32 = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) this.encoder_.writeZigzagVarint32(b[c]);
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedSint64 = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) this.encoder_.writeZigzagVarint64(b[c]);
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedSint64String = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) this.encoder_.writeZigzagVarintHash64(jspb.utils.decimalStringToHash64(b[c]));
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedSintHash64 = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) this.encoder_.writeZigzagVarintHash64(b[c]);
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedFixed32 = function (a, b) {
if (null != b && b.length) for (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.DELIMITED), this.encoder_.writeUnsignedVarint32(4 * b.length), a = 0; a < b.length; a++) this.encoder_.writeUint32(b[a]);
};
jspb.BinaryWriter.prototype.writePackedFixed64 = function (a, b) {
if (null != b && b.length) for (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.DELIMITED), this.encoder_.writeUnsignedVarint32(8 * b.length), a = 0; a < b.length; a++) this.encoder_.writeUint64(b[a]);
};
jspb.BinaryWriter.prototype.writePackedFixed64String = function (a, b) {
if (null != b && b.length) for (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.DELIMITED), this.encoder_.writeUnsignedVarint32(8 * b.length), a = 0; a < b.length; a++) {
var c = jspb.arith.UInt64.fromString(b[a]);
this.encoder_.writeSplitFixed64(c.lo, c.hi);
}
};
jspb.BinaryWriter.prototype.writePackedSfixed32 = function (a, b) {
if (null != b && b.length) for (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.DELIMITED), this.encoder_.writeUnsignedVarint32(4 * b.length), a = 0; a < b.length; a++) this.encoder_.writeInt32(b[a]);
};
jspb.BinaryWriter.prototype.writePackedSfixed64 = function (a, b) {
if (null != b && b.length) for (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.DELIMITED), this.encoder_.writeUnsignedVarint32(8 * b.length), a = 0; a < b.length; a++) this.encoder_.writeInt64(b[a]);
};
jspb.BinaryWriter.prototype.writePackedSfixed64String = function (a, b) {
if (null != b && b.length) for (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.DELIMITED), this.encoder_.writeUnsignedVarint32(8 * b.length), a = 0; a < b.length; a++) this.encoder_.writeInt64String(b[a]);
};
jspb.BinaryWriter.prototype.writePackedFloat = function (a, b) {
if (null != b && b.length) for (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.DELIMITED), this.encoder_.writeUnsignedVarint32(4 * b.length), a = 0; a < b.length; a++) this.encoder_.writeFloat(b[a]);
};
jspb.BinaryWriter.prototype.writePackedDouble = function (a, b) {
if (null != b && b.length) for (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.DELIMITED), this.encoder_.writeUnsignedVarint32(8 * b.length), a = 0; a < b.length; a++) this.encoder_.writeDouble(b[a]);
};
jspb.BinaryWriter.prototype.writePackedBool = function (a, b) {
if (null != b && b.length) for (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.DELIMITED), this.encoder_.writeUnsignedVarint32(b.length), a = 0; a < b.length; a++) this.encoder_.writeBool(b[a]);
};
jspb.BinaryWriter.prototype.writePackedEnum = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) this.encoder_.writeEnum(b[c]);
this.endDelimited_(a);
}
};
jspb.BinaryWriter.prototype.writePackedFixedHash64 = function (a, b) {
if (null != b && b.length) for (this.writeFieldHeader_(a, jspb.BinaryConstants.WireType.DELIMITED), this.encoder_.writeUnsignedVarint32(8 * b.length), a = 0; a < b.length; a++) this.encoder_.writeFixedHash64(b[a]);
};
jspb.BinaryWriter.prototype.writePackedVarintHash64 = function (a, b) {
if (null != b && b.length) {
a = this.beginDelimited_(a);
for (var c = 0; c < b.length; c++) this.encoder_.writeVarintHash64(b[c]);
this.endDelimited_(a);
}
};
jspb.Export = {};
exports.Map = jspb.Map;
exports.Message = jspb.Message;
exports.BinaryReader = jspb.BinaryReader;
exports.BinaryWriter = jspb.BinaryWriter;
exports.ExtensionFieldInfo = jspb.ExtensionFieldInfo;
exports.ExtensionFieldBinaryInfo = jspb.ExtensionFieldBinaryInfo;
exports.exportSymbol = goog.exportSymbol;
exports.inherits = goog.inherits;
exports.object = {
extend: goog.object.extend
};
exports.typeOf = goog.typeOf;
/***/ }),
/***/ "./node_modules/has-symbols/index.js":
/*!*******************************************!*\
!*** ./node_modules/has-symbols/index.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(/*! ./shams */ "./node_modules/has-symbols/shams.js");
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') {
return false;
}
if (typeof Symbol !== 'function') {
return false;
}
if (typeof origSymbol('foo') !== 'symbol') {
return false;
}
if (typeof Symbol('bar') !== 'symbol') {
return false;
}
return hasSymbolSham();
};
/***/ }),
/***/ "./node_modules/has-symbols/shams.js":
/*!*******************************************!*\
!*** ./node_modules/has-symbols/shams.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') {
return false;
}
if (typeof Symbol.iterator === 'symbol') {
return true;
}
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') {
return false;
}
if (Object.prototype.toString.call(sym) !== '[object Symbol]') {
return false;
}
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') {
return false;
} // temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) {
return false;
} // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) {
return false;
}
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) {
return false;
}
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) {
return false;
}
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) {
return false;
}
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) {
return false;
}
}
return true;
};
/***/ }),
/***/ "./node_modules/has/src/index.js":
/*!***************************************!*\
!*** ./node_modules/has/src/index.js ***!
\***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(/*! function-bind */ "./node_modules/function-bind/index.js");
module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
/***/ }),
/***/ "./node_modules/is-arguments/index.js":
/*!********************************************!*\
!*** ./node_modules/is-arguments/index.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var $toString = callBound('Object.prototype.toString');
var isStandardArguments = function isArguments(value) {
if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) {
return false;
}
return $toString(value) === '[object Arguments]';
};
var isLegacyArguments = function isArguments(value) {
if (isStandardArguments(value)) {
return true;
}
return value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && $toString(value) !== '[object Array]' && $toString(value.callee) === '[object Function]';
};
var supportsStandardArguments = function () {
return isStandardArguments(arguments);
}();
isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests
module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments;
/***/ }),
/***/ "./node_modules/is-bigint/index.js":
/*!*****************************************!*\
!*** ./node_modules/is-bigint/index.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
if (typeof BigInt === 'function') {
var bigIntValueOf = BigInt.prototype.valueOf;
var tryBigInt = function tryBigIntObject(value) {
try {
bigIntValueOf.call(value);
return true;
} catch (e) {}
return false;
};
module.exports = function isBigInt(value) {
if (value === null || typeof value === 'undefined' || typeof value === 'boolean' || typeof value === 'string' || typeof value === 'number' || typeof value === 'symbol' || typeof value === 'function') {
return false;
}
if (typeof value === 'bigint') {
return true;
}
return tryBigInt(value);
};
} else {
module.exports = function isBigInt(value) {
return false && false;
};
}
/***/ }),
/***/ "./node_modules/is-boolean-object/index.js":
/*!*************************************************!*\
!*** ./node_modules/is-boolean-object/index.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var $boolToStr = callBound('Boolean.prototype.toString');
var $toString = callBound('Object.prototype.toString');
var tryBooleanObject = function booleanBrandCheck(value) {
try {
$boolToStr(value);
return true;
} catch (e) {
return false;
}
};
var boolClass = '[object Boolean]';
var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag;
module.exports = function isBoolean(value) {
if (typeof value === 'boolean') {
return true;
}
if (value === null || typeof value !== 'object') {
return false;
}
return hasToStringTag && Symbol.toStringTag in value ? tryBooleanObject(value) : $toString(value) === boolClass;
};
/***/ }),
/***/ "./node_modules/is-buffer/index.js":
/*!*****************************************!*\
!*** ./node_modules/is-buffer/index.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {
/*!
* Determine if an object is a Buffer
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
module.exports = function (obj) {
return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer);
};
function isBuffer(obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj);
} // For Node v0.10 support. Remove this eventually.
function isSlowBuffer(obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0));
}
/***/ }),
/***/ "./node_modules/is-callable/index.js":
/*!*******************************************!*\
!*** ./node_modules/is-callable/index.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var fnToStr = Function.prototype.toString;
var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;
var badArrayLike;
var isCallableMarker;
if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {
try {
badArrayLike = Object.defineProperty({}, 'length', {
get: function () {
throw isCallableMarker;
}
});
isCallableMarker = {}; // eslint-disable-next-line no-throw-literal
reflectApply(function () {
throw 42;
}, null, badArrayLike);
} catch (_) {
if (_ !== isCallableMarker) {
reflectApply = null;
}
}
} else {
reflectApply = null;
}
var constructorRegex = /^\s*class\b/;
var isES6ClassFn = function isES6ClassFunction(value) {
try {
var fnStr = fnToStr.call(value);
return constructorRegex.test(fnStr);
} catch (e) {
return false; // not a function
}
};
var tryFunctionObject = function tryFunctionToStr(value) {
try {
if (isES6ClassFn(value)) {
return false;
}
fnToStr.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var fnClass = '[object Function]';
var genClass = '[object GeneratorFunction]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
/* globals document: false */
var documentDotAll = typeof document === 'object' && typeof document.all === 'undefined' && document.all !== undefined ? document.all : {};
module.exports = reflectApply ? function isCallable(value) {
if (value === documentDotAll) {
return true;
}
if (!value) {
return false;
}
if (typeof value !== 'function' && typeof value !== 'object') {
return false;
}
if (typeof value === 'function' && !value.prototype) {
return true;
}
try {
reflectApply(value, null, badArrayLike);
} catch (e) {
if (e !== isCallableMarker) {
return false;
}
}
return !isES6ClassFn(value);
} : function isCallable(value) {
if (value === documentDotAll) {
return true;
}
if (!value) {
return false;
}
if (typeof value !== 'function' && typeof value !== 'object') {
return false;
}
if (typeof value === 'function' && !value.prototype) {
return true;
}
if (hasToStringTag) {
return tryFunctionObject(value);
}
if (isES6ClassFn(value)) {
return false;
}
var strClass = toStr.call(value);
return strClass === fnClass || strClass === genClass;
};
/***/ }),
/***/ "./node_modules/is-date-object/index.js":
/*!**********************************************!*\
!*** ./node_modules/is-date-object/index.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var getDay = Date.prototype.getDay;
var tryDateObject = function tryDateGetDayCall(value) {
try {
getDay.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var dateClass = '[object Date]';
var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag;
module.exports = function isDateObject(value) {
if (typeof value !== 'object' || value === null) {
return false;
}
return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass;
};
/***/ }),
/***/ "./node_modules/is-map/index.js":
/*!**************************************!*\
!*** ./node_modules/is-map/index.js ***!
\**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $Map = typeof Map === 'function' && Map.prototype ? Map : null;
var $Set = typeof Set === 'function' && Set.prototype ? Set : null;
var exported;
if (!$Map) {
// eslint-disable-next-line no-unused-vars
exported = function isMap(x) {
// `Map` is not present in this environment.
return false;
};
}
var $mapHas = $Map ? Map.prototype.has : null;
var $setHas = $Set ? Set.prototype.has : null;
if (!exported && !$mapHas) {
// eslint-disable-next-line no-unused-vars
exported = function isMap(x) {
// `Map` does not have a `has` method
return false;
};
}
module.exports = exported || function isMap(x) {
if (!x || typeof x !== 'object') {
return false;
}
try {
$mapHas.call(x);
if ($setHas) {
try {
$setHas.call(x);
} catch (e) {
return true;
}
}
return x instanceof $Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
};
/***/ }),
/***/ "./node_modules/is-number-object/index.js":
/*!************************************************!*\
!*** ./node_modules/is-number-object/index.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var numToStr = Number.prototype.toString;
var tryNumberObject = function tryNumberObject(value) {
try {
numToStr.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var numClass = '[object Number]';
var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag;
module.exports = function isNumberObject(value) {
if (typeof value === 'number') {
return true;
}
if (typeof value !== 'object') {
return false;
}
return hasToStringTag ? tryNumberObject(value) : toStr.call(value) === numClass;
};
/***/ }),
/***/ "./node_modules/is-regex/index.js":
/*!****************************************!*\
!*** ./node_modules/is-regex/index.js ***!
\****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var hasSymbols = __webpack_require__(/*! has-symbols/shams */ "./node_modules/has-symbols/shams.js")();
var hasToStringTag = hasSymbols && !!Symbol.toStringTag;
var has;
var $exec;
var isRegexMarker;
var badStringifier;
if (hasToStringTag) {
has = callBound('Object.prototype.hasOwnProperty');
$exec = callBound('RegExp.prototype.exec');
isRegexMarker = {};
var throwRegexMarker = function () {
throw isRegexMarker;
};
badStringifier = {
toString: throwRegexMarker,
valueOf: throwRegexMarker
};
if (typeof Symbol.toPrimitive === 'symbol') {
badStringifier[Symbol.toPrimitive] = throwRegexMarker;
}
}
var $toString = callBound('Object.prototype.toString');
var gOPD = Object.getOwnPropertyDescriptor;
var regexClass = '[object RegExp]';
module.exports = hasToStringTag // eslint-disable-next-line consistent-return
? function isRegex(value) {
if (!value || typeof value !== 'object') {
return false;
}
var descriptor = gOPD(value, 'lastIndex');
var hasLastIndexDataProperty = descriptor && has(descriptor, 'value');
if (!hasLastIndexDataProperty) {
return false;
}
try {
$exec(value, badStringifier);
} catch (e) {
return e === isRegexMarker;
}
} : function isRegex(value) {
// In older browsers, typeof regex incorrectly returns 'function'
if (!value || typeof value !== 'object' && typeof value !== 'function') {
return false;
}
return $toString(value) === regexClass;
};
/***/ }),
/***/ "./node_modules/is-set/index.js":
/*!**************************************!*\
!*** ./node_modules/is-set/index.js ***!
\**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $Map = typeof Map === 'function' && Map.prototype ? Map : null;
var $Set = typeof Set === 'function' && Set.prototype ? Set : null;
var exported;
if (!$Set) {
// eslint-disable-next-line no-unused-vars
exported = function isSet(x) {
// `Set` is not present in this environment.
return false;
};
}
var $mapHas = $Map ? Map.prototype.has : null;
var $setHas = $Set ? Set.prototype.has : null;
if (!exported && !$setHas) {
// eslint-disable-next-line no-unused-vars
exported = function isSet(x) {
// `Set` does not have a `has` method
return false;
};
}
module.exports = exported || function isSet(x) {
if (!x || typeof x !== 'object') {
return false;
}
try {
$setHas.call(x);
if ($mapHas) {
try {
$mapHas.call(x);
} catch (e) {
return true;
}
}
return x instanceof $Set; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
};
/***/ }),
/***/ "./node_modules/is-string/index.js":
/*!*****************************************!*\
!*** ./node_modules/is-string/index.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var strValue = String.prototype.valueOf;
var tryStringObject = function tryStringObject(value) {
try {
strValue.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var strClass = '[object String]';
var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag;
module.exports = function isString(value) {
if (typeof value === 'string') {
return true;
}
if (typeof value !== 'object') {
return false;
}
return hasToStringTag ? tryStringObject(value) : toStr.call(value) === strClass;
};
/***/ }),
/***/ "./node_modules/is-symbol/index.js":
/*!*****************************************!*\
!*** ./node_modules/is-symbol/index.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toStr = Object.prototype.toString;
var hasSymbols = __webpack_require__(/*! has-symbols */ "./node_modules/has-symbols/index.js")();
if (hasSymbols) {
var symToStr = Symbol.prototype.toString;
var symStringRegex = /^Symbol\(.*\)$/;
var isSymbolObject = function isRealSymbolObject(value) {
if (typeof value.valueOf() !== 'symbol') {
return false;
}
return symStringRegex.test(symToStr.call(value));
};
module.exports = function isSymbol(value) {
if (typeof value === 'symbol') {
return true;
}
if (toStr.call(value) !== '[object Symbol]') {
return false;
}
try {
return isSymbolObject(value);
} catch (e) {
return false;
}
};
} else {
module.exports = function isSymbol(value) {
// this environment does not support Symbols.
return false && false;
};
}
/***/ }),
/***/ "./node_modules/is-typed-array/index.js":
/*!**********************************************!*\
!*** ./node_modules/is-typed-array/index.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(/*! foreach */ "./node_modules/foreach/index.js");
var availableTypedArrays = __webpack_require__(/*! available-typed-arrays */ "./node_modules/available-typed-arrays/index.js");
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var $toString = callBound('Object.prototype.toString');
var hasSymbols = __webpack_require__(/*! has-symbols */ "./node_modules/has-symbols/index.js")();
var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol';
var typedArrays = availableTypedArrays();
var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {
for (var i = 0; i < array.length; i += 1) {
if (array[i] === value) {
return i;
}
}
return -1;
};
var $slice = callBound('String.prototype.slice');
var toStrTags = {};
var gOPD = __webpack_require__(/*! es-abstract/helpers/getOwnPropertyDescriptor */ "./node_modules/es-abstract/helpers/getOwnPropertyDescriptor.js");
var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');
if (hasToStringTag && gOPD && getPrototypeOf) {
forEach(typedArrays, function (typedArray) {
var arr = new global[typedArray]();
if (!(Symbol.toStringTag in arr)) {
throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.');
}
var proto = getPrototypeOf(arr);
var descriptor = gOPD(proto, Symbol.toStringTag);
if (!descriptor) {
var superProto = getPrototypeOf(proto);
descriptor = gOPD(superProto, Symbol.toStringTag);
}
toStrTags[typedArray] = descriptor.get;
});
}
var tryTypedArrays = function tryAllTypedArrays(value) {
var anyTrue = false;
forEach(toStrTags, function (getter, typedArray) {
if (!anyTrue) {
try {
anyTrue = getter.call(value) === typedArray;
} catch (e) {
/**/
}
}
});
return anyTrue;
};
module.exports = function isTypedArray(value) {
if (!value || typeof value !== 'object') {
return false;
}
if (!hasToStringTag) {
var tag = $slice($toString(value), 8, -1);
return $indexOf(typedArrays, tag) > -1;
}
if (!gOPD) {
return false;
}
return tryTypedArrays(value);
};
/***/ }),
/***/ "./node_modules/is-weakmap/index.js":
/*!******************************************!*\
!*** ./node_modules/is-weakmap/index.js ***!
\******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $WeakMap = typeof WeakMap === 'function' && WeakMap.prototype ? WeakMap : null;
var $WeakSet = typeof WeakSet === 'function' && WeakSet.prototype ? WeakSet : null;
var exported;
if (!$WeakMap) {
// eslint-disable-next-line no-unused-vars
exported = function isWeakMap(x) {
// `WeakMap` is not present in this environment.
return false;
};
}
var $mapHas = $WeakMap ? $WeakMap.prototype.has : null;
var $setHas = $WeakSet ? $WeakSet.prototype.has : null;
if (!exported && !$mapHas) {
// eslint-disable-next-line no-unused-vars
exported = function isWeakMap(x) {
// `WeakMap` does not have a `has` method
return false;
};
}
module.exports = exported || function isWeakMap(x) {
if (!x || typeof x !== 'object') {
return false;
}
try {
$mapHas.call(x, $mapHas);
if ($setHas) {
try {
$setHas.call(x, $setHas);
} catch (e) {
return true;
}
}
return x instanceof $WeakMap; // core-js workaround, pre-v3
} catch (e) {}
return false;
};
/***/ }),
/***/ "./node_modules/is-weakset/index.js":
/*!******************************************!*\
!*** ./node_modules/is-weakset/index.js ***!
\******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $WeakMap = typeof WeakMap === 'function' && WeakMap.prototype ? WeakMap : null;
var $WeakSet = typeof WeakSet === 'function' && WeakSet.prototype ? WeakSet : null;
var exported;
if (!$WeakMap) {
// eslint-disable-next-line no-unused-vars
exported = function isWeakSet(x) {
// `WeakSet` is not present in this environment.
return false;
};
}
var $mapHas = $WeakMap ? $WeakMap.prototype.has : null;
var $setHas = $WeakSet ? $WeakSet.prototype.has : null;
if (!exported && !$setHas) {
// eslint-disable-next-line no-unused-vars
module.exports = function isWeakSet(x) {
// `WeakSet` does not have a `has` method
return false;
};
}
module.exports = exported || function isWeakSet(x) {
if (!x || typeof x !== 'object') {
return false;
}
try {
$setHas.call(x, $setHas);
if ($mapHas) {
try {
$mapHas.call(x, $mapHas);
} catch (e) {
return true;
}
}
return x instanceof $WeakSet; // core-js workaround, pre-v3
} catch (e) {}
return false;
};
/***/ }),
/***/ "./node_modules/locale-currency/index.js":
/*!***********************************************!*\
!*** ./node_modules/locale-currency/index.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var map = __webpack_require__(/*! ./map */ "./node_modules/locale-currency/map.js");
var getCountryCode = function (localeString) {
var components = localeString.split("_");
if (components.length == 2) {
return components.pop();
}
components = localeString.split("-");
if (components.length == 2) {
return components.pop();
}
return localeString;
};
exports.getCurrency = function (locale) {
var countryCode = getCountryCode(locale).toUpperCase();
if (countryCode in map) {
return map[countryCode];
}
return null;
};
exports.getLocales = function (currencyCode) {
currencyCode = currencyCode.toUpperCase();
var locales = [];
for (countryCode in map) {
if (map[countryCode] === currencyCode) {
locales.push(countryCode);
}
}
return locales;
};
/***/ }),
/***/ "./node_modules/locale-currency/map.js":
/*!*********************************************!*\
!*** ./node_modules/locale-currency/map.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {
// Generated using ShowCurrencies.java
var map = {
AD: 'EUR',
AE: 'AED',
AF: 'AFN',
AG: 'XCD',
AI: 'XCD',
AL: 'ALL',
AM: 'AMD',
AN: 'ANG',
AO: 'AOA',
AR: 'ARS',
AS: 'USD',
AT: 'EUR',
AU: 'AUD',
AW: 'AWG',
AX: 'EUR',
AZ: 'AZN',
BA: 'BAM',
BB: 'BBD',
BD: 'BDT',
BE: 'EUR',
BF: 'XOF',
BG: 'BGN',
BH: 'BHD',
BI: 'BIF',
BJ: 'XOF',
BL: 'EUR',
BM: 'BMD',
BN: 'BND',
BO: 'BOB',
BQ: 'USD',
BR: 'BRL',
BS: 'BSD',
BT: 'BTN',
BV: 'NOK',
BW: 'BWP',
BY: 'BYR',
BZ: 'BZD',
CA: 'CAD',
CC: 'AUD',
CD: 'CDF',
CF: 'XAF',
CG: 'XAF',
CH: 'CHF',
CI: 'XOF',
CK: 'NZD',
CL: 'CLP',
CM: 'XAF',
CN: 'CNY',
CO: 'COP',
CR: 'CRC',
CU: 'CUP',
CV: 'CVE',
CW: 'ANG',
CX: 'AUD',
CY: 'EUR',
CZ: 'CZK',
DE: 'EUR',
DJ: 'DJF',
DK: 'DKK',
DM: 'XCD',
DO: 'DOP',
DZ: 'DZD',
EC: 'USD',
EE: 'EUR',
EG: 'EGP',
EH: 'MAD',
ER: 'ERN',
ES: 'EUR',
ET: 'ETB',
FI: 'EUR',
FJ: 'FJD',
FK: 'FKP',
FM: 'USD',
FO: 'DKK',
FR: 'EUR',
GA: 'XAF',
GB: 'GBP',
GD: 'XCD',
GE: 'GEL',
GF: 'EUR',
GG: 'GBP',
GH: 'GHS',
GI: 'GIP',
GL: 'DKK',
GM: 'GMD',
GN: 'GNF',
GP: 'EUR',
GQ: 'XAF',
GR: 'EUR',
GS: 'GBP',
GT: 'GTQ',
GU: 'USD',
GW: 'XOF',
GY: 'GYD',
HK: 'HKD',
HM: 'AUD',
HN: 'HNL',
HR: 'HRK',
HT: 'HTG',
HU: 'HUF',
ID: 'IDR',
IE: 'EUR',
IL: 'ILS',
IM: 'GBP',
IN: 'INR',
IO: 'USD',
IQ: 'IQD',
IR: 'IRR',
IS: 'ISK',
IT: 'EUR',
JE: 'GBP',
JM: 'JMD',
JO: 'JOD',
JP: 'JPY',
KE: 'KES',
KG: 'KGS',
KH: 'KHR',
KI: 'AUD',
KM: 'KMF',
KN: 'XCD',
KP: 'KPW',
KR: 'KRW',
KW: 'KWD',
KY: 'KYD',
KZ: 'KZT',
LA: 'LAK',
LB: 'LBP',
LC: 'XCD',
LI: 'CHF',
LK: 'LKR',
LR: 'LRD',
LS: 'LSL',
LT: 'LTL',
LU: 'EUR',
LV: 'LVL',
LY: 'LYD',
MA: 'MAD',
MC: 'EUR',
MD: 'MDL',
ME: 'EUR',
MF: 'EUR',
MG: 'MGA',
MH: 'USD',
MK: 'MKD',
ML: 'XOF',
MM: 'MMK',
MN: 'MNT',
MO: 'MOP',
MP: 'USD',
MQ: 'EUR',
MR: 'MRO',
MS: 'XCD',
MT: 'EUR',
MU: 'MUR',
MV: 'MVR',
MW: 'MWK',
MX: 'MXN',
MY: 'MYR',
MZ: 'MZN',
NA: 'NAD',
NC: 'XPF',
NE: 'XOF',
NF: 'AUD',
NG: 'NGN',
NI: 'NIO',
NL: 'EUR',
NO: 'NOK',
NP: 'NPR',
NR: 'AUD',
NU: 'NZD',
NZ: 'NZD',
OM: 'OMR',
PA: 'PAB',
PE: 'PEN',
PF: 'XPF',
PG: 'PGK',
PH: 'PHP',
PK: 'PKR',
PL: 'PLN',
PM: 'EUR',
PN: 'NZD',
PR: 'USD',
PS: 'ILS',
PT: 'EUR',
PW: 'USD',
PY: 'PYG',
QA: 'QAR',
RE: 'EUR',
RO: 'RON',
RS: 'RSD',
RU: 'RUB',
RW: 'RWF',
SA: 'SAR',
SB: 'SBD',
SC: 'SCR',
SD: 'SDG',
SE: 'SEK',
SG: 'SGD',
SH: 'SHP',
SI: 'EUR',
SJ: 'NOK',
SK: 'EUR',
SL: 'SLL',
SM: 'EUR',
SN: 'XOF',
SO: 'SOS',
SR: 'SRD',
ST: 'STD',
SV: 'SVC',
SX: 'ANG',
SY: 'SYP',
SZ: 'SZL',
TC: 'USD',
TD: 'XAF',
TF: 'EUR',
TG: 'XOF',
TH: 'THB',
TJ: 'TJS',
TK: 'NZD',
TL: 'USD',
TM: 'TMT',
TN: 'TND',
TO: 'TOP',
TR: 'TRY',
TT: 'TTD',
TV: 'AUD',
TW: 'TWD',
TZ: 'TZS',
UA: 'UAH',
UG: 'UGX',
UM: 'USD',
US: 'USD',
UY: 'UYU',
UZ: 'UZS',
VA: 'EUR',
VC: 'XCD',
VE: 'VEF',
VG: 'USD',
VI: 'USD',
VN: 'VND',
VU: 'VUV',
WF: 'XPF',
WS: 'WST',
YE: 'YER',
YT: 'EUR',
ZA: 'ZAR',
ZM: 'ZMK',
ZW: 'ZWL'
};
module.exports = map;
/***/ }),
/***/ "./node_modules/md5/md5.js":
/*!*********************************!*\
!*** ./node_modules/md5/md5.js ***!
\*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
(function () {
var crypt = __webpack_require__(/*! crypt */ "./node_modules/crypt/crypt.js"),
utf8 = __webpack_require__(/*! charenc */ "./node_modules/charenc/charenc.js").utf8,
isBuffer = __webpack_require__(/*! is-buffer */ "./node_modules/is-buffer/index.js"),
bin = __webpack_require__(/*! charenc */ "./node_modules/charenc/charenc.js").bin,
// The core
md5 = function (message, options) {
// Convert to byte array
if (message.constructor == String) {
if (options && options.encoding === 'binary') message = bin.stringToBytes(message);else message = utf8.stringToBytes(message);
} else if (isBuffer(message)) message = Array.prototype.slice.call(message, 0);else if (!Array.isArray(message) && message.constructor !== Uint8Array) message = message.toString(); // else, assume byte array already
var m = crypt.bytesToWords(message),
l = message.length * 8,
a = 1732584193,
b = -271733879,
c = -1732584194,
d = 271733878; // Swap endian
for (var i = 0; i < m.length; i++) {
m[i] = (m[i] << 8 | m[i] >>> 24) & 0x00FF00FF | (m[i] << 24 | m[i] >>> 8) & 0xFF00FF00;
} // Padding
m[l >>> 5] |= 0x80 << l % 32;
m[(l + 64 >>> 9 << 4) + 14] = l; // Method shortcuts
var FF = md5._ff,
GG = md5._gg,
HH = md5._hh,
II = md5._ii;
for (var i = 0; i < m.length; i += 16) {
var aa = a,
bb = b,
cc = c,
dd = d;
a = FF(a, b, c, d, m[i + 0], 7, -680876936);
d = FF(d, a, b, c, m[i + 1], 12, -389564586);
c = FF(c, d, a, b, m[i + 2], 17, 606105819);
b = FF(b, c, d, a, m[i + 3], 22, -1044525330);
a = FF(a, b, c, d, m[i + 4], 7, -176418897);
d = FF(d, a, b, c, m[i + 5], 12, 1200080426);
c = FF(c, d, a, b, m[i + 6], 17, -1473231341);
b = FF(b, c, d, a, m[i + 7], 22, -45705983);
a = FF(a, b, c, d, m[i + 8], 7, 1770035416);
d = FF(d, a, b, c, m[i + 9], 12, -1958414417);
c = FF(c, d, a, b, m[i + 10], 17, -42063);
b = FF(b, c, d, a, m[i + 11], 22, -1990404162);
a = FF(a, b, c, d, m[i + 12], 7, 1804603682);
d = FF(d, a, b, c, m[i + 13], 12, -40341101);
c = FF(c, d, a, b, m[i + 14], 17, -1502002290);
b = FF(b, c, d, a, m[i + 15], 22, 1236535329);
a = GG(a, b, c, d, m[i + 1], 5, -165796510);
d = GG(d, a, b, c, m[i + 6], 9, -1069501632);
c = GG(c, d, a, b, m[i + 11], 14, 643717713);
b = GG(b, c, d, a, m[i + 0], 20, -373897302);
a = GG(a, b, c, d, m[i + 5], 5, -701558691);
d = GG(d, a, b, c, m[i + 10], 9, 38016083);
c = GG(c, d, a, b, m[i + 15], 14, -660478335);
b = GG(b, c, d, a, m[i + 4], 20, -405537848);
a = GG(a, b, c, d, m[i + 9], 5, 568446438);
d = GG(d, a, b, c, m[i + 14], 9, -1019803690);
c = GG(c, d, a, b, m[i + 3], 14, -187363961);
b = GG(b, c, d, a, m[i + 8], 20, 1163531501);
a = GG(a, b, c, d, m[i + 13], 5, -1444681467);
d = GG(d, a, b, c, m[i + 2], 9, -51403784);
c = GG(c, d, a, b, m[i + 7], 14, 1735328473);
b = GG(b, c, d, a, m[i + 12], 20, -1926607734);
a = HH(a, b, c, d, m[i + 5], 4, -378558);
d = HH(d, a, b, c, m[i + 8], 11, -2022574463);
c = HH(c, d, a, b, m[i + 11], 16, 1839030562);
b = HH(b, c, d, a, m[i + 14], 23, -35309556);
a = HH(a, b, c, d, m[i + 1], 4, -1530992060);
d = HH(d, a, b, c, m[i + 4], 11, 1272893353);
c = HH(c, d, a, b, m[i + 7], 16, -155497632);
b = HH(b, c, d, a, m[i + 10], 23, -1094730640);
a = HH(a, b, c, d, m[i + 13], 4, 681279174);
d = HH(d, a, b, c, m[i + 0], 11, -358537222);
c = HH(c, d, a, b, m[i + 3], 16, -722521979);
b = HH(b, c, d, a, m[i + 6], 23, 76029189);
a = HH(a, b, c, d, m[i + 9], 4, -640364487);
d = HH(d, a, b, c, m[i + 12], 11, -421815835);
c = HH(c, d, a, b, m[i + 15], 16, 530742520);
b = HH(b, c, d, a, m[i + 2], 23, -995338651);
a = II(a, b, c, d, m[i + 0], 6, -198630844);
d = II(d, a, b, c, m[i + 7], 10, 1126891415);
c = II(c, d, a, b, m[i + 14], 15, -1416354905);
b = II(b, c, d, a, m[i + 5], 21, -57434055);
a = II(a, b, c, d, m[i + 12], 6, 1700485571);
d = II(d, a, b, c, m[i + 3], 10, -1894986606);
c = II(c, d, a, b, m[i + 10], 15, -1051523);
b = II(b, c, d, a, m[i + 1], 21, -2054922799);
a = II(a, b, c, d, m[i + 8], 6, 1873313359);
d = II(d, a, b, c, m[i + 15], 10, -30611744);
c = II(c, d, a, b, m[i + 6], 15, -1560198380);
b = II(b, c, d, a, m[i + 13], 21, 1309151649);
a = II(a, b, c, d, m[i + 4], 6, -145523070);
d = II(d, a, b, c, m[i + 11], 10, -1120210379);
c = II(c, d, a, b, m[i + 2], 15, 718787259);
b = II(b, c, d, a, m[i + 9], 21, -343485551);
a = a + aa >>> 0;
b = b + bb >>> 0;
c = c + cc >>> 0;
d = d + dd >>> 0;
}
return crypt.endian([a, b, c, d]);
}; // Auxiliary functions
md5._ff = function (a, b, c, d, x, s, t) {
var n = a + (b & c | ~b & d) + (x >>> 0) + t;
return (n << s | n >>> 32 - s) + b;
};
md5._gg = function (a, b, c, d, x, s, t) {
var n = a + (b & d | c & ~d) + (x >>> 0) + t;
return (n << s | n >>> 32 - s) + b;
};
md5._hh = function (a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + (x >>> 0) + t;
return (n << s | n >>> 32 - s) + b;
};
md5._ii = function (a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;
return (n << s | n >>> 32 - s) + b;
}; // Package private blocksize
md5._blocksize = 16;
md5._digestsize = 16;
module.exports = function (message, options) {
if (message === undefined || message === null) throw new Error('Illegal argument ' + message);
var digestbytes = crypt.wordsToBytes(md5(message, options));
return options && options.asBytes ? digestbytes : options && options.asString ? bin.bytesToString(digestbytes) : crypt.bytesToHex(digestbytes);
};
})();
/***/ }),
/***/ "./node_modules/memoize-one/dist/memoize-one.esm.js":
/*!**********************************************************!*\
!*** ./node_modules/memoize-one/dist/memoize-one.esm.js ***!
\**********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
var simpleIsEqual = function simpleIsEqual(a, b) {
return a === b;
};
function index(resultFn) {
var isEqual = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : simpleIsEqual;
var lastThis = void 0;
var lastArgs = [];
var lastResult = void 0;
var calledOnce = false;
var isNewArgEqualToLast = function isNewArgEqualToLast(newArg, index) {
return isEqual(newArg, lastArgs[index]);
};
var result = function result() {
for (var _len = arguments.length, newArgs = Array(_len), _key = 0; _key < _len; _key++) {
newArgs[_key] = arguments[_key];
}
if (calledOnce && lastThis === this && newArgs.length === lastArgs.length && newArgs.every(isNewArgEqualToLast)) {
return lastResult;
}
calledOnce = true;
lastThis = this;
lastArgs = newArgs;
lastResult = resultFn.apply(this, newArgs);
return lastResult;
};
return result;
}
/* harmony default export */ __webpack_exports__["default"] = (index);
/***/ }),
/***/ "./node_modules/murmurhash/murmurhash.js":
/*!***********************************************!*\
!*** ./node_modules/murmurhash/murmurhash.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
(function () {
var _global = this;
/**
* JS Implementation of MurmurHash2
*
* @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
* @see http://github.com/garycourt/murmurhash-js
* @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
* @see http://sites.google.com/site/murmurhash/
*
* @param {string} str ASCII only
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
function MurmurHashV2(str, seed) {
var l = str.length,
h = seed ^ l,
i = 0,
k;
while (l >= 4) {
k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;
k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);
k ^= k >>> 24;
k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);
h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16) ^ k;
l -= 4;
++i;
}
switch (l) {
case 3:
h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2:
h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1:
h ^= str.charCodeAt(i) & 0xff;
h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
}
h ^= h >>> 13;
h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
h ^= h >>> 15;
return h >>> 0;
}
;
/**
* JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)
*
* @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
* @see http://github.com/garycourt/murmurhash-js
* @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
* @see http://sites.google.com/site/murmurhash/
*
* @param {string} key ASCII only
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
function MurmurHashV3(key, seed) {
var remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i;
remainder = key.length & 3; // key.length % 4
bytes = key.length - remainder;
h1 = seed;
c1 = 0xcc9e2d51;
c2 = 0x1b873593;
i = 0;
while (i < bytes) {
k1 = key.charCodeAt(i) & 0xff | (key.charCodeAt(++i) & 0xff) << 8 | (key.charCodeAt(++i) & 0xff) << 16 | (key.charCodeAt(++i) & 0xff) << 24;
++i;
k1 = (k1 & 0xffff) * c1 + (((k1 >>> 16) * c1 & 0xffff) << 16) & 0xffffffff;
k1 = k1 << 15 | k1 >>> 17;
k1 = (k1 & 0xffff) * c2 + (((k1 >>> 16) * c2 & 0xffff) << 16) & 0xffffffff;
h1 ^= k1;
h1 = h1 << 13 | h1 >>> 19;
h1b = (h1 & 0xffff) * 5 + (((h1 >>> 16) * 5 & 0xffff) << 16) & 0xffffffff;
h1 = (h1b & 0xffff) + 0x6b64 + (((h1b >>> 16) + 0xe654 & 0xffff) << 16);
}
k1 = 0;
switch (remainder) {
case 3:
k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
case 2:
k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
case 1:
k1 ^= key.charCodeAt(i) & 0xff;
k1 = (k1 & 0xffff) * c1 + (((k1 >>> 16) * c1 & 0xffff) << 16) & 0xffffffff;
k1 = k1 << 15 | k1 >>> 17;
k1 = (k1 & 0xffff) * c2 + (((k1 >>> 16) * c2 & 0xffff) << 16) & 0xffffffff;
h1 ^= k1;
}
h1 ^= key.length;
h1 ^= h1 >>> 16;
h1 = (h1 & 0xffff) * 0x85ebca6b + (((h1 >>> 16) * 0x85ebca6b & 0xffff) << 16) & 0xffffffff;
h1 ^= h1 >>> 13;
h1 = (h1 & 0xffff) * 0xc2b2ae35 + (((h1 >>> 16) * 0xc2b2ae35 & 0xffff) << 16) & 0xffffffff;
h1 ^= h1 >>> 16;
return h1 >>> 0;
}
var murmur = MurmurHashV3;
murmur.v2 = MurmurHashV2;
murmur.v3 = MurmurHashV3;
if (true) {
module.exports = murmur;
} else { var _previousRoot; }
})();
/***/ }),
/***/ "./node_modules/object-assign/index.js":
/*!*********************************************!*\
!*** ./node_modules/object-assign/index.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
} // Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
} // https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
} // https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/***/ }),
/***/ "./node_modules/object-inspect/index.js":
/*!**********************************************!*\
!*** ./node_modules/object-inspect/index.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;
var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var functionToString = Function.prototype.toString;
var match = String.prototype.match;
var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;
var gOPS = Object.getOwnPropertySymbols;
var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null;
var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object';
var isEnumerable = Object.prototype.propertyIsEnumerable;
var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype // eslint-disable-line no-proto
? function (O) {
return O.__proto__; // eslint-disable-line no-proto
} : null);
var inspectCustom = __webpack_require__(/*! ./util.inspect */ "./node_modules/object-inspect/util.inspect.js").custom;
var inspectSymbol = inspectCustom && isSymbol(inspectCustom) ? inspectCustom : null;
var toStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag !== 'undefined' ? Symbol.toStringTag : null;
module.exports = function inspect_(obj, options, depth, seen) {
var opts = options || {};
if (has(opts, 'quoteStyle') && opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double') {
throw new TypeError('option "quoteStyle" must be "single" or "double"');
}
if (has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) {
throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
}
var customInspect = has(opts, 'customInspect') ? opts.customInspect : true;
if (typeof customInspect !== 'boolean') {
throw new TypeError('option "customInspect", if provided, must be `true` or `false`');
}
if (has(opts, 'indent') && opts.indent !== null && opts.indent !== '\t' && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) {
throw new TypeError('options "indent" must be "\\t", an integer > 0, or `null`');
}
if (typeof obj === 'undefined') {
return 'undefined';
}
if (obj === null) {
return 'null';
}
if (typeof obj === 'boolean') {
return obj ? 'true' : 'false';
}
if (typeof obj === 'string') {
return inspectString(obj, opts);
}
if (typeof obj === 'number') {
if (obj === 0) {
return Infinity / obj > 0 ? '0' : '-0';
}
return String(obj);
}
if (typeof obj === 'bigint') {
return String(obj) + 'n';
}
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
if (typeof depth === 'undefined') {
depth = 0;
}
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
return isArray(obj) ? '[Array]' : '[Object]';
}
var indent = getIndent(opts, depth);
if (typeof seen === 'undefined') {
seen = [];
} else if (indexOf(seen, obj) >= 0) {
return '[Circular]';
}
function inspect(value, from, noIndent) {
if (from) {
seen = seen.slice();
seen.push(from);
}
if (noIndent) {
var newOpts = {
depth: opts.depth
};
if (has(opts, 'quoteStyle')) {
newOpts.quoteStyle = opts.quoteStyle;
}
return inspect_(value, newOpts, depth + 1, seen);
}
return inspect_(value, opts, depth + 1, seen);
}
if (typeof obj === 'function') {
var name = nameOf(obj);
var keys = arrObjKeys(obj, inspect);
return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + keys.join(', ') + ' }' : '');
}
if (isSymbol(obj)) {
var symString = hasShammedSymbols ? String(obj).replace(/^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj);
return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString;
}
if (isElement(obj)) {
var s = '<' + String(obj.nodeName).toLowerCase();
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
}
s += '>';
if (obj.childNodes && obj.childNodes.length) {
s += '...';
}
s += '</' + String(obj.nodeName).toLowerCase() + '>';
return s;
}
if (isArray(obj)) {
if (obj.length === 0) {
return '[]';
}
var xs = arrObjKeys(obj, inspect);
if (indent && !singleLineValues(xs)) {
return '[' + indentedJoin(xs, indent) + ']';
}
return '[ ' + xs.join(', ') + ' ]';
}
if (isError(obj)) {
var parts = arrObjKeys(obj, inspect);
if (parts.length === 0) {
return '[' + String(obj) + ']';
}
return '{ [' + String(obj) + '] ' + parts.join(', ') + ' }';
}
if (typeof obj === 'object' && customInspect) {
if (inspectSymbol && typeof obj[inspectSymbol] === 'function') {
return obj[inspectSymbol]();
} else if (typeof obj.inspect === 'function') {
return obj.inspect();
}
}
if (isMap(obj)) {
var mapParts = [];
mapForEach.call(obj, function (value, key) {
mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj));
});
return collectionOf('Map', mapSize.call(obj), mapParts, indent);
}
if (isSet(obj)) {
var setParts = [];
setForEach.call(obj, function (value) {
setParts.push(inspect(value, obj));
});
return collectionOf('Set', setSize.call(obj), setParts, indent);
}
if (isWeakMap(obj)) {
return weakCollectionOf('WeakMap');
}
if (isWeakSet(obj)) {
return weakCollectionOf('WeakSet');
}
if (isWeakRef(obj)) {
return weakCollectionOf('WeakRef');
}
if (isNumber(obj)) {
return markBoxed(inspect(Number(obj)));
}
if (isBigInt(obj)) {
return markBoxed(inspect(bigIntValueOf.call(obj)));
}
if (isBoolean(obj)) {
return markBoxed(booleanValueOf.call(obj));
}
if (isString(obj)) {
return markBoxed(inspect(String(obj)));
}
if (!isDate(obj) && !isRegExp(obj)) {
var ys = arrObjKeys(obj, inspect);
var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
var protoTag = obj instanceof Object ? '' : 'null prototype';
var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? toStr(obj).slice(8, -1) : protoTag ? 'Object' : '';
var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : '';
var tag = constructorTag + (stringTag || protoTag ? '[' + [].concat(stringTag || [], protoTag || []).join(': ') + '] ' : '');
if (ys.length === 0) {
return tag + '{}';
}
if (indent) {
return tag + '{' + indentedJoin(ys, indent) + '}';
}
return tag + '{ ' + ys.join(', ') + ' }';
}
return String(obj);
};
function wrapQuotes(s, defaultStyle, opts) {
var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
return quoteChar + s + quoteChar;
}
function quote(s) {
return String(s).replace(/"/g, '&quot;');
}
function isArray(obj) {
return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj));
}
function isDate(obj) {
return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj));
}
function isRegExp(obj) {
return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj));
}
function isError(obj) {
return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj));
}
function isString(obj) {
return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj));
}
function isNumber(obj) {
return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj));
}
function isBoolean(obj) {
return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj));
} // Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives
function isSymbol(obj) {
if (hasShammedSymbols) {
return obj && typeof obj === 'object' && obj instanceof Symbol;
}
if (typeof obj === 'symbol') {
return true;
}
if (!obj || typeof obj !== 'object' || !symToString) {
return false;
}
try {
symToString.call(obj);
return true;
} catch (e) {}
return false;
}
function isBigInt(obj) {
if (!obj || typeof obj !== 'object' || !bigIntValueOf) {
return false;
}
try {
bigIntValueOf.call(obj);
return true;
} catch (e) {}
return false;
}
var hasOwn = Object.prototype.hasOwnProperty || function (key) {
return key in this;
};
function has(obj, key) {
return hasOwn.call(obj, key);
}
function toStr(obj) {
return objectToString.call(obj);
}
function nameOf(f) {
if (f.name) {
return f.name;
}
var m = match.call(functionToString.call(f), /^function\s*([\w$]+)/);
if (m) {
return m[1];
}
return null;
}
function indexOf(xs, x) {
if (xs.indexOf) {
return xs.indexOf(x);
}
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) {
return i;
}
}
return -1;
}
function isMap(x) {
if (!mapSize || !x || typeof x !== 'object') {
return false;
}
try {
mapSize.call(x);
try {
setSize.call(x);
} catch (s) {
return true;
}
return x instanceof Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakMap(x) {
if (!weakMapHas || !x || typeof x !== 'object') {
return false;
}
try {
weakMapHas.call(x, weakMapHas);
try {
weakSetHas.call(x, weakSetHas);
} catch (s) {
return true;
}
return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakRef(x) {
if (!weakRefDeref || !x || typeof x !== 'object') {
return false;
}
try {
weakRefDeref.call(x);
return true;
} catch (e) {}
return false;
}
function isSet(x) {
if (!setSize || !x || typeof x !== 'object') {
return false;
}
try {
setSize.call(x);
try {
mapSize.call(x);
} catch (m) {
return true;
}
return x instanceof Set; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakSet(x) {
if (!weakSetHas || !x || typeof x !== 'object') {
return false;
}
try {
weakSetHas.call(x, weakSetHas);
try {
weakMapHas.call(x, weakMapHas);
} catch (s) {
return true;
}
return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isElement(x) {
if (!x || typeof x !== 'object') {
return false;
}
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
return true;
}
return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
}
function inspectString(str, opts) {
if (str.length > opts.maxStringLength) {
var remaining = str.length - opts.maxStringLength;
var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');
return inspectString(str.slice(0, opts.maxStringLength), opts) + trailer;
} // eslint-disable-next-line no-control-regex
var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
return wrapQuotes(s, 'single', opts);
}
function lowbyte(c) {
var n = c.charCodeAt(0);
var x = {
8: 'b',
9: 't',
10: 'n',
12: 'f',
13: 'r'
}[n];
if (x) {
return '\\' + x;
}
return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16).toUpperCase();
}
function markBoxed(str) {
return 'Object(' + str + ')';
}
function weakCollectionOf(type) {
return type + ' { ? }';
}
function collectionOf(type, size, entries, indent) {
var joinedEntries = indent ? indentedJoin(entries, indent) : entries.join(', ');
return type + ' (' + size + ') {' + joinedEntries + '}';
}
function singleLineValues(xs) {
for (var i = 0; i < xs.length; i++) {
if (indexOf(xs[i], '\n') >= 0) {
return false;
}
}
return true;
}
function getIndent(opts, depth) {
var baseIndent;
if (opts.indent === '\t') {
baseIndent = '\t';
} else if (typeof opts.indent === 'number' && opts.indent > 0) {
baseIndent = Array(opts.indent + 1).join(' ');
} else {
return null;
}
return {
base: baseIndent,
prev: Array(depth + 1).join(baseIndent)
};
}
function indentedJoin(xs, indent) {
if (xs.length === 0) {
return '';
}
var lineJoiner = '\n' + indent.prev + indent.base;
return lineJoiner + xs.join(',' + lineJoiner) + '\n' + indent.prev;
}
function arrObjKeys(obj, inspect) {
var isArr = isArray(obj);
var xs = [];
if (isArr) {
xs.length = obj.length;
for (var i = 0; i < obj.length; i++) {
xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
}
}
var syms = typeof gOPS === 'function' ? gOPS(obj) : [];
var symMap;
if (hasShammedSymbols) {
symMap = {};
for (var k = 0; k < syms.length; k++) {
symMap['$' + syms[k]] = syms[k];
}
}
for (var key in obj) {
// eslint-disable-line no-restricted-syntax
if (!has(obj, key)) {
continue;
} // eslint-disable-line no-restricted-syntax, no-continue
if (isArr && String(Number(key)) === key && key < obj.length) {
continue;
} // eslint-disable-line no-restricted-syntax, no-continue
if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) {
// this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section
continue; // eslint-disable-line no-restricted-syntax, no-continue
} else if (/[^\w$]/.test(key)) {
xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
} else {
xs.push(key + ': ' + inspect(obj[key], obj));
}
}
if (typeof gOPS === 'function') {
for (var j = 0; j < syms.length; j++) {
if (isEnumerable.call(obj, syms[j])) {
xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj));
}
}
}
return xs;
}
/***/ }),
/***/ "./node_modules/object-inspect/util.inspect.js":
/*!*****************************************************!*\
!*** ./node_modules/object-inspect/util.inspect.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! util */ "util").inspect;
/***/ }),
/***/ "./node_modules/object-is/implementation.js":
/*!**************************************************!*\
!*** ./node_modules/object-is/implementation.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var numberIsNaN = function (value) {
return value !== value;
};
module.exports = function is(a, b) {
if (a === 0 && b === 0) {
return 1 / a === 1 / b;
}
if (a === b) {
return true;
}
if (numberIsNaN(a) && numberIsNaN(b)) {
return true;
}
return false;
};
/***/ }),
/***/ "./node_modules/object-is/index.js":
/*!*****************************************!*\
!*** ./node_modules/object-is/index.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var define = __webpack_require__(/*! define-properties */ "./node_modules/define-properties/index.js");
var callBind = __webpack_require__(/*! call-bind */ "./node_modules/call-bind/index.js");
var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/object-is/implementation.js");
var getPolyfill = __webpack_require__(/*! ./polyfill */ "./node_modules/object-is/polyfill.js");
var shim = __webpack_require__(/*! ./shim */ "./node_modules/object-is/shim.js");
var polyfill = callBind(getPolyfill(), Object);
define(polyfill, {
getPolyfill: getPolyfill,
implementation: implementation,
shim: shim
});
module.exports = polyfill;
/***/ }),
/***/ "./node_modules/object-is/polyfill.js":
/*!********************************************!*\
!*** ./node_modules/object-is/polyfill.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/object-is/implementation.js");
module.exports = function getPolyfill() {
return typeof Object.is === 'function' ? Object.is : implementation;
};
/***/ }),
/***/ "./node_modules/object-is/shim.js":
/*!****************************************!*\
!*** ./node_modules/object-is/shim.js ***!
\****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var getPolyfill = __webpack_require__(/*! ./polyfill */ "./node_modules/object-is/polyfill.js");
var define = __webpack_require__(/*! define-properties */ "./node_modules/define-properties/index.js");
module.exports = function shimObjectIs() {
var polyfill = getPolyfill();
define(Object, {
is: polyfill
}, {
is: function testObjectIs() {
return Object.is !== polyfill;
}
});
return polyfill;
};
/***/ }),
/***/ "./node_modules/object-keys/implementation.js":
/*!****************************************************!*\
!*** ./node_modules/object-keys/implementation.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var keysShim;
if (!Object.keys) {
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var isArgs = __webpack_require__(/*! ./isArguments */ "./node_modules/object-keys/isArguments.js"); // eslint-disable-line global-require
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({
toString: null
}, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$applicationCache: true,
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$onmozfullscreenchange: true,
$onmozfullscreenerror: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = function () {
/* global window */
if (typeof window === 'undefined') {
return false;
}
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}();
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
}
module.exports = keysShim;
/***/ }),
/***/ "./node_modules/object-keys/index.js":
/*!*******************************************!*\
!*** ./node_modules/object-keys/index.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var slice = Array.prototype.slice;
var isArgs = __webpack_require__(/*! ./isArguments */ "./node_modules/object-keys/isArguments.js");
var origKeys = Object.keys;
var keysShim = origKeys ? function keys(o) {
return origKeys(o);
} : __webpack_require__(/*! ./implementation */ "./node_modules/object-keys/implementation.js");
var originalKeys = Object.keys;
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = function () {
// Safari 5.0 bug
var args = Object.keys(arguments);
return args && args.length === arguments.length;
}(1, 2);
if (!keysWorksWithArguments) {
Object.keys = function keys(object) {
// eslint-disable-line func-name-matching
if (isArgs(object)) {
return originalKeys(slice.call(object));
}
return originalKeys(object);
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
/***/ }),
/***/ "./node_modules/object-keys/isArguments.js":
/*!*************************************************!*\
!*** ./node_modules/object-keys/isArguments.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
/***/ }),
/***/ "./node_modules/object.assign/implementation.js":
/*!******************************************************!*\
!*** ./node_modules/object.assign/implementation.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// modified from https://github.com/es-shims/es6-shim
var keys = __webpack_require__(/*! object-keys */ "./node_modules/object-keys/index.js");
var canBeObject = function (obj) {
return typeof obj !== 'undefined' && obj !== null;
};
var hasSymbols = __webpack_require__(/*! has-symbols/shams */ "./node_modules/has-symbols/shams.js")();
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var toObject = Object;
var $push = callBound('Array.prototype.push');
var $propIsEnumerable = callBound('Object.prototype.propertyIsEnumerable');
var originalGetSymbols = hasSymbols ? Object.getOwnPropertySymbols : null; // eslint-disable-next-line no-unused-vars
module.exports = function assign(target, source1) {
if (!canBeObject(target)) {
throw new TypeError('target must be an object');
}
var objTarget = toObject(target);
var s, source, i, props, syms, value, key;
for (s = 1; s < arguments.length; ++s) {
source = toObject(arguments[s]);
props = keys(source);
var getSymbols = hasSymbols && (Object.getOwnPropertySymbols || originalGetSymbols);
if (getSymbols) {
syms = getSymbols(source);
for (i = 0; i < syms.length; ++i) {
key = syms[i];
if ($propIsEnumerable(source, key)) {
$push(props, key);
}
}
}
for (i = 0; i < props.length; ++i) {
key = props[i];
value = source[key];
if ($propIsEnumerable(source, key)) {
objTarget[key] = value;
}
}
}
return objTarget;
};
/***/ }),
/***/ "./node_modules/object.assign/index.js":
/*!*********************************************!*\
!*** ./node_modules/object.assign/index.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var defineProperties = __webpack_require__(/*! define-properties */ "./node_modules/define-properties/index.js");
var callBind = __webpack_require__(/*! call-bind */ "./node_modules/call-bind/index.js");
var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/object.assign/implementation.js");
var getPolyfill = __webpack_require__(/*! ./polyfill */ "./node_modules/object.assign/polyfill.js");
var shim = __webpack_require__(/*! ./shim */ "./node_modules/object.assign/shim.js");
var polyfill = callBind.apply(getPolyfill()); // eslint-disable-next-line no-unused-vars
var bound = function assign(target, source1) {
return polyfill(Object, arguments);
};
defineProperties(bound, {
getPolyfill: getPolyfill,
implementation: implementation,
shim: shim
});
module.exports = bound;
/***/ }),
/***/ "./node_modules/object.assign/polyfill.js":
/*!************************************************!*\
!*** ./node_modules/object.assign/polyfill.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/object.assign/implementation.js");
var lacksProperEnumerationOrder = function () {
if (!Object.assign) {
return false;
}
/*
* v8, specifically in node 4.x, has a bug with incorrect property enumeration order
* note: this does not detect the bug unless there's 20 characters
*/
var str = 'abcdefghijklmnopqrst';
var letters = str.split('');
var map = {};
for (var i = 0; i < letters.length; ++i) {
map[letters[i]] = letters[i];
}
var obj = Object.assign({}, map);
var actual = '';
for (var k in obj) {
actual += k;
}
return str !== actual;
};
var assignHasPendingExceptions = function () {
if (!Object.assign || !Object.preventExtensions) {
return false;
}
/*
* Firefox 37 still has "pending exception" logic in its Object.assign implementation,
* which is 72% slower than our shim, and Firefox 40's native implementation.
*/
var thrower = Object.preventExtensions({
1: 2
});
try {
Object.assign(thrower, 'xy');
} catch (e) {
return thrower[1] === 'y';
}
return false;
};
module.exports = function getPolyfill() {
if (!Object.assign) {
return implementation;
}
if (lacksProperEnumerationOrder()) {
return implementation;
}
if (assignHasPendingExceptions()) {
return implementation;
}
return Object.assign;
};
/***/ }),
/***/ "./node_modules/object.assign/shim.js":
/*!********************************************!*\
!*** ./node_modules/object.assign/shim.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var define = __webpack_require__(/*! define-properties */ "./node_modules/define-properties/index.js");
var getPolyfill = __webpack_require__(/*! ./polyfill */ "./node_modules/object.assign/polyfill.js");
module.exports = function shimAssign() {
var polyfill = getPolyfill();
define(Object, {
assign: polyfill
}, {
assign: function () {
return Object.assign !== polyfill;
}
});
return polyfill;
};
/***/ }),
/***/ "./node_modules/regexp.prototype.flags/implementation.js":
/*!***************************************************************!*\
!*** ./node_modules/regexp.prototype.flags/implementation.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $Object = Object;
var $TypeError = TypeError;
module.exports = function flags() {
if (this != null && this !== $Object(this)) {
throw new $TypeError('RegExp.prototype.flags getter called on non-object');
}
var result = '';
if (this.global) {
result += 'g';
}
if (this.ignoreCase) {
result += 'i';
}
if (this.multiline) {
result += 'm';
}
if (this.dotAll) {
result += 's';
}
if (this.unicode) {
result += 'u';
}
if (this.sticky) {
result += 'y';
}
return result;
};
/***/ }),
/***/ "./node_modules/regexp.prototype.flags/index.js":
/*!******************************************************!*\
!*** ./node_modules/regexp.prototype.flags/index.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var define = __webpack_require__(/*! define-properties */ "./node_modules/define-properties/index.js");
var callBind = __webpack_require__(/*! call-bind */ "./node_modules/call-bind/index.js");
var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/regexp.prototype.flags/implementation.js");
var getPolyfill = __webpack_require__(/*! ./polyfill */ "./node_modules/regexp.prototype.flags/polyfill.js");
var shim = __webpack_require__(/*! ./shim */ "./node_modules/regexp.prototype.flags/shim.js");
var flagsBound = callBind(implementation);
define(flagsBound, {
getPolyfill: getPolyfill,
implementation: implementation,
shim: shim
});
module.exports = flagsBound;
/***/ }),
/***/ "./node_modules/regexp.prototype.flags/polyfill.js":
/*!*********************************************************!*\
!*** ./node_modules/regexp.prototype.flags/polyfill.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/regexp.prototype.flags/implementation.js");
var supportsDescriptors = __webpack_require__(/*! define-properties */ "./node_modules/define-properties/index.js").supportsDescriptors;
var $gOPD = Object.getOwnPropertyDescriptor;
var $TypeError = TypeError;
module.exports = function getPolyfill() {
if (!supportsDescriptors) {
throw new $TypeError('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors');
}
if (/a/mig.flags === 'gim') {
var descriptor = $gOPD(RegExp.prototype, 'flags');
if (descriptor && typeof descriptor.get === 'function' && typeof /a/.dotAll === 'boolean') {
return descriptor.get;
}
}
return implementation;
};
/***/ }),
/***/ "./node_modules/regexp.prototype.flags/shim.js":
/*!*****************************************************!*\
!*** ./node_modules/regexp.prototype.flags/shim.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var supportsDescriptors = __webpack_require__(/*! define-properties */ "./node_modules/define-properties/index.js").supportsDescriptors;
var getPolyfill = __webpack_require__(/*! ./polyfill */ "./node_modules/regexp.prototype.flags/polyfill.js");
var gOPD = Object.getOwnPropertyDescriptor;
var defineProperty = Object.defineProperty;
var TypeErr = TypeError;
var getProto = Object.getPrototypeOf;
var regex = /a/;
module.exports = function shimFlags() {
if (!supportsDescriptors || !getProto) {
throw new TypeErr('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors');
}
var polyfill = getPolyfill();
var proto = getProto(regex);
var descriptor = gOPD(proto, 'flags');
if (!descriptor || descriptor.get !== polyfill) {
defineProperty(proto, 'flags', {
configurable: true,
enumerable: false,
get: polyfill
});
}
return polyfill;
};
/***/ }),
/***/ "./node_modules/side-channel/index.js":
/*!********************************************!*\
!*** ./node_modules/side-channel/index.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js");
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var inspect = __webpack_require__(/*! object-inspect */ "./node_modules/object-inspect/index.js");
var $TypeError = GetIntrinsic('%TypeError%');
var $WeakMap = GetIntrinsic('%WeakMap%', true);
var $Map = GetIntrinsic('%Map%', true);
var $weakMapGet = callBound('WeakMap.prototype.get', true);
var $weakMapSet = callBound('WeakMap.prototype.set', true);
var $weakMapHas = callBound('WeakMap.prototype.has', true);
var $mapGet = callBound('Map.prototype.get', true);
var $mapSet = callBound('Map.prototype.set', true);
var $mapHas = callBound('Map.prototype.has', true);
/*
* This function traverses the list returning the node corresponding to the
* given key.
*
* That node is also moved to the head of the list, so that if it's accessed
* again we don't need to traverse the whole list. By doing so, all the recently
* used nodes can be accessed relatively quickly.
*/
var listGetNode = function (list, key) {
// eslint-disable-line consistent-return
for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) {
if (curr.key === key) {
prev.next = curr.next;
curr.next = list.next;
list.next = curr; // eslint-disable-line no-param-reassign
return curr;
}
}
};
var listGet = function (objects, key) {
var node = listGetNode(objects, key);
return node && node.value;
};
var listSet = function (objects, key, value) {
var node = listGetNode(objects, key);
if (node) {
node.value = value;
} else {
// Prepend the new node to the beginning of the list
objects.next = {
// eslint-disable-line no-param-reassign
key: key,
next: objects.next,
value: value
};
}
};
var listHas = function (objects, key) {
return !!listGetNode(objects, key);
};
module.exports = function getSideChannel() {
var $wm;
var $m;
var $o;
var channel = {
assert: function (key) {
if (!channel.has(key)) {
throw new $TypeError('Side channel does not contain ' + inspect(key));
}
},
get: function (key) {
// eslint-disable-line consistent-return
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
if ($wm) {
return $weakMapGet($wm, key);
}
} else if ($Map) {
if ($m) {
return $mapGet($m, key);
}
} else {
if ($o) {
// eslint-disable-line no-lonely-if
return listGet($o, key);
}
}
},
has: function (key) {
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
if ($wm) {
return $weakMapHas($wm, key);
}
} else if ($Map) {
if ($m) {
return $mapHas($m, key);
}
} else {
if ($o) {
// eslint-disable-line no-lonely-if
return listHas($o, key);
}
}
return false;
},
set: function (key, value) {
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
if (!$wm) {
$wm = new $WeakMap();
}
$weakMapSet($wm, key, value);
} else if ($Map) {
if (!$m) {
$m = new $Map();
}
$mapSet($m, key, value);
} else {
if (!$o) {
/*
* Initialize the linked list as an empty node, so that we don't have
* to special-case handling of the first node: we can always refer to
* it as (previous node).next, instead of something like (list).head
*/
$o = {
key: {},
next: null
};
}
listSet($o, key, value);
}
}
};
return channel;
};
/***/ }),
/***/ "./node_modules/slash/index.js":
/*!*************************************!*\
!*** ./node_modules/slash/index.js ***!
\*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = path => {
const isExtendedLengthPath = /^\\\\\?\\/.test(path);
const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex
if (isExtendedLengthPath || hasNonAscii) {
return path;
}
return path.replace(/\\/g, '/');
};
/***/ }),
/***/ "./node_modules/uuid/index.js":
/*!************************************!*\
!*** ./node_modules/uuid/index.js ***!
\************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var v1 = __webpack_require__(/*! ./v1 */ "./node_modules/uuid/v1.js");
var v4 = __webpack_require__(/*! ./v4 */ "./node_modules/uuid/v4.js");
var uuid = v4;
uuid.v1 = v1;
uuid.v4 = v4;
module.exports = uuid;
/***/ }),
/***/ "./node_modules/uuid/lib/bytesToUuid.js":
/*!**********************************************!*\
!*** ./node_modules/uuid/lib/bytesToUuid.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
var byteToHex = [];
for (var i = 0; i < 256; ++i) {
byteToHex[i] = (i + 0x100).toString(16).substr(1);
}
function bytesToUuid(buf, offset) {
var i = offset || 0;
var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
return [bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]]].join('');
}
module.exports = bytesToUuid;
/***/ }),
/***/ "./node_modules/uuid/lib/rng.js":
/*!**************************************!*\
!*** ./node_modules/uuid/lib/rng.js ***!
\**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// Unique ID creation requires a high quality random # generator. In node.js
// this is pretty straight-forward - we use the crypto API.
var crypto = __webpack_require__(/*! crypto */ "crypto");
module.exports = function nodeRNG() {
return crypto.randomBytes(16);
};
/***/ }),
/***/ "./node_modules/uuid/v1.js":
/*!*********************************!*\
!*** ./node_modules/uuid/v1.js ***!
\*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var rng = __webpack_require__(/*! ./lib/rng */ "./node_modules/uuid/lib/rng.js");
var bytesToUuid = __webpack_require__(/*! ./lib/bytesToUuid */ "./node_modules/uuid/lib/bytesToUuid.js"); // **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
var _nodeId;
var _clockseq; // Previous uuid creation time
var _lastMSecs = 0;
var _lastNSecs = 0; // See https://github.com/broofa/node-uuid for API details
function v1(options, buf, offset) {
var i = buf && offset || 0;
var b = buf || [];
options = options || {};
var node = options.node || _nodeId;
var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
// specified. We do this lazily to minimize issues related to insufficient
// system entropy. See #189
if (node == null || clockseq == null) {
var seedBytes = rng();
if (node == null) {
// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
}
if (clockseq == null) {
// Per 4.2.2, randomize (14 bit) clockseq
clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
}
} // UUID timestamps are 100 nano-second units since the Gregorian epoch,
// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock
// cycle to simulate higher resolution clock
var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
if (dt < 0 && options.clockseq === undefined) {
clockseq = clockseq + 1 & 0x3fff;
} // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
// time interval
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
nsecs = 0;
} // Per 4.2.1.2 Throw error if too many uuids are requested
if (nsecs >= 10000) {
throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
msecs += 12219292800000; // `time_low`
var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
b[i++] = tl >>> 24 & 0xff;
b[i++] = tl >>> 16 & 0xff;
b[i++] = tl >>> 8 & 0xff;
b[i++] = tl & 0xff; // `time_mid`
var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
b[i++] = tmh >>> 8 & 0xff;
b[i++] = tmh & 0xff; // `time_high_and_version`
b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
b[i++] = clockseq & 0xff; // `node`
for (var n = 0; n < 6; ++n) {
b[i + n] = node[n];
}
return buf ? buf : bytesToUuid(b);
}
module.exports = v1;
/***/ }),
/***/ "./node_modules/uuid/v4.js":
/*!*********************************!*\
!*** ./node_modules/uuid/v4.js ***!
\*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var rng = __webpack_require__(/*! ./lib/rng */ "./node_modules/uuid/lib/rng.js");
var bytesToUuid = __webpack_require__(/*! ./lib/bytesToUuid */ "./node_modules/uuid/lib/bytesToUuid.js");
function v4(options, buf, offset) {
var i = buf && offset || 0;
if (typeof options == 'string') {
buf = options === 'binary' ? new Array(16) : null;
options = null;
}
options = options || {};
var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = rnds[6] & 0x0f | 0x40;
rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
if (buf) {
for (var ii = 0; ii < 16; ++ii) {
buf[i + ii] = rnds[ii];
}
}
return buf || bytesToUuid(rnds);
}
module.exports = v4;
/***/ }),
/***/ "./node_modules/which-boxed-primitive/index.js":
/*!*****************************************************!*\
!*** ./node_modules/which-boxed-primitive/index.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var isString = __webpack_require__(/*! is-string */ "./node_modules/is-string/index.js");
var isNumber = __webpack_require__(/*! is-number-object */ "./node_modules/is-number-object/index.js");
var isBoolean = __webpack_require__(/*! is-boolean-object */ "./node_modules/is-boolean-object/index.js");
var isSymbol = __webpack_require__(/*! is-symbol */ "./node_modules/is-symbol/index.js");
var isBigInt = __webpack_require__(/*! is-bigint */ "./node_modules/is-bigint/index.js"); // eslint-disable-next-line consistent-return
module.exports = function whichBoxedPrimitive(value) {
// eslint-disable-next-line eqeqeq
if (value == null || typeof value !== 'object' && typeof value !== 'function') {
return null;
}
if (isString(value)) {
return 'String';
}
if (isNumber(value)) {
return 'Number';
}
if (isBoolean(value)) {
return 'Boolean';
}
if (isSymbol(value)) {
return 'Symbol';
}
if (isBigInt(value)) {
return 'BigInt';
}
};
/***/ }),
/***/ "./node_modules/which-collection/index.js":
/*!************************************************!*\
!*** ./node_modules/which-collection/index.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var isMap = __webpack_require__(/*! is-map */ "./node_modules/is-map/index.js");
var isSet = __webpack_require__(/*! is-set */ "./node_modules/is-set/index.js");
var isWeakMap = __webpack_require__(/*! is-weakmap */ "./node_modules/is-weakmap/index.js");
var isWeakSet = __webpack_require__(/*! is-weakset */ "./node_modules/is-weakset/index.js");
module.exports = function whichCollection(value) {
if (value && typeof value === 'object') {
if (isMap(value)) {
return 'Map';
}
if (isSet(value)) {
return 'Set';
}
if (isWeakMap(value)) {
return 'WeakMap';
}
if (isWeakSet(value)) {
return 'WeakSet';
}
}
return false;
};
/***/ }),
/***/ "./node_modules/which-typed-array/index.js":
/*!*************************************************!*\
!*** ./node_modules/which-typed-array/index.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(/*! foreach */ "./node_modules/foreach/index.js");
var availableTypedArrays = __webpack_require__(/*! available-typed-arrays */ "./node_modules/available-typed-arrays/index.js");
var callBound = __webpack_require__(/*! call-bind/callBound */ "./node_modules/call-bind/callBound.js");
var $toString = callBound('Object.prototype.toString');
var hasSymbols = __webpack_require__(/*! has-symbols */ "./node_modules/has-symbols/index.js")();
var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol';
var typedArrays = availableTypedArrays();
var $slice = callBound('String.prototype.slice');
var toStrTags = {};
var gOPD = __webpack_require__(/*! es-abstract/helpers/getOwnPropertyDescriptor */ "./node_modules/es-abstract/helpers/getOwnPropertyDescriptor.js");
var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');
if (hasToStringTag && gOPD && getPrototypeOf) {
forEach(typedArrays, function (typedArray) {
if (typeof global[typedArray] === 'function') {
var arr = new global[typedArray]();
if (!(Symbol.toStringTag in arr)) {
throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.');
}
var proto = getPrototypeOf(arr);
var descriptor = gOPD(proto, Symbol.toStringTag);
if (!descriptor) {
var superProto = getPrototypeOf(proto);
descriptor = gOPD(superProto, Symbol.toStringTag);
}
toStrTags[typedArray] = descriptor.get;
}
});
}
var tryTypedArrays = function tryAllTypedArrays(value) {
var foundName = false;
forEach(toStrTags, function (getter, typedArray) {
if (!foundName) {
try {
var name = getter.call(value);
if (name === typedArray) {
foundName = name;
}
} catch (e) {}
}
});
return foundName;
};
var isTypedArray = __webpack_require__(/*! is-typed-array */ "./node_modules/is-typed-array/index.js");
module.exports = function whichTypedArray(value) {
if (!isTypedArray(value)) {
return false;
}
if (!hasToStringTag) {
return $slice($toString(value), 8, -1);
}
return tryTypedArrays(value);
};
/***/ }),
/***/ "./packages/api/injected.js":
/*!**********************************!*\
!*** ./packages/api/injected.js ***!
\**********************************/
/*! no static exports found */
/***/ (function(module, exports) {
// TODO: comment on why it works this way
let send;
module.exports = {
send
};
/***/ }),
/***/ "./packages/api/methods.js":
/*!*********************************!*\
!*** ./packages/api/methods.js ***!
\*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const q = __webpack_require__(/*! ./query */ "./packages/api/query.js");
const injected = __webpack_require__(/*! ./injected */ "./packages/api/injected.js");
function send(name, args) {
return injected.send(name, args);
}
async function runImport(name, func) {
await send('api/start-import', {
budgetName: name
});
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
async function loadBudget(budgetId) {
return send('api/load-budget', {
id: budgetId
});
}
async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
function runQuery(query) {
return send('api/query', {
query: query.serialize()
});
}
function getBudgetMonths() {
return send('api/budget-months');
}
function getBudgetMonth(month) {
return send('api/budget-month', {
month
});
}
function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', {
month,
categoryId,
amount: value
});
}
function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', {
month,
categoryId,
flag
});
}
function addTransactions(accountId, transactions) {
return send('api/transactions-add', {
accountId,
transactions
});
}
function importTransactions(accountId, transactions) {
return send('api/transactions-import', {
accountId,
transactions
});
}
function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', {
accountId,
startDate,
endDate
});
}
function filterTransactions(accountId, text) {
return send('api/transactions-filter', {
accountId,
text
});
}
function updateTransaction(id, fields) {
return send('api/transaction-update', {
id,
fields
});
}
function deleteTransaction(id) {
return send('api/transaction-delete', {
id
});
}
function getAccounts() {
return send('api/accounts-get');
}
function createAccount(account, initialBalance) {
return send('api/account-create', {
account,
initialBalance
});
}
function updateAccount(id, fields) {
return send('api/account-update', {
id,
fields
});
}
function closeAccount(id, transferAccountId, transferCategoryId) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId
});
}
function reopenAccount(id) {
return send('api/account-reopen', {
id
});
}
function deleteAccount(id) {
return send('api/account-delete', {
id
});
}
function getCategoryGroups() {
return send('api/categories-get', {
grouped: true
});
}
function createCategoryGroup(group) {
return send('api/category-group-create', {
group
});
}
function updateCategoryGroup(id, fields) {
return send('api/category-group-update', {
id,
fields
});
}
function deleteCategoryGroup(id, transferCategoryId) {
return send('api/category-group-delete', {
id,
transferCategoryId
});
}
function getCategories() {
return send('api/categories-get', {
grouped: false
});
}
function createCategory(category) {
return send('api/category-create', {
category
});
}
function updateCategory(id, fields) {
return send('api/category-update', {
id,
fields
});
}
function deleteCategory(id, transferCategoryId) {
return send('api/category-delete', {
id,
transferCategoryId
});
}
function getPayees() {
return send('api/payees-get');
}
function createPayee(payee) {
return send('api/payee-create', {
payee
});
}
function updatePayee(id, fields) {
return send('api/payee-update', {
id,
fields
});
}
function deletePayee(id) {
return send('api/payee-delete', {
id
});
}
function getPayeeRules(payeeId) {
return send('api/payee-rules-get', {
payeeId
});
}
function createPayeeRule(payeeId, rule) {
return send('api/payee-rule-create', {
payee_id: payeeId,
rule
});
}
function updatePayeeRule(id, fields) {
return send('api/payee-rule-update', {
id,
fields
});
}
function deletePayeeRule(id) {
return send('api/payee-rule-delete', {
id
});
}
module.exports = {
runImport,
runQuery,
q,
loadBudget,
batchBudgetUpdates,
getBudgetMonths,
getBudgetMonth,
setBudgetAmount,
setBudgetCarryover,
addTransactions,
importTransactions,
filterTransactions,
getTransactions,
updateTransaction,
deleteTransaction,
getAccounts,
createAccount,
updateAccount,
closeAccount,
reopenAccount,
deleteAccount,
getCategories,
createCategoryGroup,
updateCategoryGroup,
deleteCategoryGroup,
createCategory,
updateCategory,
deleteCategory,
getPayees,
createPayee,
updatePayee,
deletePayee,
getPayeeRules,
createPayeeRule,
deletePayeeRule,
updatePayeeRule
};
/***/ }),
/***/ "./packages/api/query.js":
/*!*******************************!*\
!*** ./packages/api/query.js ***!
\*******************************/
/*! no static exports found */
/***/ (function(module, exports) {
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
class Query {
constructor(state) {
this.state = _objectSpread({
filterExpressions: state.filterExpressions || [],
selectExpressions: state.selectExpressions || [],
groupExpressions: state.groupExpressions || [],
orderExpressions: state.orderExpressions || [],
calculation: false,
rawMode: false,
withDead: false,
limit: null,
offset: null
}, state);
}
filter(expr) {
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
filterExpressions: [...this.state.filterExpressions, expr]
}));
}
unfilter(exprs) {
let exprSet = new Set(exprs);
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
filterExpressions: this.state.filterExpressions.filter(expr => !exprSet.has(Object.keys(expr)[0]))
}));
}
select(exprs = []) {
if (!Array.isArray(exprs)) {
exprs = [exprs];
}
let query = new Query(_objectSpread(_objectSpread({}, this.state), {}, {
selectExpressions: exprs
}));
query.state.calculation = false;
return query;
}
calculate(expr) {
let query = this.select({
result: expr
});
query.state.calculation = true;
return query;
}
groupBy(exprs) {
if (!Array.isArray(exprs)) {
exprs = [exprs];
}
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
groupExpressions: [...this.state.groupExpressions, ...exprs]
}));
}
orderBy(exprs) {
if (!Array.isArray(exprs)) {
exprs = [exprs];
}
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
orderExpressions: [...this.state.orderExpressions, ...exprs]
}));
}
limit(num) {
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
limit: num
}));
}
offset(num) {
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
offset: num
}));
}
raw() {
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
rawMode: true
}));
}
withDead() {
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
withDead: true
}));
}
options(opts) {
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
tableOptions: opts
}));
}
serialize() {
return this.state;
}
}
module.exports = function q(table) {
return new Query({
table
});
};
/***/ }),
/***/ "./packages/api/utils.js":
/*!*******************************!*\
!*** ./packages/api/utils.js ***!
\*******************************/
/*! no static exports found */
/***/ (function(module, exports) {
function amountToInteger(n) {
return Math.round(n * 100) | 0;
}
function integerToAmount(n) {
return parseFloat((n / 100).toFixed(2));
}
module.exports = {
amountToInteger,
integerToAmount
};
/***/ }),
/***/ "./packages/import-ynab4/importer.js":
/*!*******************************************!*\
!*** ./packages/import-ynab4/importer.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
const d = __webpack_require__(/*! date-fns */ "./node_modules/date-fns/esm/index.js");
const normalizePathSep = __webpack_require__(/*! slash */ "./node_modules/slash/index.js");
const uuid = __webpack_require__(/*! uuid */ "./node_modules/uuid/index.js");
const AdmZip = __webpack_require__(/*! adm-zip */ "./node_modules/adm-zip/adm-zip.js");
const actual = __webpack_require__(/*! @actual-app/api/methods */ "./packages/api/methods.js");
const _require = __webpack_require__(/*! @actual-app/api/utils */ "./packages/api/utils.js"),
amountToInteger = _require.amountToInteger; // Utils
function mapAccountType(type) {
switch (type) {
case 'Cash':
case 'Checking':
return 'checking';
case 'CreditCard':
return 'credit';
case 'Savings':
return 'savings';
case 'InvestmentAccount':
return 'investment';
case 'Mortgage':
return 'mortgage';
default:
return 'other';
}
}
function sortByKey(arr, key) {
return [...arr].sort((item1, item2) => {
if (item1[key] < item2[key]) {
return -1;
} else if (item1[key] > item2[key]) {
return 1;
}
return 0;
});
}
function groupBy(arr, keyName) {
return arr.reduce(function (obj, item) {
var key = item[keyName];
if (!obj.hasOwnProperty(key)) {
obj[key] = [];
}
obj[key].push(item);
return obj;
}, {});
}
function _parse(value) {
if (typeof value === 'string') {
// We don't want parsing to take local timezone into account,
// which parsing a string does. Pass the integers manually to
// bypass it.
let _value$split = value.split('-'),
_value$split2 = _slicedToArray(_value$split, 3),
year = _value$split2[0],
month = _value$split2[1],
day = _value$split2[2];
if (day != null) {
return new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
} else if (month != null) {
return new Date(parseInt(year), parseInt(month) - 1, 1);
} else {
return new Date(parseInt(year), 0, 1);
}
}
return value;
}
function monthFromDate(date) {
return d.format(_parse(date), 'yyyy-MM');
}
function getCurrentMonth() {
return d.format(new Date(), 'yyyy-MM');
} // Importer
async function importAccounts(data, entityIdMap) {
return Promise.all(data.accounts.map(async account => {
if (!account.isTombstone) {
const id = await actual.createAccount({
type: mapAccountType(account.accountType),
name: account.accountName,
offbudget: account.onBudget ? false : true,
closed: account.hidden ? true : false
});
entityIdMap.set(account.entityId, id);
}
}));
}
async function importCategories(data, entityIdMap) {
const masterCategories = sortByKey(data.masterCategories, 'sortableIndex');
await Promise.all(masterCategories.map(async masterCategory => {
if (masterCategory.type === 'OUTFLOW' && !masterCategory.isTombstone && masterCategory.subCategories && masterCategory.subCategories.some(cat => !cat.isTombstone) > 0) {
const id = await actual.createCategoryGroup({
name: masterCategory.name,
is_income: false
});
entityIdMap.set(masterCategory.entityId, id);
if (masterCategory.subCategories) {
const subCategories = sortByKey(masterCategory.subCategories, 'sortableIndex');
subCategories.reverse(); // This can't be done in parallel because sort order depends
// on insertion order
for (let category of subCategories) {
if (!category.isTombstone) {
const id = await actual.createCategory({
name: category.name,
group_id: entityIdMap.get(category.masterCategoryId)
});
entityIdMap.set(category.entityId, id);
}
}
}
}
}));
}
async function importPayees(data, entityIdMap) {
for (let payee of data.payees) {
if (!payee.isTombstone) {
let id = await actual.createPayee({
name: payee.name,
category: entityIdMap.get(payee.autoFillCategoryId) || null,
transfer_acct: entityIdMap.get(payee.targetAccountId) || null
}); // TODO: import payee rules
entityIdMap.set(payee.entityId, id);
}
}
}
async function importTransactions(data, entityIdMap) {
const categories = await actual.getCategories();
const incomeCategoryId = categories.find(cat => cat.name === 'Income').id;
const accounts = await actual.getAccounts();
const payees = await actual.getPayees();
function getCategory(id) {
if (id == null || id === 'Category/__Split__') {
return null;
} else if (id === 'Category/__ImmediateIncome__' || id === 'Category/__DeferredIncome__') {
return incomeCategoryId;
}
return entityIdMap.get(id);
}
function isOffBudget(acctId) {
let acct = accounts.find(acct => acct.id === acctId);
if (!acct) {
throw new Error('Could not find account for transaction when importing');
}
return acct.offbudget;
} // Go ahead and generate ids for all of the transactions so we can
// reliably resolve transfers
for (let transaction of data.transactions) {
entityIdMap.set(transaction.entityId, uuid.v4());
}
let sortOrder = 1;
let transactionsGrouped = groupBy(data.transactions, 'accountId');
await Promise.all(Object.keys(transactionsGrouped).map(async accountId => {
let transactions = transactionsGrouped[accountId];
let toImport = transactions.map(transaction => {
if (transaction.isTombstone) {
return;
}
let id = entityIdMap.get(transaction.entityId);
let transferId = entityIdMap.get(transaction.transferTransactionId) || null;
let payee = null;
if (transferId) {
payee = payees.find(p => p.transfer_acct === entityIdMap.get(transaction.targetAccountId)).id;
} else {
payee = entityIdMap.get(transaction.payeeId);
}
let newTransaction = {
id,
amount: amountToInteger(transaction.amount),
category: isOffBudget(entityIdMap.get(accountId)) ? null : getCategory(transaction.categoryId),
date: transaction.date,
notes: transaction.memo || null,
payee,
transfer_id: transferId
};
newTransaction.subtransactions = transaction.subTransactions && transaction.subTransactions.map((t, i) => {
return {
amount: amountToInteger(t.amount),
category: getCategory(t.categoryId)
};
});
return newTransaction;
}).filter(x => x);
await actual.addTransactions(entityIdMap.get(accountId), toImport);
}));
}
function fillInBudgets(data, categoryBudgets) {
// YNAB only contains entries for categories that have been actually
// budgeted. That would be fine except that we need to set the
// "carryover" flag on each month when carrying debt across months.
// To make sure our system has a chance to set this flag on each
// category, make sure a budget exists for every category of every
// month.
const budgets = [...categoryBudgets];
data.masterCategories.forEach(masterCategory => {
if (masterCategory.subCategories) {
masterCategory.subCategories.forEach(category => {
if (!budgets.find(b => b.categoryId === category.entityId)) {
budgets.push({
budgeted: 0,
categoryId: category.entityId
});
}
});
}
});
return budgets;
}
async function importBudgets(data, entityIdMap) {
let budgets = sortByKey(data.monthlyBudgets, 'month');
let earliestMonth = monthFromDate(budgets[0].month);
let currentMonth = getCurrentMonth();
await actual.batchBudgetUpdates(async () => {
const carryoverFlags = {};
for (let budget of budgets) {
let filled = fillInBudgets(data, budget.monthlySubCategoryBudgets.filter(b => !b.isTombstone));
await Promise.all(filled.map(async catBudget => {
let amount = amountToInteger(catBudget.budgeted);
let catId = entityIdMap.get(catBudget.categoryId);
let month = monthFromDate(budget.month);
if (!catId) {
return;
}
await actual.setBudgetAmount(month, catId, amount);
if (catBudget.overspendingHandling === 'AffectsBuffer') {
// Turn off the carryover flag so it doesn't propagate
// to future months
carryoverFlags[catId] = false;
} else if (catBudget.overspendingHandling === 'Confined' || carryoverFlags[catId]) {
// Overspending has switched to carryover, set the
// flag so it propagates to future months
carryoverFlags[catId] = true;
await actual.setBudgetCarryover(month, catId, true);
}
}));
}
});
}
function estimateRecentness(str) {
// The "recentness" is the total amount of changes that this device
// is aware of, which is estimated by summing up all of the version
// numbers that its aware of. This works because version numbers are
// increasing integers.
return str.split(',').reduce((total, version) => {
const _version$split = version.split('-'),
_version$split2 = _slicedToArray(_version$split, 2),
_ = _version$split2[0],
number = _version$split2[1];
return total + parseInt(number);
}, 0);
}
function findLatestDevice(zipped, entries) {
let devices = entries.map(entry => {
const contents = zipped.readFile(entry).toString('utf8');
let data;
try {
data = JSON.parse(contents);
} catch (e) {
return null;
}
if (data.hasFullKnowledge) {
return {
deviceGUID: data.deviceGUID,
shortName: data.shortDeviceId,
recentness: estimateRecentness(data.knowledge)
};
}
return null;
}).filter(x => x);
devices = sortByKey(devices, 'recentness');
return devices[devices.length - 1].deviceGUID;
}
async function doImport(data) {
const entityIdMap = new Map();
console.log('Importing Accounts...');
await importAccounts(data, entityIdMap);
console.log('Importing Categories...');
await importCategories(data, entityIdMap);
console.log('Importing Payees...');
await importPayees(data, entityIdMap);
console.log('Importing Transactions...');
await importTransactions(data, entityIdMap);
console.log('Importing Budgets...');
await importBudgets(data, entityIdMap);
console.log('Setting up...');
}
function getBudgetName(filepath) {
let unixFilepath = normalizePathSep(filepath);
if (!/\.zip/.test(unixFilepath)) {
return null;
}
unixFilepath = unixFilepath.replace(/\.zip$/, '').replace(/.ynab4$/, ''); // Most budgets are named like "Budget~51938D82.ynab4" but sometimes
// they are only "Budget.ynab4". We only want to grab the name
// before the ~ if it exists.
let m = unixFilepath.match(/([^/~]+)[^/]*$/);
if (!m) {
return null;
}
return m[1];
}
function getFile(entries, path) {
let files = entries.filter(e => e.entryName === path);
if (files.length === 0) {
throw new Error('Could not find file: ' + path);
}
if (files.length >= 2) {
throw new Error('File name matches multiple files: ' + path);
}
return files[0];
}
function join(...paths) {
return paths.slice(1).reduce((full, path) => {
return full + '/' + path.replace(/^\//, '');
}, paths[0].replace(/\/$/, ''));
}
async function importBuffer(filepath, buffer) {
let budgetName = getBudgetName(filepath);
if (!budgetName) {
throw new Error('Not a YNAB4 file: ' + filepath);
}
let zipped = new AdmZip(buffer);
let entries = zipped.getEntries();
let root = '';
let dirMatch = entries[0].entryName.match(/([^/]*\.ynab4)/);
if (dirMatch) {
root = dirMatch[1] + '/';
}
let metaStr = zipped.readFile(getFile(entries, root + 'Budget.ymeta'));
let meta = JSON.parse(metaStr.toString('utf8'));
let budgetPath = join(root, meta.relativeDataFolderName);
let deviceFiles = entries.filter(e => e.entryName.startsWith(join(budgetPath, 'devices')));
let deviceGUID = findLatestDevice(zipped, deviceFiles);
const yfullPath = join(budgetPath, deviceGUID, 'Budget.yfull');
let contents;
try {
contents = zipped.readFile(getFile(entries, yfullPath)).toString('utf8');
} catch (e) {
console.log(e);
throw new Error('Error reading Budget.yfull file');
}
let data;
try {
data = JSON.parse(contents);
} catch (e) {
throw new Error('Error parsing Budget.yull file');
}
return actual.runImport(budgetName, () => doImport(data));
}
module.exports = {
importBuffer
};
/***/ }),
/***/ "./packages/import-ynab5/importer.js":
/*!*******************************************!*\
!*** ./packages/import-ynab5/importer.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const d = __webpack_require__(/*! date-fns */ "./node_modules/date-fns/esm/index.js");
const uuid = __webpack_require__(/*! uuid */ "./node_modules/uuid/index.js");
const actual = __webpack_require__(/*! @actual-app/api/methods */ "./packages/api/methods.js");
const _require = __webpack_require__(/*! @actual-app/api/utils */ "./packages/api/utils.js"),
amountToInteger = _require.amountToInteger;
function amountFromYnab(amount) {
// ynabs multiplies amount by 1000 and actual by 100
// so, this function divides by 10
return Math.round(amount / 10);
}
function monthFromDate(date) {
let parts = date.split('-');
return parts[0] + '-' + parts[1];
}
function mapAccountType(type) {
switch (type) {
case 'cash':
case 'checking':
return 'checking';
case 'creditCard':
case 'lineOfCredit':
return 'credit';
case 'savings':
return 'savings';
case 'investmentAccount':
return 'investment';
case 'mortgage':
return 'mortgage';
default:
return 'other';
}
}
function sortByKey(arr, key) {
return [...arr].sort((item1, item2) => {
if (item1[key] < item2[key]) {
return -1;
} else if (item1[key] > item2[key]) {
return 1;
}
return 0;
});
}
function groupBy(arr, keyName) {
return arr.reduce(function (obj, item) {
var key = item[keyName];
if (!obj.hasOwnProperty(key)) {
obj[key] = [];
}
obj[key].push(item);
return obj;
}, {});
}
function importAccounts(data, entityIdMap) {
return Promise.all(data.accounts.map(async account => {
if (!account.deleted) {
let id = await actual.createAccount({
type: mapAccountType(account.type),
name: account.name,
offbudget: account.on_budget ? false : true,
closed: account.closed
});
entityIdMap.set(account.id, id);
}
}));
}
async function importCategories(data, entityIdMap) {
// Hidden categories are put in its own group by YNAB,
// so it's already handled.
const categories = await actual.getCategories();
const incomeCatId = categories.find(cat => cat.name === 'Income').id;
const ynabIncomeCategories = ['To be Budgeted', 'Inflow: Ready to Assign'];
function checkSpecialCat(cat) {
if (cat.category_group_id === data.category_groups.find(group => group.name === 'Internal Master Category').id) {
if (ynabIncomeCategories.includes(cat.name)) {
return 'income';
} else {
return 'internal';
}
} else if (cat.category_group_id === data.category_groups.find(group => group.name === 'Credit Card Payments').id) {
return 'creditCard';
}
} // Can't be done in parallel to have
// correct sort order.
for (let group of data.category_groups) {
if (!group.deleted) {
// Ignores internal category and credit cards
if (group.name !== 'Internal Master Category' && group.name !== 'Credit Card Payments') {
var groupId = await actual.createCategoryGroup({
name: group.name,
is_income: false
});
entityIdMap.set(group.id, groupId);
}
let cats = data.categories.filter(cat => cat.category_group_id === group.id);
for (let cat of cats.reverse()) {
if (!cat.deleted) {
let newCategory = {};
newCategory.name = cat.name; // Handles special categories. Starting balance is a payee
// in YNAB so it's handled in importTransactions
switch (checkSpecialCat(cat)) {
case 'income':
{
// doesn't create new category, only assigns id
let id = incomeCatId;
entityIdMap.set(cat.id, id);
break;
}
case 'creditCard': // ignores it
case 'internal':
// uncategorized is ignored too, handled by actual
break;
default:
{
newCategory.group_id = groupId;
let id = await actual.createCategory(newCategory);
entityIdMap.set(cat.id, id);
break;
}
}
}
}
}
}
}
function importPayees(data, entityIdMap) {
return Promise.all(data.payees.map(async payee => {
if (!payee.deleted) {
let id = await actual.createPayee({
name: payee.name
});
entityIdMap.set(payee.id, id);
}
}));
}
async function importTransactions(data, entityIdMap) {
const payees = await actual.getPayees();
const categories = await actual.getCategories();
const incomeCatId = categories.find(cat => cat.name === 'Income').id;
const startingBalanceCatId = categories.find(cat => cat.name === 'Starting Balances').id; //better way to do it?
const startingPayeeYNAB = data.payees.find(payee => payee.name === 'Starting Balance').id;
let transactionsGrouped = groupBy(data.transactions, 'account_id');
let subtransactionsGrouped = groupBy(data.subtransactions, 'transaction_id'); // Go ahead and generate ids for all of the transactions so we can
// reliably resolve transfers
for (let transaction of data.transactions) {
entityIdMap.set(transaction.id, uuid.v4());
}
await Promise.all(Object.keys(transactionsGrouped).map(async accountId => {
let transactions = transactionsGrouped[accountId];
let toImport = transactions.map(transaction => {
if (transaction.deleted) {
return null;
} // Handle subtransactions
let subtransactions = subtransactionsGrouped[transaction.id];
if (subtransactions) {
subtransactions = subtransactions.map(subtrans => {
return {
amount: amountFromYnab(subtrans.amount),
category: entityIdMap.get(subtrans.category_id) || null,
notes: subtrans.memo
};
});
} // Add transaction
let newTransaction = {
id: entityIdMap.get(transaction.id),
account: entityIdMap.get(transaction.account_id),
date: transaction.date,
amount: amountFromYnab(transaction.amount),
category: entityIdMap.get(transaction.category_id) || null,
cleared: ['cleared', 'reconciled'].includes(transaction.cleared),
notes: transaction.memo || null,
imported_id: transaction.import_id || null,
transfer_id: entityIdMap.get(transaction.transfer_transaction_id) || null,
subtransactions: subtransactions
}; // Handle transfer payee
if (transaction.transfer_account_id) {
newTransaction.payee = payees.find(p => p.transfer_acct === entityIdMap.get(transaction.transfer_account_id)).id;
} else {
newTransaction.payee = entityIdMap.get(transaction.payee_id);
} // Handle starting balances
if (transaction.payee_id === startingPayeeYNAB && entityIdMap.get(transaction.category_id) === incomeCatId) {
newTransaction.category = startingBalanceCatId;
newTransaction.payee = null;
}
return newTransaction;
}).filter(x => x);
await actual.addTransactions(entityIdMap.get(accountId), toImport);
}));
}
async function importBudgets(data, entityIdMap) {
// There should be info in the docs to deal with
// no credit card category and how YNAB and Actual
// handle differently the amount To be Budgeted
// i.e. Actual considers the cc debt while YNAB doesn't
//
// Also, there could be a way to set rollover using
// Deferred Income Subcat and Immediate Income Subcat
let budgets = sortByKey(data.months, 'month');
const internalCatIdYnab = data.category_groups.find(group => group.name === 'Internal Master Category').id;
const creditcardCatIdYnab = data.category_groups.find(group => group.name === 'Credit Card Payments').id;
await actual.batchBudgetUpdates(async () => {
for (let budget of budgets) {
let month = monthFromDate(budget.month);
await Promise.all(budget.categories.map(async catBudget => {
let catId = entityIdMap.get(catBudget.id);
let amount = catBudget.budgeted / 10;
if (!catId || catBudget.category_group_id === internalCatIdYnab || catBudget.category_group_id === creditcardCatIdYnab) {
return;
}
await actual.setBudgetAmount(month, catId, amount);
}));
}
});
} // Utils
async function doImport(data) {
const entityIdMap = new Map();
console.log('Importing Accounts...');
await importAccounts(data, entityIdMap);
console.log('Importing Categories...');
await importCategories(data, entityIdMap);
console.log('Importing Payees...');
await importPayees(data, entityIdMap);
console.log('Importing Transactions...');
await importTransactions(data, entityIdMap);
console.log('Importing Budgets...');
await importBudgets(data, entityIdMap);
console.log('Setting up...');
}
async function importYNAB5(data) {
if (data.data) {
data = data.data;
}
return actual.runImport(data.budget.name, () => doImport(data.budget));
}
module.exports = {
importYNAB5
};
/***/ }),
/***/ "./packages/loot-core/migrations/1632571489012_remove_cache.js":
/*!*********************************************************************!*\
!*** ./packages/loot-core/migrations/1632571489012_remove_cache.js ***!
\*********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return runMigration; });
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
async function runMigration(db, uuid) {
function getValue(node) {
return node.expr != null ? node.expr : node.cachedValue;
}
db.execQuery(`
CREATE TABLE zero_budget_months
(id TEXT PRIMARY KEY,
buffered INTEGER DEFAULT 0);
CREATE TABLE zero_budgets
(id TEXT PRIMARY KEY,
month INTEGER,
category TEXT,
amount INTEGER DEFAULT 0,
carryover INTEGER DEFAULT 0);
CREATE TABLE reflect_budgets
(id TEXT PRIMARY KEY,
month INTEGER,
category TEXT,
amount INTEGER DEFAULT 0,
carryover INTEGER DEFAULT 0);
CREATE TABLE notes
(id TEXT PRIMARY KEY,
note TEXT);
CREATE TABLE kvcache (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE kvcache_key (id INTEGER PRIMARY KEY, key REAL);
`); // Migrate budget amounts and carryover
let budget = db.runQuery(`SELECT * FROM spreadsheet_cells WHERE name LIKE 'budget%!budget-%'`, [], true);
db.transaction(() => {
budget.map(monthBudget => {
let match = monthBudget.name.match(/^(budget-report|budget)(\d+)!budget-(.+)$/);
if (match == null) {
console.log('Warning: invalid budget month name', monthBudget.name);
return;
}
let type = match[1];
let month = match[2].slice(0, 4) + '-' + match[2].slice(4);
let dbmonth = parseInt(match[2]);
let cat = match[3];
let amount = parseInt(getValue(monthBudget));
if (isNaN(amount)) {
amount = 0;
}
let sheetName = monthBudget.name.split('!')[0];
let carryover = db.runQuery('SELECT * FROM spreadsheet_cells WHERE name = ?', [`${sheetName}!carryover-${cat}`], true);
let table = type === 'budget-report' ? 'reflect_budgets' : 'zero_budgets';
db.runQuery(`INSERT INTO ${table} (id, month, category, amount, carryover) VALUES (?, ?, ?, ?, ?)`, [`${month}-${cat}`, dbmonth, cat, amount, carryover.length > 0 && getValue(carryover[0]) === 'true' ? 1 : 0]);
});
}); // Migrate buffers
let buffers = db.runQuery(`SELECT * FROM spreadsheet_cells WHERE name LIKE 'budget%!buffered'`, [], true);
db.transaction(() => {
buffers.map(buffer => {
let match = buffer.name.match(/^budget(\d+)!buffered$/);
if (match) {
let month = match[1].slice(0, 4) + '-' + match[1].slice(4);
let amount = parseInt(getValue(buffer));
if (isNaN(amount)) {
amount = 0;
}
db.runQuery(`INSERT INTO zero_budget_months (id, buffered) VALUES (?, ?)`, [month, amount]);
}
});
}); // Migrate notes
let notes = db.runQuery(`SELECT * FROM spreadsheet_cells WHERE name LIKE 'notes!%'`, [], true);
let parseNote = str => {
try {
let value = JSON.parse(str);
return value && value !== '' ? value : null;
} catch (e) {
return null;
}
};
db.transaction(() => {
notes.forEach(note => {
let parsed = parseNote(getValue(note));
if (parsed) {
let _note$name$split = note.name.split('!'),
_note$name$split2 = _slicedToArray(_note$name$split, 2),
id = _note$name$split2[1];
db.runQuery(`INSERT INTO notes (id, note) VALUES (?, ?)`, [id, parsed]);
}
});
});
db.execQuery(`
DROP TABLE spreadsheet_cells;
ANALYZE;
VACUUM;
`);
}
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/adm-zip.js":
/*!************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/adm-zip.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var Utils = __webpack_require__(/*! ./util */ "./packages/loot-core/node_modules/adm-zip/util/index.js");
var fs = Utils.FileSystem.require(),
pth = __webpack_require__(/*! path */ "path");
fs.existsSync = fs.existsSync || pth.existsSync;
var ZipEntry = __webpack_require__(/*! ./zipEntry */ "./packages/loot-core/node_modules/adm-zip/zipEntry.js"),
ZipFile = __webpack_require__(/*! ./zipFile */ "./packages/loot-core/node_modules/adm-zip/zipFile.js");
var isWin = /^win/.test(process.platform);
module.exports = function (
/*String*/
input) {
var _zip = undefined,
_filename = "";
if (input && typeof input === "string") {
// load zip file
if (fs.existsSync(input)) {
_filename = input;
_zip = new ZipFile(input, Utils.Constants.FILE);
} else {
throw Utils.Errors.INVALID_FILENAME;
}
} else if (input && Buffer.isBuffer(input)) {
// load buffer
_zip = new ZipFile(input, Utils.Constants.BUFFER);
} else {
// create new zip file
_zip = new ZipFile(null, Utils.Constants.NONE);
}
function sanitize(prefix, name) {
prefix = pth.resolve(pth.normalize(prefix));
var parts = name.split('/');
for (var i = 0, l = parts.length; i < l; i++) {
var path = pth.normalize(pth.join(prefix, parts.slice(i, l).join(pth.sep)));
if (path.indexOf(prefix) === 0) {
return path;
}
}
return pth.normalize(pth.join(prefix, pth.basename(name)));
}
function getEntry(
/*Object*/
entry) {
if (entry && _zip) {
var item; // If entry was given as a file name
if (typeof entry === "string") item = _zip.getEntry(entry); // if entry was given as a ZipEntry object
if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined") item = _zip.getEntry(entry.entryName);
if (item) {
return item;
}
}
return null;
}
return {
/**
* Extracts the given entry from the archive and returns the content as a Buffer object
* @param entry ZipEntry object or String with the full path of the entry
*
* @return Buffer or Null in case of error
*/
readFile: function (
/*Object*/
entry) {
var item = getEntry(entry);
return item && item.getData() || null;
},
/**
* Asynchronous readFile
* @param entry ZipEntry object or String with the full path of the entry
* @param callback
*
* @return Buffer or Null in case of error
*/
readFileAsync: function (
/*Object*/
entry,
/*Function*/
callback) {
var item = getEntry(entry);
if (item) {
item.getDataAsync(callback);
} else {
callback(null, "getEntry failed for:" + entry);
}
},
/**
* Extracts the given entry from the archive and returns the content as plain text in the given encoding
* @param entry ZipEntry object or String with the full path of the entry
* @param encoding Optional. If no encoding is specified utf8 is used
*
* @return String
*/
readAsText: function (
/*Object*/
entry,
/*String - Optional*/
encoding) {
var item = getEntry(entry);
if (item) {
var data = item.getData();
if (data && data.length) {
return data.toString(encoding || "utf8");
}
}
return "";
},
/**
* Asynchronous readAsText
* @param entry ZipEntry object or String with the full path of the entry
* @param callback
* @param encoding Optional. If no encoding is specified utf8 is used
*
* @return String
*/
readAsTextAsync: function (
/*Object*/
entry,
/*Function*/
callback,
/*String - Optional*/
encoding) {
var item = getEntry(entry);
if (item) {
item.getDataAsync(function (data, err) {
if (err) {
callback(data, err);
return;
}
if (data && data.length) {
callback(data.toString(encoding || "utf8"));
} else {
callback("");
}
});
} else {
callback("");
}
},
/**
* Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory
*
* @param entry
*/
deleteFile: function (
/*Object*/
entry) {
// @TODO: test deleteFile
var item = getEntry(entry);
if (item) {
_zip.deleteEntry(item.entryName);
}
},
/**
* Adds a comment to the zip. The zip must be rewritten after adding the comment.
*
* @param comment
*/
addZipComment: function (
/*String*/
comment) {
// @TODO: test addZipComment
_zip.comment = comment;
},
/**
* Returns the zip comment
*
* @return String
*/
getZipComment: function () {
return _zip.comment || '';
},
/**
* Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment
* The comment cannot exceed 65535 characters in length
*
* @param entry
* @param comment
*/
addZipEntryComment: function (
/*Object*/
entry,
/*String*/
comment) {
var item = getEntry(entry);
if (item) {
item.comment = comment;
}
},
/**
* Returns the comment of the specified entry
*
* @param entry
* @return String
*/
getZipEntryComment: function (
/*Object*/
entry) {
var item = getEntry(entry);
if (item) {
return item.comment || '';
}
return '';
},
/**
* Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content
*
* @param entry
* @param content
*/
updateFile: function (
/*Object*/
entry,
/*Buffer*/
content) {
var item = getEntry(entry);
if (item) {
item.setData(content);
}
},
/**
* Adds a file from the disk to the archive
*
* @param localPath File to add to zip
* @param zipPath Optional path inside the zip
* @param zipName Optional name for the file
*/
addLocalFile: function (
/*String*/
localPath,
/*String*/
zipPath,
/*String*/
zipName) {
if (fs.existsSync(localPath)) {
if (zipPath) {
zipPath = zipPath.split("\\").join("/");
if (zipPath.charAt(zipPath.length - 1) !== "/") {
zipPath += "/";
}
} else {
zipPath = "";
}
var p = localPath.split("\\").join("/").split("/").pop();
if (zipName) {
this.addFile(zipPath + zipName, fs.readFileSync(localPath), "", 0);
} else {
this.addFile(zipPath + p, fs.readFileSync(localPath), "", 0);
}
} else {
throw Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath);
}
},
/**
* Adds a local directory and all its nested files and directories to the archive
*
* @param localPath
* @param zipPath optional path inside zip
* @param filter optional RegExp or Function if files match will
* be included.
*/
addLocalFolder: function (
/*String*/
localPath,
/*String*/
zipPath,
/*RegExp|Function*/
filter) {
if (filter === undefined) {
filter = function () {
return true;
};
} else if (filter instanceof RegExp) {
filter = function (filter) {
return function (filename) {
return filter.test(filename);
};
}(filter);
}
if (zipPath) {
zipPath = zipPath.split("\\").join("/");
if (zipPath.charAt(zipPath.length - 1) !== "/") {
zipPath += "/";
}
} else {
zipPath = "";
} // normalize the path first
localPath = pth.normalize(localPath);
localPath = localPath.split("\\").join("/"); //windows fix
if (localPath.charAt(localPath.length - 1) !== "/") localPath += "/";
if (fs.existsSync(localPath)) {
var items = Utils.findFiles(localPath),
self = this;
if (items.length) {
items.forEach(function (path) {
var p = path.split("\\").join("/").replace(new RegExp(localPath.replace(/(\(|\))/g, '\\$1'), 'i'), ""); //windows fix
if (filter(p)) {
if (p.charAt(p.length - 1) !== "/") {
self.addFile(zipPath + p, fs.readFileSync(path), "", 0);
} else {
self.addFile(zipPath + p, Buffer.alloc(0), "", 0);
}
}
});
}
} else {
throw Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath);
}
},
/**
* Allows you to create a entry (file or directory) in the zip file.
* If you want to create a directory the entryName must end in / and a null buffer should be provided.
* Comment and attributes are optional
*
* @param entryName
* @param content
* @param comment
* @param attr
*/
addFile: function (
/*String*/
entryName,
/*Buffer*/
content,
/*String*/
comment,
/*Number*/
attr) {
var entry = new ZipEntry();
entry.entryName = entryName;
entry.comment = comment || "";
if (!attr) {
if (entry.isDirectory) {
attr = 0o40755 << 16 | 0x10; // (permissions drwxr-xr-x) + (MS-DOS directory flag)
} else {
attr = 0o644 << 16; // permissions -r-wr--r--
}
}
entry.attr = attr;
entry.setData(content);
_zip.setEntry(entry);
},
/**
* Returns an array of ZipEntry objects representing the files and folders inside the archive
*
* @return Array
*/
getEntries: function () {
if (_zip) {
return _zip.entries;
} else {
return [];
}
},
/**
* Returns a ZipEntry object representing the file or folder specified by ``name``.
*
* @param name
* @return ZipEntry
*/
getEntry: function (
/*String*/
name) {
return getEntry(name);
},
/**
* Extracts the given entry to the given targetPath
* If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted
*
* @param entry ZipEntry object or String with the full path of the entry
* @param targetPath Target folder where to write the file
* @param maintainEntryPath If maintainEntryPath is true and the entry is inside a folder, the entry folder
* will be created in targetPath as well. Default is TRUE
* @param overwrite If the file already exists at the target path, the file will be overwriten if this is true.
* Default is FALSE
*
* @return Boolean
*/
extractEntryTo: function (
/*Object*/
entry,
/*String*/
targetPath,
/*Boolean*/
maintainEntryPath,
/*Boolean*/
overwrite) {
overwrite = overwrite || false;
maintainEntryPath = typeof maintainEntryPath === "undefined" ? true : maintainEntryPath;
var item = getEntry(entry);
if (!item) {
throw Utils.Errors.NO_ENTRY;
}
var entryName = item.entryName;
var target = sanitize(targetPath, maintainEntryPath ? entryName : pth.basename(entryName));
if (item.isDirectory) {
target = pth.resolve(target, "..");
var children = _zip.getEntryChildren(item);
children.forEach(function (child) {
if (child.isDirectory) return;
var content = child.getData();
if (!content) {
throw Utils.Errors.CANT_EXTRACT_FILE;
}
var childName = sanitize(targetPath, maintainEntryPath ? child.entryName : pth.basename(child.entryName));
Utils.writeFileTo(childName, content, overwrite);
});
return true;
}
var content = item.getData();
if (!content) throw Utils.Errors.CANT_EXTRACT_FILE;
if (fs.existsSync(target) && !overwrite) {
throw Utils.Errors.CANT_OVERRIDE;
}
Utils.writeFileTo(target, content, overwrite);
return true;
},
/**
* Test the archive
*
*/
test: function () {
if (!_zip) {
return false;
}
for (var entry in _zip.entries) {
try {
if (entry.isDirectory) {
continue;
}
var content = _zip.entries[entry].getData();
if (!content) {
return false;
}
} catch (err) {
return false;
}
}
return true;
},
/**
* Extracts the entire archive to the given location
*
* @param targetPath Target location
* @param overwrite If the file already exists at the target path, the file will be overwriten if this is true.
* Default is FALSE
*/
extractAllTo: function (
/*String*/
targetPath,
/*Boolean*/
overwrite) {
overwrite = overwrite || false;
if (!_zip) {
throw Utils.Errors.NO_ZIP;
}
_zip.entries.forEach(function (entry) {
var entryName = sanitize(targetPath, entry.entryName.toString());
if (entry.isDirectory) {
Utils.makeDir(entryName);
return;
}
var content = entry.getData();
if (!content) {
throw Utils.Errors.CANT_EXTRACT_FILE;
}
Utils.writeFileTo(entryName, content, overwrite);
try {
fs.utimesSync(entryName, entry.header.time, entry.header.time);
} catch (err) {
throw Utils.Errors.CANT_EXTRACT_FILE;
}
});
},
/**
* Asynchronous extractAllTo
*
* @param targetPath Target location
* @param overwrite If the file already exists at the target path, the file will be overwriten if this is true.
* Default is FALSE
* @param callback
*/
extractAllToAsync: function (
/*String*/
targetPath,
/*Boolean*/
overwrite,
/*Function*/
callback) {
if (!callback) {
callback = function () {};
}
overwrite = overwrite || false;
if (!_zip) {
callback(new Error(Utils.Errors.NO_ZIP));
return;
}
var entries = _zip.entries;
var i = entries.length;
entries.forEach(function (entry) {
if (i <= 0) return; // Had an error already
var entryName = pth.normalize(entry.entryName.toString());
if (entry.isDirectory) {
Utils.makeDir(sanitize(targetPath, entryName));
if (--i === 0) callback(undefined);
return;
}
entry.getDataAsync(function (content, err) {
if (i <= 0) return;
if (err) {
callback(new Error(err));
return;
}
if (!content) {
i = 0;
callback(new Error(Utils.Errors.CANT_EXTRACT_FILE));
return;
}
Utils.writeFileToAsync(sanitize(targetPath, entryName), content, overwrite, function (succ) {
try {
fs.utimesSync(pth.resolve(targetPath, entryName), entry.header.time, entry.header.time);
} catch (err) {
callback(new Error('Unable to set utimes'));
}
if (i <= 0) return;
if (!succ) {
i = 0;
callback(new Error('Unable to write'));
return;
}
if (--i === 0) callback(undefined);
});
});
});
},
/**
* Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip
*
* @param targetFileName
* @param callback
*/
writeZip: function (
/*String*/
targetFileName,
/*Function*/
callback) {
if (arguments.length === 1) {
if (typeof targetFileName === "function") {
callback = targetFileName;
targetFileName = "";
}
}
if (!targetFileName && _filename) {
targetFileName = _filename;
}
if (!targetFileName) return;
var zipData = _zip.compressToBuffer();
if (zipData) {
var ok = Utils.writeFileTo(targetFileName, zipData, true);
if (typeof callback === 'function') callback(!ok ? new Error("failed") : null, "");
}
},
/**
* Returns the content of the entire zip file as a Buffer object
*
* @return Buffer
*/
toBuffer: function (
/*Function*/
onSuccess,
/*Function*/
onFail,
/*Function*/
onItemStart,
/*Function*/
onItemEnd) {
this.valueOf = 2;
if (typeof onSuccess === "function") {
_zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd);
return null;
}
return _zip.compressToBuffer();
}
};
};
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/headers/entryHeader.js":
/*!************************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/headers/entryHeader.js ***!
\************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var Utils = __webpack_require__(/*! ../util */ "./packages/loot-core/node_modules/adm-zip/util/index.js"),
Constants = Utils.Constants;
/* The central directory file header */
module.exports = function () {
var _verMade = 0x0A,
_version = 0x0A,
_flags = 0,
_method = 0,
_time = 0,
_crc = 0,
_compressedSize = 0,
_size = 0,
_fnameLen = 0,
_extraLen = 0,
_comLen = 0,
_diskStart = 0,
_inattr = 0,
_attr = 0,
_offset = 0;
var _dataHeader = {};
function setTime(val) {
val = new Date(val);
_time = (val.getFullYear() - 1980 & 0x7f) << 25 // b09-16 years from 1980
| val.getMonth() + 1 << 21 // b05-08 month
| val.getDate() << 16 // b00-04 hour
// 2 bytes time
| val.getHours() << 11 // b11-15 hour
| val.getMinutes() << 5 // b05-10 minute
| val.getSeconds() >> 1; // b00-04 seconds divided by 2
}
setTime(+new Date());
return {
get made() {
return _verMade;
},
set made(val) {
_verMade = val;
},
get version() {
return _version;
},
set version(val) {
_version = val;
},
get flags() {
return _flags;
},
set flags(val) {
_flags = val;
},
get method() {
return _method;
},
set method(val) {
_method = val;
},
get time() {
return new Date((_time >> 25 & 0x7f) + 1980, (_time >> 21 & 0x0f) - 1, _time >> 16 & 0x1f, _time >> 11 & 0x1f, _time >> 5 & 0x3f, (_time & 0x1f) << 1);
},
set time(val) {
setTime(val);
},
get crc() {
return _crc;
},
set crc(val) {
_crc = val;
},
get compressedSize() {
return _compressedSize;
},
set compressedSize(val) {
_compressedSize = val;
},
get size() {
return _size;
},
set size(val) {
_size = val;
},
get fileNameLength() {
return _fnameLen;
},
set fileNameLength(val) {
_fnameLen = val;
},
get extraLength() {
return _extraLen;
},
set extraLength(val) {
_extraLen = val;
},
get commentLength() {
return _comLen;
},
set commentLength(val) {
_comLen = val;
},
get diskNumStart() {
return _diskStart;
},
set diskNumStart(val) {
_diskStart = val;
},
get inAttr() {
return _inattr;
},
set inAttr(val) {
_inattr = val;
},
get attr() {
return _attr;
},
set attr(val) {
_attr = val;
},
get offset() {
return _offset;
},
set offset(val) {
_offset = val;
},
get encripted() {
return (_flags & 1) === 1;
},
get entryHeaderSize() {
return Constants.CENHDR + _fnameLen + _extraLen + _comLen;
},
get realDataOffset() {
return _offset + Constants.LOCHDR + _dataHeader.fnameLen + _dataHeader.extraLen;
},
get dataHeader() {
return _dataHeader;
},
loadDataHeaderFromBinary: function (
/*Buffer*/
input) {
var data = input.slice(_offset, _offset + Constants.LOCHDR); // 30 bytes and should start with "PK\003\004"
if (data.readUInt32LE(0) !== Constants.LOCSIG) {
throw Utils.Errors.INVALID_LOC;
}
_dataHeader = {
// version needed to extract
version: data.readUInt16LE(Constants.LOCVER),
// general purpose bit flag
flags: data.readUInt16LE(Constants.LOCFLG),
// compression method
method: data.readUInt16LE(Constants.LOCHOW),
// modification time (2 bytes time, 2 bytes date)
time: data.readUInt32LE(Constants.LOCTIM),
// uncompressed file crc-32 value
crc: data.readUInt32LE(Constants.LOCCRC),
// compressed size
compressedSize: data.readUInt32LE(Constants.LOCSIZ),
// uncompressed size
size: data.readUInt32LE(Constants.LOCLEN),
// filename length
fnameLen: data.readUInt16LE(Constants.LOCNAM),
// extra field length
extraLen: data.readUInt16LE(Constants.LOCEXT)
};
},
loadFromBinary: function (
/*Buffer*/
data) {
// data should be 46 bytes and start with "PK 01 02"
if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) {
throw Utils.Errors.INVALID_CEN;
} // version made by
_verMade = data.readUInt16LE(Constants.CENVEM); // version needed to extract
_version = data.readUInt16LE(Constants.CENVER); // encrypt, decrypt flags
_flags = data.readUInt16LE(Constants.CENFLG); // compression method
_method = data.readUInt16LE(Constants.CENHOW); // modification time (2 bytes time, 2 bytes date)
_time = data.readUInt32LE(Constants.CENTIM); // uncompressed file crc-32 value
_crc = data.readUInt32LE(Constants.CENCRC); // compressed size
_compressedSize = data.readUInt32LE(Constants.CENSIZ); // uncompressed size
_size = data.readUInt32LE(Constants.CENLEN); // filename length
_fnameLen = data.readUInt16LE(Constants.CENNAM); // extra field length
_extraLen = data.readUInt16LE(Constants.CENEXT); // file comment length
_comLen = data.readUInt16LE(Constants.CENCOM); // volume number start
_diskStart = data.readUInt16LE(Constants.CENDSK); // internal file attributes
_inattr = data.readUInt16LE(Constants.CENATT); // external file attributes
_attr = data.readUInt32LE(Constants.CENATX); // LOC header offset
_offset = data.readUInt32LE(Constants.CENOFF);
},
dataHeaderToBinary: function () {
// LOC header size (30 bytes)
var data = Buffer.alloc(Constants.LOCHDR); // "PK\003\004"
data.writeUInt32LE(Constants.LOCSIG, 0); // version needed to extract
data.writeUInt16LE(_version, Constants.LOCVER); // general purpose bit flag
data.writeUInt16LE(_flags, Constants.LOCFLG); // compression method
data.writeUInt16LE(_method, Constants.LOCHOW); // modification time (2 bytes time, 2 bytes date)
data.writeUInt32LE(_time, Constants.LOCTIM); // uncompressed file crc-32 value
data.writeUInt32LE(_crc, Constants.LOCCRC); // compressed size
data.writeUInt32LE(_compressedSize, Constants.LOCSIZ); // uncompressed size
data.writeUInt32LE(_size, Constants.LOCLEN); // filename length
data.writeUInt16LE(_fnameLen, Constants.LOCNAM); // extra field length
data.writeUInt16LE(_extraLen, Constants.LOCEXT);
return data;
},
entryHeaderToBinary: function () {
// CEN header size (46 bytes)
var data = Buffer.alloc(Constants.CENHDR + _fnameLen + _extraLen + _comLen); // "PK\001\002"
data.writeUInt32LE(Constants.CENSIG, 0); // version made by
data.writeUInt16LE(_verMade, Constants.CENVEM); // version needed to extract
data.writeUInt16LE(_version, Constants.CENVER); // encrypt, decrypt flags
data.writeUInt16LE(_flags, Constants.CENFLG); // compression method
data.writeUInt16LE(_method, Constants.CENHOW); // modification time (2 bytes time, 2 bytes date)
data.writeUInt32LE(_time, Constants.CENTIM); // uncompressed file crc-32 value
data.writeUInt32LE(_crc, Constants.CENCRC); // compressed size
data.writeUInt32LE(_compressedSize, Constants.CENSIZ); // uncompressed size
data.writeUInt32LE(_size, Constants.CENLEN); // filename length
data.writeUInt16LE(_fnameLen, Constants.CENNAM); // extra field length
data.writeUInt16LE(_extraLen, Constants.CENEXT); // file comment length
data.writeUInt16LE(_comLen, Constants.CENCOM); // volume number start
data.writeUInt16LE(_diskStart, Constants.CENDSK); // internal file attributes
data.writeUInt16LE(_inattr, Constants.CENATT); // external file attributes
data.writeUInt32LE(_attr, Constants.CENATX); // LOC header offset
data.writeUInt32LE(_offset, Constants.CENOFF); // fill all with
data.fill(0x00, Constants.CENHDR);
return data;
},
toString: function () {
return '{\n' + '\t"made" : ' + _verMade + ",\n" + '\t"version" : ' + _version + ",\n" + '\t"flags" : ' + _flags + ",\n" + '\t"method" : ' + Utils.methodToString(_method) + ",\n" + '\t"time" : ' + this.time + ",\n" + '\t"crc" : 0x' + _crc.toString(16).toUpperCase() + ",\n" + '\t"compressedSize" : ' + _compressedSize + " bytes,\n" + '\t"size" : ' + _size + " bytes,\n" + '\t"fileNameLength" : ' + _fnameLen + ",\n" + '\t"extraLength" : ' + _extraLen + " bytes,\n" + '\t"commentLength" : ' + _comLen + " bytes,\n" + '\t"diskNumStart" : ' + _diskStart + ",\n" + '\t"inAttr" : ' + _inattr + ",\n" + '\t"attr" : ' + _attr + ",\n" + '\t"offset" : ' + _offset + ",\n" + '\t"entryHeaderSize" : ' + (Constants.CENHDR + _fnameLen + _extraLen + _comLen) + " bytes\n" + '}';
}
};
};
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/headers/index.js":
/*!******************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/headers/index.js ***!
\******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
exports.EntryHeader = __webpack_require__(/*! ./entryHeader */ "./packages/loot-core/node_modules/adm-zip/headers/entryHeader.js");
exports.MainHeader = __webpack_require__(/*! ./mainHeader */ "./packages/loot-core/node_modules/adm-zip/headers/mainHeader.js");
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/headers/mainHeader.js":
/*!***********************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/headers/mainHeader.js ***!
\***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var Utils = __webpack_require__(/*! ../util */ "./packages/loot-core/node_modules/adm-zip/util/index.js"),
Constants = Utils.Constants;
/* The entries in the end of central directory */
module.exports = function () {
var _volumeEntries = 0,
_totalEntries = 0,
_size = 0,
_offset = 0,
_commentLength = 0;
return {
get diskEntries() {
return _volumeEntries;
},
set diskEntries(
/*Number*/
val) {
_volumeEntries = _totalEntries = val;
},
get totalEntries() {
return _totalEntries;
},
set totalEntries(
/*Number*/
val) {
_totalEntries = _volumeEntries = val;
},
get size() {
return _size;
},
set size(
/*Number*/
val) {
_size = val;
},
get offset() {
return _offset;
},
set offset(
/*Number*/
val) {
_offset = val;
},
get commentLength() {
return _commentLength;
},
set commentLength(
/*Number*/
val) {
_commentLength = val;
},
get mainHeaderSize() {
return Constants.ENDHDR + _commentLength;
},
loadFromBinary: function (
/*Buffer*/
data) {
// data should be 22 bytes and start with "PK 05 06"
if (data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) throw Utils.Errors.INVALID_END; // number of entries on this volume
_volumeEntries = data.readUInt16LE(Constants.ENDSUB); // total number of entries
_totalEntries = data.readUInt16LE(Constants.ENDTOT); // central directory size in bytes
_size = data.readUInt32LE(Constants.ENDSIZ); // offset of first CEN header
_offset = data.readUInt32LE(Constants.ENDOFF); // zip file comment length
_commentLength = data.readUInt16LE(Constants.ENDCOM);
},
toBinary: function () {
var b = Buffer.alloc(Constants.ENDHDR + _commentLength); // "PK 05 06" signature
b.writeUInt32LE(Constants.ENDSIG, 0);
b.writeUInt32LE(0, 4); // number of entries on this volume
b.writeUInt16LE(_volumeEntries, Constants.ENDSUB); // total number of entries
b.writeUInt16LE(_totalEntries, Constants.ENDTOT); // central directory size in bytes
b.writeUInt32LE(_size, Constants.ENDSIZ); // offset of first CEN header
b.writeUInt32LE(_offset, Constants.ENDOFF); // zip file comment length
b.writeUInt16LE(_commentLength, Constants.ENDCOM); // fill comment memory with spaces so no garbage is left there
b.fill(" ", Constants.ENDHDR);
return b;
},
toString: function () {
return '{\n' + '\t"diskEntries" : ' + _volumeEntries + ",\n" + '\t"totalEntries" : ' + _totalEntries + ",\n" + '\t"size" : ' + _size + " bytes,\n" + '\t"offset" : 0x' + _offset.toString(16).toUpperCase() + ",\n" + '\t"commentLength" : 0x' + _commentLength + "\n" + '}';
}
};
};
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/methods/deflater.js":
/*!*********************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/methods/deflater.js ***!
\*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = function (
/*Buffer*/
inbuf) {
var zlib = __webpack_require__(/*! zlib */ "zlib");
var opts = {
chunkSize: (parseInt(inbuf.length / 1024) + 1) * 1024
};
return {
deflate: function () {
return zlib.deflateRawSync(inbuf, opts);
},
deflateAsync: function (
/*Function*/
callback) {
var tmp = zlib.createDeflateRaw(opts),
parts = [],
total = 0;
tmp.on('data', function (data) {
parts.push(data);
total += data.length;
});
tmp.on('end', function () {
var buf = Buffer.alloc(total),
written = 0;
buf.fill(0);
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
part.copy(buf, written);
written += part.length;
}
callback && callback(buf);
});
tmp.end(inbuf);
}
};
};
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/methods/index.js":
/*!******************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/methods/index.js ***!
\******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
exports.Deflater = __webpack_require__(/*! ./deflater */ "./packages/loot-core/node_modules/adm-zip/methods/deflater.js");
exports.Inflater = __webpack_require__(/*! ./inflater */ "./packages/loot-core/node_modules/adm-zip/methods/inflater.js");
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/methods/inflater.js":
/*!*********************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/methods/inflater.js ***!
\*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = function (
/*Buffer*/
inbuf) {
var zlib = __webpack_require__(/*! zlib */ "zlib");
return {
inflate: function () {
return zlib.inflateRawSync(inbuf);
},
inflateAsync: function (
/*Function*/
callback) {
var tmp = zlib.createInflateRaw(),
parts = [],
total = 0;
tmp.on('data', function (data) {
parts.push(data);
total += data.length;
});
tmp.on('end', function () {
var buf = Buffer.alloc(total),
written = 0;
buf.fill(0);
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
part.copy(buf, written);
written += part.length;
}
callback && callback(buf);
});
tmp.end(inbuf);
}
};
};
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/util/constants.js":
/*!*******************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/util/constants.js ***!
\*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = {
/* The local file header */
LOCHDR: 30,
// LOC header size
LOCSIG: 0x04034b50,
// "PK\003\004"
LOCVER: 4,
// version needed to extract
LOCFLG: 6,
// general purpose bit flag
LOCHOW: 8,
// compression method
LOCTIM: 10,
// modification time (2 bytes time, 2 bytes date)
LOCCRC: 14,
// uncompressed file crc-32 value
LOCSIZ: 18,
// compressed size
LOCLEN: 22,
// uncompressed size
LOCNAM: 26,
// filename length
LOCEXT: 28,
// extra field length
/* The Data descriptor */
EXTSIG: 0x08074b50,
// "PK\007\008"
EXTHDR: 16,
// EXT header size
EXTCRC: 4,
// uncompressed file crc-32 value
EXTSIZ: 8,
// compressed size
EXTLEN: 12,
// uncompressed size
/* The central directory file header */
CENHDR: 46,
// CEN header size
CENSIG: 0x02014b50,
// "PK\001\002"
CENVEM: 4,
// version made by
CENVER: 6,
// version needed to extract
CENFLG: 8,
// encrypt, decrypt flags
CENHOW: 10,
// compression method
CENTIM: 12,
// modification time (2 bytes time, 2 bytes date)
CENCRC: 16,
// uncompressed file crc-32 value
CENSIZ: 20,
// compressed size
CENLEN: 24,
// uncompressed size
CENNAM: 28,
// filename length
CENEXT: 30,
// extra field length
CENCOM: 32,
// file comment length
CENDSK: 34,
// volume number start
CENATT: 36,
// internal file attributes
CENATX: 38,
// external file attributes (host system dependent)
CENOFF: 42,
// LOC header offset
/* The entries in the end of central directory */
ENDHDR: 22,
// END header size
ENDSIG: 0x06054b50,
// "PK\005\006"
ENDSUB: 8,
// number of entries on this disk
ENDTOT: 10,
// total number of entries
ENDSIZ: 12,
// central directory size in bytes
ENDOFF: 16,
// offset of first CEN header
ENDCOM: 20,
// zip file comment length
/* Compression methods */
STORED: 0,
// no compression
SHRUNK: 1,
// shrunk
REDUCED1: 2,
// reduced with compression factor 1
REDUCED2: 3,
// reduced with compression factor 2
REDUCED3: 4,
// reduced with compression factor 3
REDUCED4: 5,
// reduced with compression factor 4
IMPLODED: 6,
// imploded
// 7 reserved
DEFLATED: 8,
// deflated
ENHANCED_DEFLATED: 9,
// enhanced deflated
PKWARE: 10,
// PKWare DCL imploded
// 11 reserved
BZIP2: 12,
// compressed using BZIP2
// 13 reserved
LZMA: 14,
// LZMA
// 15-17 reserved
IBM_TERSE: 18,
// compressed using IBM TERSE
IBM_LZ77: 19,
//IBM LZ77 z
/* General purpose bit flag */
FLG_ENC: 0,
// encripted file
FLG_COMP1: 1,
// compression option
FLG_COMP2: 2,
// compression option
FLG_DESC: 4,
// data descriptor
FLG_ENH: 8,
// enhanced deflation
FLG_STR: 16,
// strong encryption
FLG_LNG: 1024,
// language encoding
FLG_MSK: 4096,
// mask header values
/* Load type */
FILE: 0,
BUFFER: 1,
NONE: 2,
/* 4.5 Extensible data fields */
EF_ID: 0,
EF_SIZE: 2,
/* Header IDs */
ID_ZIP64: 0x0001,
ID_AVINFO: 0x0007,
ID_PFS: 0x0008,
ID_OS2: 0x0009,
ID_NTFS: 0x000a,
ID_OPENVMS: 0x000c,
ID_UNIX: 0x000d,
ID_FORK: 0x000e,
ID_PATCH: 0x000f,
ID_X509_PKCS7: 0x0014,
ID_X509_CERTID_F: 0x0015,
ID_X509_CERTID_C: 0x0016,
ID_STRONGENC: 0x0017,
ID_RECORD_MGT: 0x0018,
ID_X509_PKCS7_RL: 0x0019,
ID_IBM1: 0x0065,
ID_IBM2: 0x0066,
ID_POSZIP: 0x4690,
EF_ZIP64_OR_32: 0xffffffff,
EF_ZIP64_OR_16: 0xffff,
EF_ZIP64_SUNCOMP: 0,
EF_ZIP64_SCOMP: 8,
EF_ZIP64_RHO: 16,
EF_ZIP64_DSN: 24
};
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/util/errors.js":
/*!****************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/util/errors.js ***!
\****************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = {
/* Header error messages */
"INVALID_LOC": "Invalid LOC header (bad signature)",
"INVALID_CEN": "Invalid CEN header (bad signature)",
"INVALID_END": "Invalid END header (bad signature)",
/* ZipEntry error messages*/
"NO_DATA": "Nothing to decompress",
"BAD_CRC": "CRC32 checksum failed",
"FILE_IN_THE_WAY": "There is a file in the way: %s",
"UNKNOWN_METHOD": "Invalid/unsupported compression method",
/* Inflater error messages */
"AVAIL_DATA": "inflate::Available inflate data did not terminate",
"INVALID_DISTANCE": "inflate::Invalid literal/length or distance code in fixed or dynamic block",
"TO_MANY_CODES": "inflate::Dynamic block code description: too many length or distance codes",
"INVALID_REPEAT_LEN": "inflate::Dynamic block code description: repeat more than specified lengths",
"INVALID_REPEAT_FIRST": "inflate::Dynamic block code description: repeat lengths with no first length",
"INCOMPLETE_CODES": "inflate::Dynamic block code description: code lengths codes incomplete",
"INVALID_DYN_DISTANCE": "inflate::Dynamic block code description: invalid distance code lengths",
"INVALID_CODES_LEN": "inflate::Dynamic block code description: invalid literal/length code lengths",
"INVALID_STORE_BLOCK": "inflate::Stored block length did not match one's complement",
"INVALID_BLOCK_TYPE": "inflate::Invalid block type (type == 3)",
/* ADM-ZIP error messages */
"CANT_EXTRACT_FILE": "Could not extract the file",
"CANT_OVERRIDE": "Target file already exists",
"NO_ZIP": "No zip file was loaded",
"NO_ENTRY": "Entry doesn't exist",
"DIRECTORY_CONTENT_ERROR": "A directory cannot have content",
"FILE_NOT_FOUND": "File not found: %s",
"NOT_IMPLEMENTED": "Not implemented",
"INVALID_FILENAME": "Invalid filename",
"INVALID_FORMAT": "Invalid or unsupported zip format. No END header found"
};
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/util/fattr.js":
/*!***************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/util/fattr.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var fs = __webpack_require__(/*! ./fileSystem */ "./packages/loot-core/node_modules/adm-zip/util/fileSystem.js").require(),
pth = __webpack_require__(/*! path */ "path");
fs.existsSync = fs.existsSync || pth.existsSync;
module.exports = function (
/*String*/
path) {
var _path = path || "",
_permissions = 0,
_obj = newAttr(),
_stat = null;
function newAttr() {
return {
directory: false,
readonly: false,
hidden: false,
executable: false,
mtime: 0,
atime: 0
};
}
if (_path && fs.existsSync(_path)) {
_stat = fs.statSync(_path);
_obj.directory = _stat.isDirectory();
_obj.mtime = _stat.mtime;
_obj.atime = _stat.atime;
_obj.executable = !!(1 & parseInt((_stat.mode & parseInt("777", 8)).toString(8)[0]));
_obj.readonly = !!(2 & parseInt((_stat.mode & parseInt("777", 8)).toString(8)[0]));
_obj.hidden = pth.basename(_path)[0] === ".";
} else {
console.warn("Invalid path: " + _path);
}
return {
get directory() {
return _obj.directory;
},
get readOnly() {
return _obj.readonly;
},
get hidden() {
return _obj.hidden;
},
get mtime() {
return _obj.mtime;
},
get atime() {
return _obj.atime;
},
get executable() {
return _obj.executable;
},
decodeAttributes: function (val) {},
encodeAttributes: function (val) {},
toString: function () {
return '{\n' + '\t"path" : "' + _path + ",\n" + '\t"isDirectory" : ' + _obj.directory + ",\n" + '\t"isReadOnly" : ' + _obj.readonly + ",\n" + '\t"isHidden" : ' + _obj.hidden + ",\n" + '\t"isExecutable" : ' + _obj.executable + ",\n" + '\t"mTime" : ' + _obj.mtime + "\n" + '\t"aTime" : ' + _obj.atime + "\n" + '}';
}
};
};
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/util/fileSystem.js":
/*!********************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/util/fileSystem.js ***!
\********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
exports.require = function () {
var fs = __webpack_require__(/*! fs */ "fs");
if (process.versions['electron']) {
try {
originalFs = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module 'original-fs'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
if (Object.keys(originalFs).length > 0) {
fs = originalFs;
}
} catch (e) {}
}
return fs;
};
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/util/index.js":
/*!***************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/util/index.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! ./utils */ "./packages/loot-core/node_modules/adm-zip/util/utils.js");
module.exports.FileSystem = __webpack_require__(/*! ./fileSystem */ "./packages/loot-core/node_modules/adm-zip/util/fileSystem.js");
module.exports.Constants = __webpack_require__(/*! ./constants */ "./packages/loot-core/node_modules/adm-zip/util/constants.js");
module.exports.Errors = __webpack_require__(/*! ./errors */ "./packages/loot-core/node_modules/adm-zip/util/errors.js");
module.exports.FileAttr = __webpack_require__(/*! ./fattr */ "./packages/loot-core/node_modules/adm-zip/util/fattr.js");
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/util/utils.js":
/*!***************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/util/utils.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var fs = __webpack_require__(/*! ./fileSystem */ "./packages/loot-core/node_modules/adm-zip/util/fileSystem.js").require(),
pth = __webpack_require__(/*! path */ "path");
fs.existsSync = fs.existsSync || pth.existsSync;
module.exports = function () {
var crcTable = [],
Constants = __webpack_require__(/*! ./constants */ "./packages/loot-core/node_modules/adm-zip/util/constants.js"),
Errors = __webpack_require__(/*! ./errors */ "./packages/loot-core/node_modules/adm-zip/util/errors.js"),
PATH_SEPARATOR = pth.sep;
function mkdirSync(
/*String*/
path) {
var resolvedPath = path.split(PATH_SEPARATOR)[0];
path.split(PATH_SEPARATOR).forEach(function (name) {
if (!name || name.substr(-1, 1) === ":") return;
resolvedPath += PATH_SEPARATOR + name;
var stat;
try {
stat = fs.statSync(resolvedPath);
} catch (e) {
fs.mkdirSync(resolvedPath);
}
if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY.replace("%s", resolvedPath);
});
}
function findSync(
/*String*/
dir,
/*RegExp*/
pattern,
/*Boolean*/
recoursive) {
if (typeof pattern === 'boolean') {
recoursive = pattern;
pattern = undefined;
}
var files = [];
fs.readdirSync(dir).forEach(function (file) {
var path = pth.join(dir, file);
if (fs.statSync(path).isDirectory() && recoursive) files = files.concat(findSync(path, pattern, recoursive));
if (!pattern || pattern.test(path)) {
files.push(pth.normalize(path) + (fs.statSync(path).isDirectory() ? PATH_SEPARATOR : ""));
}
});
return files;
}
return {
makeDir: function (
/*String*/
path) {
mkdirSync(path);
},
crc32: function (buf) {
if (typeof buf === 'string') {
buf = Buffer.alloc(buf.length, buf);
}
var b = Buffer.alloc(4);
if (!crcTable.length) {
for (var n = 0; n < 256; n++) {
var c = n;
for (var k = 8; --k >= 0;) //
if ((c & 1) !== 0) {
c = 0xedb88320 ^ c >>> 1;
} else {
c = c >>> 1;
}
if (c < 0) {
b.writeInt32LE(c, 0);
c = b.readUInt32LE(0);
}
crcTable[n] = c;
}
}
var crc = 0,
off = 0,
len = buf.length,
c1 = ~crc;
while (--len >= 0) c1 = crcTable[(c1 ^ buf[off++]) & 0xff] ^ c1 >>> 8;
crc = ~c1;
b.writeInt32LE(crc & 0xffffffff, 0);
return b.readUInt32LE(0);
},
methodToString: function (
/*Number*/
method) {
switch (method) {
case Constants.STORED:
return 'STORED (' + method + ')';
case Constants.DEFLATED:
return 'DEFLATED (' + method + ')';
default:
return 'UNSUPPORTED (' + method + ')';
}
},
writeFileTo: function (
/*String*/
path,
/*Buffer*/
content,
/*Boolean*/
overwrite,
/*Number*/
attr) {
if (fs.existsSync(path)) {
if (!overwrite) return false; // cannot overwrite
var stat = fs.statSync(path);
if (stat.isDirectory()) {
return false;
}
}
var folder = pth.dirname(path);
if (!fs.existsSync(folder)) {
mkdirSync(folder);
}
var fd;
try {
fd = fs.openSync(path, 'w', 438); // 0666
} catch (e) {
fs.chmodSync(path, 438);
fd = fs.openSync(path, 'w', 438);
}
if (fd) {
try {
fs.writeSync(fd, content, 0, content.length, 0);
} catch (e) {
throw e;
} finally {
fs.closeSync(fd);
}
}
fs.chmodSync(path, attr || 438);
return true;
},
writeFileToAsync: function (
/*String*/
path,
/*Buffer*/
content,
/*Boolean*/
overwrite,
/*Number*/
attr,
/*Function*/
callback) {
if (typeof attr === 'function') {
callback = attr;
attr = undefined;
}
fs.exists(path, function (exists) {
if (exists && !overwrite) return callback(false);
fs.stat(path, function (err, stat) {
if (exists && stat.isDirectory()) {
return callback(false);
}
var folder = pth.dirname(path);
fs.exists(folder, function (exists) {
if (!exists) mkdirSync(folder);
fs.open(path, 'w', 438, function (err, fd) {
if (err) {
fs.chmod(path, 438, function () {
fs.open(path, 'w', 438, function (err, fd) {
fs.write(fd, content, 0, content.length, 0, function () {
fs.close(fd, function () {
fs.chmod(path, attr || 438, function () {
callback(true);
});
});
});
});
});
} else {
if (fd) {
fs.write(fd, content, 0, content.length, 0, function () {
fs.close(fd, function () {
fs.chmod(path, attr || 438, function () {
callback(true);
});
});
});
} else {
fs.chmod(path, attr || 438, function () {
callback(true);
});
}
}
});
});
});
});
},
findFiles: function (
/*String*/
path) {
return findSync(path, true);
},
getAttributes: function (
/*String*/
path) {},
setAttributes: function (
/*String*/
path) {},
toBuffer: function (input) {
if (Buffer.isBuffer(input)) {
return input;
} else {
if (input.length === 0) {
return Buffer.alloc(0);
}
return Buffer.from(input, 'utf8');
}
},
Constants: Constants,
Errors: Errors
};
}();
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/zipEntry.js":
/*!*************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/zipEntry.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var Utils = __webpack_require__(/*! ./util */ "./packages/loot-core/node_modules/adm-zip/util/index.js"),
Headers = __webpack_require__(/*! ./headers */ "./packages/loot-core/node_modules/adm-zip/headers/index.js"),
Constants = Utils.Constants,
Methods = __webpack_require__(/*! ./methods */ "./packages/loot-core/node_modules/adm-zip/methods/index.js");
module.exports = function (
/*Buffer*/
input) {
var _entryHeader = new Headers.EntryHeader(),
_entryName = Buffer.alloc(0),
_comment = Buffer.alloc(0),
_isDirectory = false,
uncompressedData = null,
_extra = Buffer.alloc(0);
function getCompressedDataFromZip() {
if (!input || !Buffer.isBuffer(input)) {
return Buffer.alloc(0);
}
_entryHeader.loadDataHeaderFromBinary(input);
return input.slice(_entryHeader.realDataOffset, _entryHeader.realDataOffset + _entryHeader.compressedSize);
}
function crc32OK(data) {
// if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the header is written
if ((_entryHeader.flags & 0x8) !== 0x8) {
if (Utils.crc32(data) !== _entryHeader.dataHeader.crc) {
return false;
}
} else {// @TODO: load and check data descriptor header
// The fields in the local header are filled with zero, and the CRC-32 and size are appended in a 12-byte structure
// (optionally preceded by a 4-byte signature) immediately after the compressed data:
}
return true;
}
function decompress(
/*Boolean*/
async,
/*Function*/
callback,
/*String*/
pass) {
if (typeof callback === 'undefined' && typeof async === 'string') {
pass = async;
async = void 0;
}
if (_isDirectory) {
if (async && callback) {
callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR); //si added error.
}
return Buffer.alloc(0);
}
var compressedData = getCompressedDataFromZip();
if (compressedData.length === 0) {
if (async && callback) callback(compressedData, Utils.Errors.NO_DATA); //si added error.
return compressedData;
}
var data = Buffer.alloc(_entryHeader.size);
switch (_entryHeader.method) {
case Utils.Constants.STORED:
compressedData.copy(data);
if (!crc32OK(data)) {
if (async && callback) callback(data, Utils.Errors.BAD_CRC); //si added error
return Utils.Errors.BAD_CRC;
} else {
//si added otherwise did not seem to return data.
if (async && callback) callback(data);
return data;
}
case Utils.Constants.DEFLATED:
var inflater = new Methods.Inflater(compressedData);
if (!async) {
var result = inflater.inflate(data);
result.copy(data, 0);
if (!crc32OK(data)) {
console.warn(Utils.Errors.BAD_CRC + " " + _entryName.toString());
}
return data;
} else {
inflater.inflateAsync(function (result) {
result.copy(data, 0);
if (!crc32OK(data)) {
if (callback) callback(data, Utils.Errors.BAD_CRC); //si added error
} else {
//si added otherwise did not seem to return data.
if (callback) callback(data);
}
});
}
break;
default:
if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD);
return Utils.Errors.UNKNOWN_METHOD;
}
}
function compress(
/*Boolean*/
async,
/*Function*/
callback) {
if ((!uncompressedData || !uncompressedData.length) && Buffer.isBuffer(input)) {
// no data set or the data wasn't changed to require recompression
if (async && callback) callback(getCompressedDataFromZip());
return getCompressedDataFromZip();
}
if (uncompressedData.length && !_isDirectory) {
var compressedData; // Local file header
switch (_entryHeader.method) {
case Utils.Constants.STORED:
_entryHeader.compressedSize = _entryHeader.size;
compressedData = Buffer.alloc(uncompressedData.length);
uncompressedData.copy(compressedData);
if (async && callback) callback(compressedData);
return compressedData;
default:
case Utils.Constants.DEFLATED:
var deflater = new Methods.Deflater(uncompressedData);
if (!async) {
var deflated = deflater.deflate();
_entryHeader.compressedSize = deflated.length;
return deflated;
} else {
deflater.deflateAsync(function (data) {
compressedData = Buffer.alloc(data.length);
_entryHeader.compressedSize = data.length;
data.copy(compressedData);
callback && callback(compressedData);
});
}
deflater = null;
break;
}
} else {
if (async && callback) {
callback(Buffer.alloc(0));
} else {
return Buffer.alloc(0);
}
}
}
function readUInt64LE(buffer, offset) {
return (buffer.readUInt32LE(offset + 4) << 4) + buffer.readUInt32LE(offset);
}
function parseExtra(data) {
var offset = 0;
var signature, size, part;
while (offset < data.length) {
signature = data.readUInt16LE(offset);
offset += 2;
size = data.readUInt16LE(offset);
offset += 2;
part = data.slice(offset, offset + size);
offset += size;
if (Constants.ID_ZIP64 === signature) {
parseZip64ExtendedInformation(part);
}
}
} //Override header field values with values from the ZIP64 extra field
function parseZip64ExtendedInformation(data) {
var size, compressedSize, offset, diskNumStart;
if (data.length >= Constants.EF_ZIP64_SCOMP) {
size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP);
if (_entryHeader.size === Constants.EF_ZIP64_OR_32) {
_entryHeader.size = size;
}
}
if (data.length >= Constants.EF_ZIP64_RHO) {
compressedSize = readUInt64LE(data, Constants.EF_ZIP64_SCOMP);
if (_entryHeader.compressedSize === Constants.EF_ZIP64_OR_32) {
_entryHeader.compressedSize = compressedSize;
}
}
if (data.length >= Constants.EF_ZIP64_DSN) {
offset = readUInt64LE(data, Constants.EF_ZIP64_RHO);
if (_entryHeader.offset === Constants.EF_ZIP64_OR_32) {
_entryHeader.offset = offset;
}
}
if (data.length >= Constants.EF_ZIP64_DSN + 4) {
diskNumStart = data.readUInt32LE(Constants.EF_ZIP64_DSN);
if (_entryHeader.diskNumStart === Constants.EF_ZIP64_OR_16) {
_entryHeader.diskNumStart = diskNumStart;
}
}
}
return {
get entryName() {
return _entryName.toString();
},
get rawEntryName() {
return _entryName;
},
set entryName(val) {
_entryName = Utils.toBuffer(val);
var lastChar = _entryName[_entryName.length - 1];
_isDirectory = lastChar === 47 || lastChar === 92;
_entryHeader.fileNameLength = _entryName.length;
},
get extra() {
return _extra;
},
set extra(val) {
_extra = val;
_entryHeader.extraLength = val.length;
parseExtra(val);
},
get comment() {
return _comment.toString();
},
set comment(val) {
_comment = Utils.toBuffer(val);
_entryHeader.commentLength = _comment.length;
},
get name() {
var n = _entryName.toString();
return _isDirectory ? n.substr(n.length - 1).split("/").pop() : n.split("/").pop();
},
get isDirectory() {
return _isDirectory;
},
getCompressedData: function () {
return compress(false, null);
},
getCompressedDataAsync: function (
/*Function*/
callback) {
compress(true, callback);
},
setData: function (value) {
uncompressedData = Utils.toBuffer(value);
if (!_isDirectory && uncompressedData.length) {
_entryHeader.size = uncompressedData.length;
_entryHeader.method = Utils.Constants.DEFLATED;
_entryHeader.crc = Utils.crc32(value);
_entryHeader.changed = true;
} else {
// folders and blank files should be stored
_entryHeader.method = Utils.Constants.STORED;
}
},
getData: function (pass) {
if (_entryHeader.changed) {
return uncompressedData;
} else {
return decompress(false, null, pass);
}
},
getDataAsync: function (
/*Function*/
callback, pass) {
if (_entryHeader.changed) {
callback(uncompressedData);
} else {
decompress(true, callback, pass);
}
},
set attr(attr) {
_entryHeader.attr = attr;
},
get attr() {
return _entryHeader.attr;
},
set header(
/*Buffer*/
data) {
_entryHeader.loadFromBinary(data);
},
get header() {
return _entryHeader;
},
packHeader: function () {
var header = _entryHeader.entryHeaderToBinary(); // add
_entryName.copy(header, Utils.Constants.CENHDR);
if (_entryHeader.extraLength) {
_extra.copy(header, Utils.Constants.CENHDR + _entryName.length);
}
if (_entryHeader.commentLength) {
_comment.copy(header, Utils.Constants.CENHDR + _entryName.length + _entryHeader.extraLength, _comment.length);
}
return header;
},
toString: function () {
return '{\n' + '\t"entryName" : "' + _entryName.toString() + "\",\n" + '\t"name" : "' + (_isDirectory ? _entryName.toString().replace(/\/$/, '').split("/").pop() : _entryName.toString().split("/").pop()) + "\",\n" + '\t"comment" : "' + _comment.toString() + "\",\n" + '\t"isDirectory" : ' + _isDirectory + ",\n" + '\t"header" : ' + _entryHeader.toString().replace(/\t/mg, "\t\t").replace(/}/mg, "\t}") + ",\n" + '\t"compressedData" : <' + (input && input.length + " bytes buffer" || "null") + ">\n" + '\t"data" : <' + (uncompressedData && uncompressedData.length + " bytes buffer" || "null") + ">\n" + '}';
}
};
};
/***/ }),
/***/ "./packages/loot-core/node_modules/adm-zip/zipFile.js":
/*!************************************************************!*\
!*** ./packages/loot-core/node_modules/adm-zip/zipFile.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var ZipEntry = __webpack_require__(/*! ./zipEntry */ "./packages/loot-core/node_modules/adm-zip/zipEntry.js"),
Headers = __webpack_require__(/*! ./headers */ "./packages/loot-core/node_modules/adm-zip/headers/index.js"),
Utils = __webpack_require__(/*! ./util */ "./packages/loot-core/node_modules/adm-zip/util/index.js");
module.exports = function (
/*String|Buffer*/
input,
/*Number*/
inputType) {
var entryList = [],
entryTable = {},
_comment = Buffer.alloc(0),
filename = "",
fs = Utils.FileSystem.require(),
inBuffer = null,
mainHeader = new Headers.MainHeader();
if (inputType === Utils.Constants.FILE) {
// is a filename
filename = input;
inBuffer = fs.readFileSync(filename);
readMainHeader();
} else if (inputType === Utils.Constants.BUFFER) {
// is a memory buffer
inBuffer = input;
readMainHeader();
} else {// none. is a new file
}
function readEntries() {
entryTable = {};
entryList = new Array(mainHeader.diskEntries); // total number of entries
var index = mainHeader.offset; // offset of first CEN header
for (var i = 0; i < entryList.length; i++) {
var tmp = index,
entry = new ZipEntry(inBuffer);
entry.header = inBuffer.slice(tmp, tmp += Utils.Constants.CENHDR);
entry.entryName = inBuffer.slice(tmp, tmp += entry.header.fileNameLength);
if (entry.header.extraLength) {
entry.extra = inBuffer.slice(tmp, tmp += entry.header.extraLength);
}
if (entry.header.commentLength) entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength);
index += entry.header.entryHeaderSize;
entryList[i] = entry;
entryTable[entry.entryName] = entry;
}
}
function readMainHeader() {
var i = inBuffer.length - Utils.Constants.ENDHDR,
// END header size
n = Math.max(0, i - 0xFFFF),
// 0xFFFF is the max zip file comment length
endOffset = -1; // Start offset of the END header
for (i; i >= n; i--) {
if (inBuffer[i] !== 0x50) continue; // quick check that the byte is 'P'
if (inBuffer.readUInt32LE(i) === Utils.Constants.ENDSIG) {
// "PK\005\006"
endOffset = i;
break;
}
}
if (!~endOffset) throw Utils.Errors.INVALID_FORMAT;
mainHeader.loadFromBinary(inBuffer.slice(endOffset, endOffset + Utils.Constants.ENDHDR));
if (mainHeader.commentLength) {
_comment = inBuffer.slice(endOffset + Utils.Constants.ENDHDR);
}
readEntries();
}
return {
/**
* Returns an array of ZipEntry objects existent in the current opened archive
* @return Array
*/
get entries() {
return entryList;
},
/**
* Archive comment
* @return {String}
*/
get comment() {
return _comment.toString();
},
set comment(val) {
mainHeader.commentLength = val.length;
_comment = val;
},
/**
* Returns a reference to the entry with the given name or null if entry is inexistent
*
* @param entryName
* @return ZipEntry
*/
getEntry: function (
/*String*/
entryName) {
return entryTable[entryName] || null;
},
/**
* Adds the given entry to the entry list
*
* @param entry
*/
setEntry: function (
/*ZipEntry*/
entry) {
entryList.push(entry);
entryTable[entry.entryName] = entry;
mainHeader.totalEntries = entryList.length;
},
/**
* Removes the entry with the given name from the entry list.
*
* If the entry is a directory, then all nested files and directories will be removed
* @param entryName
*/
deleteEntry: function (
/*String*/
entryName) {
var entry = entryTable[entryName];
if (entry && entry.isDirectory) {
var _self = this;
this.getEntryChildren(entry).forEach(function (child) {
if (child.entryName !== entryName) {
_self.deleteEntry(child.entryName);
}
});
}
entryList.splice(entryList.indexOf(entry), 1);
delete entryTable[entryName];
mainHeader.totalEntries = entryList.length;
},
/**
* Iterates and returns all nested files and directories of the given entry
*
* @param entry
* @return Array
*/
getEntryChildren: function (
/*ZipEntry*/
entry) {
if (entry.isDirectory) {
var list = [],
name = entry.entryName,
len = name.length;
entryList.forEach(function (zipEntry) {
if (zipEntry.entryName.substr(0, len) === name) {
list.push(zipEntry);
}
});
return list;
}
return [];
},
/**
* Returns the zip file
*
* @return Buffer
*/
compressToBuffer: function () {
if (entryList.length > 1) {
entryList.sort(function (a, b) {
var nameA = a.entryName.toLowerCase();
var nameB = b.entryName.toLowerCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
});
}
var totalSize = 0,
dataBlock = [],
entryHeaders = [],
dindex = 0;
mainHeader.size = 0;
mainHeader.offset = 0;
entryList.forEach(function (entry) {
// compress data and set local and entry header accordingly. Reason why is called first
var compressedData = entry.getCompressedData(); // data header
entry.header.offset = dindex;
var dataHeader = entry.header.dataHeaderToBinary();
var entryNameLen = entry.rawEntryName.length;
var extra = entry.extra.toString();
var postHeader = Buffer.alloc(entryNameLen + extra.length);
entry.rawEntryName.copy(postHeader, 0);
postHeader.fill(extra, entryNameLen);
var dataLength = dataHeader.length + postHeader.length + compressedData.length;
dindex += dataLength;
dataBlock.push(dataHeader);
dataBlock.push(postHeader);
dataBlock.push(compressedData);
var entryHeader = entry.packHeader();
entryHeaders.push(entryHeader);
mainHeader.size += entryHeader.length;
totalSize += dataLength + entryHeader.length;
});
totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length
// point to end of data and beginning of central directory first record
mainHeader.offset = dindex;
dindex = 0;
var outBuffer = Buffer.alloc(totalSize);
dataBlock.forEach(function (content) {
content.copy(outBuffer, dindex); // write data blocks
dindex += content.length;
});
entryHeaders.forEach(function (content) {
content.copy(outBuffer, dindex); // write central directory entries
dindex += content.length;
});
var mh = mainHeader.toBinary();
if (_comment) {
_comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment
}
mh.copy(outBuffer, dindex); // write main header
return outBuffer;
},
toAsyncBuffer: function (
/*Function*/
onSuccess,
/*Function*/
onFail,
/*Function*/
onItemStart,
/*Function*/
onItemEnd) {
if (entryList.length > 1) {
entryList.sort(function (a, b) {
var nameA = a.entryName.toLowerCase();
var nameB = b.entryName.toLowerCase();
if (nameA > nameB) {
return -1;
}
if (nameA < nameB) {
return 1;
}
return 0;
});
}
var totalSize = 0,
dataBlock = [],
entryHeaders = [],
dindex = 0;
mainHeader.size = 0;
mainHeader.offset = 0;
var compress = function (entryList) {
var self = arguments.callee;
if (entryList.length) {
var entry = entryList.pop();
var name = entry.entryName + entry.extra.toString();
if (onItemStart) onItemStart(name);
entry.getCompressedDataAsync(function (compressedData) {
if (onItemEnd) onItemEnd(name);
entry.header.offset = dindex; // data header
var dataHeader = entry.header.dataHeaderToBinary();
var postHeader;
try {
postHeader = Buffer.alloc(name.length, name); // using alloc will work on node 5.x+
} catch (e) {
postHeader = new Buffer(name); // use deprecated method if alloc fails...
}
var dataLength = dataHeader.length + postHeader.length + compressedData.length;
dindex += dataLength;
dataBlock.push(dataHeader);
dataBlock.push(postHeader);
dataBlock.push(compressedData);
var entryHeader = entry.packHeader();
entryHeaders.push(entryHeader);
mainHeader.size += entryHeader.length;
totalSize += dataLength + entryHeader.length;
if (entryList.length) {
self(entryList);
} else {
totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length
// point to end of data and beginning of central directory first record
mainHeader.offset = dindex;
dindex = 0;
var outBuffer = Buffer.alloc(totalSize);
dataBlock.forEach(function (content) {
content.copy(outBuffer, dindex); // write data blocks
dindex += content.length;
});
entryHeaders.forEach(function (content) {
content.copy(outBuffer, dindex); // write central directory entries
dindex += content.length;
});
var mh = mainHeader.toBinary();
if (_comment) {
_comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment
}
mh.copy(outBuffer, dindex); // write main header
onSuccess(outBuffer);
}
});
}
};
compress(entryList);
}
};
};
/***/ }),
/***/ "./packages/loot-core/node_modules/lru-cache/index.js":
/*!************************************************************!*\
!*** ./packages/loot-core/node_modules/lru-cache/index.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// A linked list to keep track of recently-used-ness
const Yallist = __webpack_require__(/*! yallist */ "./packages/loot-core/node_modules/yallist/yallist.js");
const MAX = Symbol('max');
const LENGTH = Symbol('length');
const LENGTH_CALCULATOR = Symbol('lengthCalculator');
const ALLOW_STALE = Symbol('allowStale');
const MAX_AGE = Symbol('maxAge');
const DISPOSE = Symbol('dispose');
const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet');
const LRU_LIST = Symbol('lruList');
const CACHE = Symbol('cache');
const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet');
const naiveLength = () => 1; // lruList is a yallist where the head is the youngest
// item, and the tail is the oldest. the list contains the Hit
// objects as the entries.
// Each Hit object has a reference to its Yallist.Node. This
// never changes.
//
// cache is a Map (or PseudoMap) that matches the keys to
// the Yallist.Node object.
class LRUCache {
constructor(options) {
if (typeof options === 'number') options = {
max: options
};
if (!options) options = {};
if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number'); // Kind of weird to have a default max of Infinity, but oh well.
const max = this[MAX] = options.max || Infinity;
const lc = options.length || naiveLength;
this[LENGTH_CALCULATOR] = typeof lc !== 'function' ? naiveLength : lc;
this[ALLOW_STALE] = options.stale || false;
if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number');
this[MAX_AGE] = options.maxAge || 0;
this[DISPOSE] = options.dispose;
this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false;
this.reset();
} // resize the cache when the max changes.
set max(mL) {
if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number');
this[MAX] = mL || Infinity;
trim(this);
}
get max() {
return this[MAX];
}
set allowStale(allowStale) {
this[ALLOW_STALE] = !!allowStale;
}
get allowStale() {
return this[ALLOW_STALE];
}
set maxAge(mA) {
if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number');
this[MAX_AGE] = mA;
trim(this);
}
get maxAge() {
return this[MAX_AGE];
} // resize the cache when the lengthCalculator changes.
set lengthCalculator(lC) {
if (typeof lC !== 'function') lC = naiveLength;
if (lC !== this[LENGTH_CALCULATOR]) {
this[LENGTH_CALCULATOR] = lC;
this[LENGTH] = 0;
this[LRU_LIST].forEach(hit => {
hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
this[LENGTH] += hit.length;
});
}
trim(this);
}
get lengthCalculator() {
return this[LENGTH_CALCULATOR];
}
get length() {
return this[LENGTH];
}
get itemCount() {
return this[LRU_LIST].length;
}
rforEach(fn, thisp) {
thisp = thisp || this;
for (let walker = this[LRU_LIST].tail; walker !== null;) {
const prev = walker.prev;
forEachStep(this, fn, walker, thisp);
walker = prev;
}
}
forEach(fn, thisp) {
thisp = thisp || this;
for (let walker = this[LRU_LIST].head; walker !== null;) {
const next = walker.next;
forEachStep(this, fn, walker, thisp);
walker = next;
}
}
keys() {
return this[LRU_LIST].toArray().map(k => k.key);
}
values() {
return this[LRU_LIST].toArray().map(k => k.value);
}
reset() {
if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) {
this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value));
}
this[CACHE] = new Map(); // hash of items by key
this[LRU_LIST] = new Yallist(); // list of items in order of use recency
this[LENGTH] = 0; // length of items in the list
}
dump() {
return this[LRU_LIST].map(hit => isStale(this, hit) ? false : {
k: hit.key,
v: hit.value,
e: hit.now + (hit.maxAge || 0)
}).toArray().filter(h => h);
}
dumpLru() {
return this[LRU_LIST];
}
set(key, value, maxAge) {
maxAge = maxAge || this[MAX_AGE];
if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number');
const now = maxAge ? Date.now() : 0;
const len = this[LENGTH_CALCULATOR](value, key);
if (this[CACHE].has(key)) {
if (len > this[MAX]) {
del(this, this[CACHE].get(key));
return false;
}
const node = this[CACHE].get(key);
const item = node.value; // dispose of the old one before overwriting
// split out into 2 ifs for better coverage tracking
if (this[DISPOSE]) {
if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value);
}
item.now = now;
item.maxAge = maxAge;
item.value = value;
this[LENGTH] += len - item.length;
item.length = len;
this.get(key);
trim(this);
return true;
}
const hit = new Entry(key, value, len, now, maxAge); // oversized objects fall out of cache automatically.
if (hit.length > this[MAX]) {
if (this[DISPOSE]) this[DISPOSE](key, value);
return false;
}
this[LENGTH] += hit.length;
this[LRU_LIST].unshift(hit);
this[CACHE].set(key, this[LRU_LIST].head);
trim(this);
return true;
}
has(key) {
if (!this[CACHE].has(key)) return false;
const hit = this[CACHE].get(key).value;
return !isStale(this, hit);
}
get(key) {
return get(this, key, true);
}
peek(key) {
return get(this, key, false);
}
pop() {
const node = this[LRU_LIST].tail;
if (!node) return null;
del(this, node);
return node.value;
}
del(key) {
del(this, this[CACHE].get(key));
}
load(arr) {
// reset the cache
this.reset();
const now = Date.now(); // A previous serialized cache has the most recent items first
for (let l = arr.length - 1; l >= 0; l--) {
const hit = arr[l];
const expiresAt = hit.e || 0;
if (expiresAt === 0) // the item was created without expiration in a non aged cache
this.set(hit.k, hit.v);else {
const maxAge = expiresAt - now; // dont add already expired items
if (maxAge > 0) {
this.set(hit.k, hit.v, maxAge);
}
}
}
}
prune() {
this[CACHE].forEach((value, key) => get(this, key, false));
}
}
const get = (self, key, doUse) => {
const node = self[CACHE].get(key);
if (node) {
const hit = node.value;
if (isStale(self, hit)) {
del(self, node);
if (!self[ALLOW_STALE]) return undefined;
} else {
if (doUse) {
if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now();
self[LRU_LIST].unshiftNode(node);
}
}
return hit.value;
}
};
const isStale = (self, hit) => {
if (!hit || !hit.maxAge && !self[MAX_AGE]) return false;
const diff = Date.now() - hit.now;
return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && diff > self[MAX_AGE];
};
const trim = self => {
if (self[LENGTH] > self[MAX]) {
for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) {
// We know that we're about to delete this one, and also
// what the next least recently used key will be, so just
// go ahead and set it now.
const prev = walker.prev;
del(self, walker);
walker = prev;
}
}
};
const del = (self, node) => {
if (node) {
const hit = node.value;
if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value);
self[LENGTH] -= hit.length;
self[CACHE].delete(hit.key);
self[LRU_LIST].removeNode(node);
}
};
class Entry {
constructor(key, value, length, now, maxAge) {
this.key = key;
this.value = value;
this.length = length;
this.now = now;
this.maxAge = maxAge || 0;
}
}
const forEachStep = (self, fn, node, thisp) => {
let hit = node.value;
if (isStale(self, hit)) {
del(self, node);
if (!self[ALLOW_STALE]) hit = undefined;
}
if (hit) fn.call(thisp, hit.value, hit.key, self);
};
module.exports = LRUCache;
/***/ }),
/***/ "./packages/loot-core/node_modules/mitt/dist/mitt.es.js":
/*!**************************************************************!*\
!*** ./packages/loot-core/node_modules/mitt/dist/mitt.es.js ***!
\**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = (function (n) {
return {
all: n = n || new Map(),
on: function (t, e) {
var i = n.get(t);
i && i.push(e) || n.set(t, [e]);
},
off: function (t, e) {
var i = n.get(t);
i && i.splice(i.indexOf(e) >>> 0, 1);
},
emit: function (t, e) {
(n.get(t) || []).slice().map(function (n) {
n(e);
}), (n.get("*") || []).slice().map(function (n) {
n(t, e);
});
}
};
});
/***/ }),
/***/ "./packages/loot-core/node_modules/yallist/iterator.js":
/*!*************************************************************!*\
!*** ./packages/loot-core/node_modules/yallist/iterator.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Yallist) {
Yallist.prototype[Symbol.iterator] = function* () {
for (let walker = this.head; walker; walker = walker.next) {
yield walker.value;
}
};
};
/***/ }),
/***/ "./packages/loot-core/node_modules/yallist/yallist.js":
/*!************************************************************!*\
!*** ./packages/loot-core/node_modules/yallist/yallist.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = Yallist;
Yallist.Node = Node;
Yallist.create = Yallist;
function Yallist(list) {
var self = this;
if (!(self instanceof Yallist)) {
self = new Yallist();
}
self.tail = null;
self.head = null;
self.length = 0;
if (list && typeof list.forEach === 'function') {
list.forEach(function (item) {
self.push(item);
});
} else if (arguments.length > 0) {
for (var i = 0, l = arguments.length; i < l; i++) {
self.push(arguments[i]);
}
}
return self;
}
Yallist.prototype.removeNode = function (node) {
if (node.list !== this) {
throw new Error('removing node which does not belong to this list');
}
var next = node.next;
var prev = node.prev;
if (next) {
next.prev = prev;
}
if (prev) {
prev.next = next;
}
if (node === this.head) {
this.head = next;
}
if (node === this.tail) {
this.tail = prev;
}
node.list.length--;
node.next = null;
node.prev = null;
node.list = null;
};
Yallist.prototype.unshiftNode = function (node) {
if (node === this.head) {
return;
}
if (node.list) {
node.list.removeNode(node);
}
var head = this.head;
node.list = this;
node.next = head;
if (head) {
head.prev = node;
}
this.head = node;
if (!this.tail) {
this.tail = node;
}
this.length++;
};
Yallist.prototype.pushNode = function (node) {
if (node === this.tail) {
return;
}
if (node.list) {
node.list.removeNode(node);
}
var tail = this.tail;
node.list = this;
node.prev = tail;
if (tail) {
tail.next = node;
}
this.tail = node;
if (!this.head) {
this.head = node;
}
this.length++;
};
Yallist.prototype.push = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
push(this, arguments[i]);
}
return this.length;
};
Yallist.prototype.unshift = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
unshift(this, arguments[i]);
}
return this.length;
};
Yallist.prototype.pop = function () {
if (!this.tail) {
return undefined;
}
var res = this.tail.value;
this.tail = this.tail.prev;
if (this.tail) {
this.tail.next = null;
} else {
this.head = null;
}
this.length--;
return res;
};
Yallist.prototype.shift = function () {
if (!this.head) {
return undefined;
}
var res = this.head.value;
this.head = this.head.next;
if (this.head) {
this.head.prev = null;
} else {
this.tail = null;
}
this.length--;
return res;
};
Yallist.prototype.forEach = function (fn, thisp) {
thisp = thisp || this;
for (var walker = this.head, i = 0; walker !== null; i++) {
fn.call(thisp, walker.value, i, this);
walker = walker.next;
}
};
Yallist.prototype.forEachReverse = function (fn, thisp) {
thisp = thisp || this;
for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
fn.call(thisp, walker.value, i, this);
walker = walker.prev;
}
};
Yallist.prototype.get = function (n) {
for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.next;
}
if (i === n && walker !== null) {
return walker.value;
}
};
Yallist.prototype.getReverse = function (n) {
for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.prev;
}
if (i === n && walker !== null) {
return walker.value;
}
};
Yallist.prototype.map = function (fn, thisp) {
thisp = thisp || this;
var res = new Yallist();
for (var walker = this.head; walker !== null;) {
res.push(fn.call(thisp, walker.value, this));
walker = walker.next;
}
return res;
};
Yallist.prototype.mapReverse = function (fn, thisp) {
thisp = thisp || this;
var res = new Yallist();
for (var walker = this.tail; walker !== null;) {
res.push(fn.call(thisp, walker.value, this));
walker = walker.prev;
}
return res;
};
Yallist.prototype.reduce = function (fn, initial) {
var acc;
var walker = this.head;
if (arguments.length > 1) {
acc = initial;
} else if (this.head) {
walker = this.head.next;
acc = this.head.value;
} else {
throw new TypeError('Reduce of empty list with no initial value');
}
for (var i = 0; walker !== null; i++) {
acc = fn(acc, walker.value, i);
walker = walker.next;
}
return acc;
};
Yallist.prototype.reduceReverse = function (fn, initial) {
var acc;
var walker = this.tail;
if (arguments.length > 1) {
acc = initial;
} else if (this.tail) {
walker = this.tail.prev;
acc = this.tail.value;
} else {
throw new TypeError('Reduce of empty list with no initial value');
}
for (var i = this.length - 1; walker !== null; i--) {
acc = fn(acc, walker.value, i);
walker = walker.prev;
}
return acc;
};
Yallist.prototype.toArray = function () {
var arr = new Array(this.length);
for (var i = 0, walker = this.head; walker !== null; i++) {
arr[i] = walker.value;
walker = walker.next;
}
return arr;
};
Yallist.prototype.toArrayReverse = function () {
var arr = new Array(this.length);
for (var i = 0, walker = this.tail; walker !== null; i++) {
arr[i] = walker.value;
walker = walker.prev;
}
return arr;
};
Yallist.prototype.slice = function (from, to) {
to = to || this.length;
if (to < 0) {
to += this.length;
}
from = from || 0;
if (from < 0) {
from += this.length;
}
var ret = new Yallist();
if (to < from || to < 0) {
return ret;
}
if (from < 0) {
from = 0;
}
if (to > this.length) {
to = this.length;
}
for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
walker = walker.next;
}
for (; walker !== null && i < to; i++, walker = walker.next) {
ret.push(walker.value);
}
return ret;
};
Yallist.prototype.sliceReverse = function (from, to) {
to = to || this.length;
if (to < 0) {
to += this.length;
}
from = from || 0;
if (from < 0) {
from += this.length;
}
var ret = new Yallist();
if (to < from || to < 0) {
return ret;
}
if (from < 0) {
from = 0;
}
if (to > this.length) {
to = this.length;
}
for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
walker = walker.prev;
}
for (; walker !== null && i > from; i--, walker = walker.prev) {
ret.push(walker.value);
}
return ret;
};
Yallist.prototype.reverse = function () {
var head = this.head;
var tail = this.tail;
for (var walker = head; walker !== null; walker = walker.prev) {
var p = walker.prev;
walker.prev = walker.next;
walker.next = p;
}
this.head = tail;
this.tail = head;
return this;
};
function push(self, item) {
self.tail = new Node(item, self.tail, null, self);
if (!self.head) {
self.head = self.tail;
}
self.length++;
}
function unshift(self, item) {
self.head = new Node(item, null, self.head, self);
if (!self.tail) {
self.tail = self.head;
}
self.length++;
}
function Node(value, prev, next, list) {
if (!(this instanceof Node)) {
return new Node(value, prev, next, list);
}
this.list = list;
this.value = value;
if (prev) {
prev.next = this;
this.prev = prev;
} else {
this.prev = null;
}
if (next) {
next.prev = this;
this.next = next;
} else {
this.next = null;
}
}
try {
// add if support for Symbol.iterator is present
__webpack_require__(/*! ./iterator.js */ "./packages/loot-core/node_modules/yallist/iterator.js")(Yallist);
} catch (er) {}
/***/ }),
/***/ "./packages/loot-core/src/mocks/budget.js":
/*!************************************************!*\
!*** ./packages/loot-core/src/mocks/budget.js ***!
\************************************************/
/*! exports provided: createTestBudget */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createTestBudget", function() { return createTestBudget; });
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _server_sheet__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../server/sheet */ "./packages/loot-core/src/server/sheet.js");
/* harmony import */ var _server_budget_base__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../server/budget/base */ "./packages/loot-core/src/server/budget/base.js");
/* harmony import */ var _server_db__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../server/db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _server_prefs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../server/prefs */ "./packages/loot-core/src/server/prefs.js");
/* harmony import */ var _server_budget_actions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../server/budget/actions */ "./packages/loot-core/src/server/budget/actions.js");
/* harmony import */ var _server_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../server/aql/schema/run-query */ "./packages/loot-core/src/server/aql/schema/run-query.js");
/* harmony import */ var _server_sync__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../server/sync */ "./packages/loot-core/src/server/sync/index.js");
/* harmony import */ var _server_mutators__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../server/mutators */ "./packages/loot-core/src/server/mutators.js");
/* harmony import */ var _server_accounts_sync__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../server/accounts/sync */ "./packages/loot-core/src/server/accounts/sync.js");
/* harmony import */ var _shared_query__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../shared/query */ "./packages/loot-core/src/shared/query.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function pickRandom(list) {
return list[(Math.random() * list.length | 0) % list.length];
}
function number(start, end) {
return start + (end - start) * Math.random();
}
function integer(start, end) {
return number(start, end) | 0;
}
function findMin(items, field) {
let item = items[0];
for (let i = 0; i < items.length; i++) {
if (items[i][field] < item[field]) {
item = items[i];
}
}
return item;
}
function getStartingBalanceCat(categories) {
return categories.find(c => c.name === 'Starting Balances').id;
}
function extractCommonThings(payees, groups) {
let incomePayee = payees.find(p => p.name === 'Deposit');
let expensePayees = payees.filter(p => p.name !== 'Deposit' && p.name !== 'Starting Balance');
let expenseGroup = groups.find(g => g.is_income === 0);
let incomeGroup = groups.find(g => g.is_income === 1);
let categories = expenseGroup.categories.filter(c => ['Food', 'Restaurants', 'Entertainment', 'Clothing', 'General', 'Gift', 'Medical'].indexOf(c.name) !== -1);
return {
incomePayee,
expensePayees: expensePayees.filter(p => !p.bill),
incomeGroup,
expenseCategories: categories,
billCategories: groups.find(g => g.name === 'Bills').categories,
billPayees: expensePayees.filter(p => p.bill)
};
}
async function fillPrimaryChecking(handlers, account, payees, groups) {
let _extractCommonThings = extractCommonThings(payees, groups),
incomePayee = _extractCommonThings.incomePayee,
expensePayees = _extractCommonThings.expensePayees,
incomeGroup = _extractCommonThings.incomeGroup,
expenseCategories = _extractCommonThings.expenseCategories,
billCategories = _extractCommonThings.billCategories,
billPayees = _extractCommonThings.billPayees;
let numTransactions = integer(100, 200);
let transactions = [];
for (let i = 0; i < numTransactions; i++) {
let payee;
if (Math.random() < 0.09) {
payee = incomePayee;
} else {
payee = pickRandom(expensePayees);
}
let category;
if (payee.name === 'Deposit') {
category = incomeGroup.categories.find(c => c.name === 'Income');
} else {
category = pickRandom(expenseCategories);
}
let amount;
if (payee.name === 'Deposit') {
amount = integer(50000, 70000);
} else {
amount = integer(0, Math.random() < 0.05 ? -8000 : -700);
}
let transaction = {
amount,
payee: payee.id,
account: account.id,
date: _shared_months__WEBPACK_IMPORTED_MODULE_0__["subDays"](_shared_months__WEBPACK_IMPORTED_MODULE_0__["currentDay"](), i / 3 | 0),
category: category.id
};
transactions.push(transaction);
if (Math.random() < 0.2) {
let a = transaction.amount / 3 | 0;
let pick = () => payee === incomePayee ? incomeGroup.categories.find(c => c.name === 'Income').id : pickRandom(expenseCategories).id;
transaction.subtransactions = [{
amount: a,
category: pick()
}, {
amount: a,
category: pick()
}, {
amount: transaction.amount - a * 2,
category: pick()
}];
}
}
let earliestMonth = _shared_months__WEBPACK_IMPORTED_MODULE_0__["monthFromDate"](transactions[transactions.length - 1].date);
let months = _shared_months__WEBPACK_IMPORTED_MODULE_0__["rangeInclusive"](earliestMonth, _shared_months__WEBPACK_IMPORTED_MODULE_0__["currentMonth"]());
let currentDay = _shared_months__WEBPACK_IMPORTED_MODULE_0__["currentDay"]();
for (let month of months) {
let date = _shared_months__WEBPACK_IMPORTED_MODULE_0__["addDays"](month, '12');
if (_shared_months__WEBPACK_IMPORTED_MODULE_0__["isBefore"](date, currentDay)) {
transactions.push({
amount: -10000,
payee: billPayees.find(p => p.name.toLowerCase().includes('power')).id,
account: account.id,
date,
category: billCategories.find(c => c.name === 'Power').id
});
}
date = _shared_months__WEBPACK_IMPORTED_MODULE_0__["addDays"](month, '18');
if (_shared_months__WEBPACK_IMPORTED_MODULE_0__["isBefore"](date, currentDay)) {
transactions.push({
amount: -9000,
payee: billPayees.find(p => p.name.toLowerCase().includes('water')).id,
account: account.id,
date,
category: billCategories.find(c => c.name === 'Water').id
});
}
date = _shared_months__WEBPACK_IMPORTED_MODULE_0__["addDays"](month, '2');
if (_shared_months__WEBPACK_IMPORTED_MODULE_0__["isBefore"](date, currentDay)) {
transactions.push({
amount: -120000,
payee: billPayees.find(p => p.name.toLowerCase().includes('housy')).id,
account: account.id,
date,
category: billCategories.find(c => c.name === 'Mortgage').id
});
}
date = _shared_months__WEBPACK_IMPORTED_MODULE_0__["addDays"](month, '20');
if (_shared_months__WEBPACK_IMPORTED_MODULE_0__["isBefore"](date, currentDay)) {
transactions.push({
amount: -6000,
payee: billPayees.find(p => p.name.toLowerCase().includes('internet')).id,
account: account.id,
date,
category: billCategories.find(c => c.name === 'Internet').id
});
}
date = _shared_months__WEBPACK_IMPORTED_MODULE_0__["addDays"](month, '23');
if (_shared_months__WEBPACK_IMPORTED_MODULE_0__["isBefore"](date, currentDay)) {
transactions.push({
amount: -7500,
payee: billPayees.find(p => p.name.toLowerCase().includes('t-mobile')).id,
account: account.id,
date,
category: billCategories.find(c => c.name === 'Cell').id
});
}
}
let earliestDate = null;
transactions.forEach(t => {
if (earliestDate == null || t.date < earliestDate) {
earliestDate = t.date;
}
});
transactions.unshift({
amount: 100000,
payee: payees.find(p => p.name === 'Starting Balance').id,
account: account.id,
date: earliestDate,
category: getStartingBalanceCat(incomeGroup.categories),
starting_balance_flag: true
});
return Object(_server_accounts_sync__WEBPACK_IMPORTED_MODULE_9__["addTransactions"])(account.id, transactions);
}
async function fillChecking(handlers, account, payees, groups) {
let _extractCommonThings2 = extractCommonThings(payees, groups),
incomePayee = _extractCommonThings2.incomePayee,
expensePayees = _extractCommonThings2.expensePayees,
incomeGroup = _extractCommonThings2.incomeGroup,
expenseCategories = _extractCommonThings2.expenseCategories;
let numTransactions = integer(20, 40);
let transactions = [];
for (let i = 0; i < numTransactions; i++) {
let payee;
if (Math.random() < 0.04) {
payee = incomePayee;
} else {
payee = pickRandom(expensePayees);
}
let category;
if (payee.name === 'Deposit') {
category = incomeGroup.categories.find(c => c.name === 'Income');
} else {
category = pickRandom(expenseCategories);
}
let amount = payee.name === 'Deposit' ? integer(50000, 70000) : integer(0, -10000);
transactions.push({
amount,
payee: payee.id,
account: account.id,
date: _shared_months__WEBPACK_IMPORTED_MODULE_0__["subDays"](_shared_months__WEBPACK_IMPORTED_MODULE_0__["currentDay"](), i * 2 | 0),
category: category.id
});
}
transactions.unshift({
amount: integer(90000, 120000),
payee: payees.find(p => p.name === 'Starting Balance').id,
account: account.id,
date: transactions[transactions.length - 1].date,
category: getStartingBalanceCat(incomeGroup.categories),
starting_balance_flag: true
});
await handlers['transactions-batch-update']({
added: transactions,
fastMode: true
});
}
async function fillInvestment(handlers, account, payees, groups) {
let _extractCommonThings3 = extractCommonThings(payees, groups),
incomePayee = _extractCommonThings3.incomePayee,
expensePayees = _extractCommonThings3.expensePayees,
incomeGroup = _extractCommonThings3.incomeGroup,
expenseCategories = _extractCommonThings3.expenseCategories;
let numTransactions = integer(10, 30);
let transactions = [];
for (let i = 0; i < numTransactions; i++) {
let payee = incomePayee;
let category = incomeGroup.categories.find(c => c.name === 'Income');
let amount = integer(10000, 20000);
transactions.push({
amount,
payee: payee.id,
account: account.id,
date: _shared_months__WEBPACK_IMPORTED_MODULE_0__["subDays"](_shared_months__WEBPACK_IMPORTED_MODULE_0__["currentDay"](), integer(10, 360)),
category: category.id
});
}
transactions.unshift({
amount: integer(10000, 20000),
payee: payees.find(p => p.name === 'Starting Balance').id,
account: account.id,
date: findMin(transactions, 'date').date,
category: getStartingBalanceCat(incomeGroup.categories),
starting_balance_flag: true
});
await handlers['transactions-batch-update']({
added: transactions,
fastMode: true
});
}
async function fillSavings(handlers, account, payees, groups) {
let _extractCommonThings4 = extractCommonThings(payees, groups),
incomePayee = _extractCommonThings4.incomePayee,
expensePayees = _extractCommonThings4.expensePayees,
incomeGroup = _extractCommonThings4.incomeGroup,
expenseCategories = _extractCommonThings4.expenseCategories;
let numTransactions = integer(15, 40);
let transactions = [];
for (let i = 0; i < numTransactions; i++) {
let payee;
if (Math.random() < 0.3) {
payee = incomePayee;
} else {
payee = pickRandom(expensePayees);
}
let category = payee === incomePayee ? incomeGroup.categories.find(c => c.name === 'Income') : pickRandom(expenseCategories);
let amount = payee === incomePayee ? integer(10000, 80000) : integer(-10000, -2000);
transactions.push({
amount,
payee: payee.id,
account: account.id,
date: _shared_months__WEBPACK_IMPORTED_MODULE_0__["subDays"](_shared_months__WEBPACK_IMPORTED_MODULE_0__["currentDay"](), i * 5 | 0),
category: category.id
});
}
transactions.unshift({
amount: 30000,
payee: payees.find(p => p.name === 'Starting Balance').id,
account: account.id,
date: transactions[transactions.length - 1].date,
category: getStartingBalanceCat(incomeGroup.categories),
starting_balance_flag: true
});
await handlers['transactions-batch-update']({
added: transactions,
fastMode: true
});
}
async function fillMortgage(handlers, account, payees, groups) {
let _extractCommonThings5 = extractCommonThings(payees, groups),
incomePayee = _extractCommonThings5.incomePayee,
expensePayees = _extractCommonThings5.expensePayees,
incomeGroup = _extractCommonThings5.incomeGroup,
expenseCategories = _extractCommonThings5.expenseCategories;
let numTransactions = integer(7, 10);
let amount = integer(100000, 200000);
let category = incomeGroup.categories.find(c => c.name === 'Income');
let transactions = [{
amount: integer(-3000, -3500) * 100 * 100,
payee: payees.find(p => p.name === 'Starting Balance').id,
account: account.id,
date: _shared_months__WEBPACK_IMPORTED_MODULE_0__["subMonths"](_shared_months__WEBPACK_IMPORTED_MODULE_0__["currentDay"](), numTransactions) + '-02',
category: getStartingBalanceCat(incomeGroup.categories),
starting_balance_flag: true
}];
for (let i = 0; i < numTransactions; i++) {
let payee = incomePayee;
transactions.push({
amount,
payee: payee.id,
account: account.id,
date: _shared_months__WEBPACK_IMPORTED_MODULE_0__["subMonths"](_shared_months__WEBPACK_IMPORTED_MODULE_0__["currentDay"](), i) + '-02',
category: category.id,
starting_balance_flag: true
});
}
await handlers['transactions-batch-update']({
added: transactions,
fastMode: true
});
}
async function fillOther(handlers, account, payees, groups) {
let _extractCommonThings6 = extractCommonThings(payees, groups),
incomePayee = _extractCommonThings6.incomePayee,
expensePayees = _extractCommonThings6.expensePayees,
incomeGroup = _extractCommonThings6.incomeGroup,
expenseCategories = _extractCommonThings6.expenseCategories;
let numTransactions = integer(3, 6);
let category = incomeGroup.categories.find(c => c.name === 'Income');
let transactions = [{
amount: integer(3250, 3700) * 100 * 100,
payee: payees.find(p => p.name === 'Starting Balance').id,
account: account.id,
date: _shared_months__WEBPACK_IMPORTED_MODULE_0__["subMonths"](_shared_months__WEBPACK_IMPORTED_MODULE_0__["currentDay"](), numTransactions) + '-02',
category: getStartingBalanceCat(incomeGroup.categories),
starting_balance_flag: true
}];
for (let i = 0; i < numTransactions; i++) {
let payee = incomePayee;
let amount = integer(4, 9) * 100 * 100;
transactions.push({
amount,
payee: payee.id,
account: account.id,
date: _shared_months__WEBPACK_IMPORTED_MODULE_0__["subMonths"](_shared_months__WEBPACK_IMPORTED_MODULE_0__["currentDay"](), i) + '-02',
category: category.id
});
}
await handlers['transactions-batch-update']({
added: transactions,
fastMode: true
});
}
async function createBudget(accounts, payees, groups) {
let primaryAccount = accounts.find(a => a.name = 'Bank of America');
let earliestDate = (await _server_db__WEBPACK_IMPORTED_MODULE_3__["first"](`SELECT * FROM v_transactions t LEFT JOIN accounts a ON t.account = a.id
WHERE a.offbudget = 0 AND t.is_child = 0 ORDER BY date ASC LIMIT 1`)).date;
let earliestPrimaryDate = (await _server_db__WEBPACK_IMPORTED_MODULE_3__["first"](`SELECT * FROM v_transactions t LEFT JOIN accounts a ON t.account = a.id
WHERE a.id = ? AND a.offbudget = 0 AND t.is_child = 0 ORDER BY date ASC LIMIT 1`, [primaryAccount.id])).date;
let start = _shared_months__WEBPACK_IMPORTED_MODULE_0__["monthFromDate"](_server_db__WEBPACK_IMPORTED_MODULE_3__["fromDateRepr"](earliestDate));
let end = _shared_months__WEBPACK_IMPORTED_MODULE_0__["currentMonth"]();
let months = _shared_months__WEBPACK_IMPORTED_MODULE_0__["rangeInclusive"](start, end);
function category(name) {
for (let group of groups) {
let cat = group.categories.find(c => c.name === name);
if (cat) {
return cat;
}
}
}
function setBudget(month, category, amount) {
return _server_budget_actions__WEBPACK_IMPORTED_MODULE_5__["setBudget"]({
month,
category: category.id,
amount
});
}
function setBudgetIfSpent(month, cat) {
let spent = _server_sheet__WEBPACK_IMPORTED_MODULE_1__["getCellValue"](_shared_months__WEBPACK_IMPORTED_MODULE_0__["sheetForMonth"](month), `sum-amount-${cat.id}`);
if (spent < 0) {
setBudget(month, cat, -spent);
}
}
await Object(_server_mutators__WEBPACK_IMPORTED_MODULE_8__["runMutator"])(() => Object(_server_sync__WEBPACK_IMPORTED_MODULE_7__["batchMessages"])(async () => {
for (let month of months) {
if (month >= _shared_months__WEBPACK_IMPORTED_MODULE_0__["monthFromDate"](_server_db__WEBPACK_IMPORTED_MODULE_3__["fromDateRepr"](earliestPrimaryDate))) {
setBudget(month, category('Food'), 40000);
setBudget(month, category('Restaurants'), 30000);
setBudget(month, category('Entertainment'), 10000);
setBudget(month, category('Clothing'), 3000);
setBudget(month, category('General'), 50000);
setBudget(month, category('Gift'), 7500);
setBudget(month, category('Medical'), 10000);
setBudget(month, category('Cell'), 7500);
setBudget(month, category('Internet'), 6000);
setBudget(month, category('Mortgage'), 120000);
setBudget(month, category('Water'), 9000);
setBudget(month, category('Power'), 10000);
} else {
setBudgetIfSpent(month, category('Food'));
setBudgetIfSpent(month, category('Restaurants'));
setBudgetIfSpent(month, category('Entertainment'));
setBudgetIfSpent(month, category('Clothing'));
setBudgetIfSpent(month, category('General'));
setBudgetIfSpent(month, category('Gift'));
setBudgetIfSpent(month, category('Medical'));
setBudgetIfSpent(month, category('Cell'));
setBudgetIfSpent(month, category('Internet'));
setBudgetIfSpent(month, category('Mortgage'));
setBudgetIfSpent(month, category('Water'));
setBudgetIfSpent(month, category('Power'));
}
}
}));
await _server_sheet__WEBPACK_IMPORTED_MODULE_1__["waitOnSpreadsheet"]();
await Object(_server_mutators__WEBPACK_IMPORTED_MODULE_8__["runMutator"])(() => Object(_server_sync__WEBPACK_IMPORTED_MODULE_7__["batchMessages"])(async () => {
let prevSaved = 0;
for (let month of months) {
if (month >= _shared_months__WEBPACK_IMPORTED_MODULE_0__["monthFromDate"](_server_db__WEBPACK_IMPORTED_MODULE_3__["fromDateRepr"](earliestPrimaryDate)) && month <= _shared_months__WEBPACK_IMPORTED_MODULE_0__["currentMonth"]()) {
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_0__["sheetForMonth"](month);
let toBudget = _server_sheet__WEBPACK_IMPORTED_MODULE_1__["getCellValue"](sheetName, 'to-budget');
let available = toBudget - prevSaved;
if (available - 403000 > 0) {
setBudget(month, category('Savings'), available - 403000);
_server_budget_actions__WEBPACK_IMPORTED_MODULE_5__["setBuffer"](month, 403000);
prevSaved += available - 403000;
} else if (available > 0) {
_server_budget_actions__WEBPACK_IMPORTED_MODULE_5__["setBuffer"](month, available);
}
}
}
}));
await _server_sheet__WEBPACK_IMPORTED_MODULE_1__["waitOnSpreadsheet"]();
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_0__["sheetForMonth"](_shared_months__WEBPACK_IMPORTED_MODULE_0__["currentMonth"]());
let toBudget = _server_sheet__WEBPACK_IMPORTED_MODULE_1__["getCellValue"](sheetName, 'to-budget');
if (toBudget < 0) {
await Object(_server_accounts_sync__WEBPACK_IMPORTED_MODULE_9__["addTransactions"])(primaryAccount.id, [{
amount: -toBudget,
category: category('Income').id,
date: _shared_months__WEBPACK_IMPORTED_MODULE_0__["currentMonth"]() + '-01'
}]);
} // let sheetName = monthUtils.sheetForMonth(monthUtils.currentMonth());
// let toBudget = sheet.getCellValue(sheetName, 'to-budget');
// setBudget(monthUtils.currentMonth(), category('Savings'), toBudget);
await _server_sheet__WEBPACK_IMPORTED_MODULE_1__["waitOnSpreadsheet"]();
}
async function createTestBudget(handlers) {
Object(_server_sync__WEBPACK_IMPORTED_MODULE_7__["setSyncingMode"])('import');
await _server_db__WEBPACK_IMPORTED_MODULE_3__["execQuery"]('PRAGMA journal_mode = OFF'); // Clear out the default categories. This is fine to do without
// going through the sync system because we are in import mode and
// these aren't tracked through messages anyway.
await _server_db__WEBPACK_IMPORTED_MODULE_3__["runQuery"]('DELETE FROM categories;');
await _server_db__WEBPACK_IMPORTED_MODULE_3__["runQuery"]('DELETE FROM category_groups');
let accounts = [{
name: 'Bank of America',
type: 'checking'
}, {
name: 'Ally Savings',
type: 'savings'
}, {
name: 'Capital One Checking',
type: 'checking'
}, {
name: 'HSBC',
type: 'checking'
}, {
name: 'Vanguard 401k',
type: 'investment',
offBudget: 1
}, {
name: 'Mortgage',
type: 'mortgage',
offBudget: 1
}, {
name: 'House Asset',
type: 'other',
offBudget: 1
}, {
name: 'Roth IRA',
type: 'investment',
offBudget: 1
}];
await Object(_server_mutators__WEBPACK_IMPORTED_MODULE_8__["runMutator"])(() => Object(_server_sync__WEBPACK_IMPORTED_MODULE_7__["batchMessages"])(async () => {
for (let account of accounts) {
account.id = await handlers['account-create'](account);
}
}));
let payees = [{
name: 'Starting Balance'
}, {
name: 'Kroger'
}, {
name: 'Publix'
}, {
name: 'Home Depot'
}, {
name: 'Movies'
}, {
name: 'Online store'
}, {
name: 'Deposit'
}, {
name: 'Dominion Power',
bill: true
}, {
name: 'Extra Watery',
bill: true
}, {
name: 'Housy House',
bill: true
}, {
name: 'Fast Internet',
bill: true
}, {
name: 'T-mobile',
bill: true
}];
await Object(_server_mutators__WEBPACK_IMPORTED_MODULE_8__["runMutator"])(() => Object(_server_sync__WEBPACK_IMPORTED_MODULE_7__["batchMessages"])(async () => {
for (let payee of payees) {
payee.id = await handlers['payee-create']({
name: payee.name
});
}
}));
let categoryGroups = [{
name: 'Usual Expenses',
categories: [{
name: 'Savings'
}, {
name: 'Medical'
}, {
name: 'Gift'
}, {
name: 'General'
}, {
name: 'Clothing'
}, {
name: 'Entertainment'
}, {
name: 'Restaurants'
}, {
name: 'Food'
}]
}, {
name: 'Bills',
categories: [{
name: 'Power'
}, {
name: 'Water'
}, {
name: 'Mortgage'
}, {
name: 'Internet'
}, {
name: 'Cell'
}]
}, {
name: 'Income',
is_income: true,
categories: [{
name: 'Income',
is_income: true
}, {
name: 'Misc',
is_income: true
}, {
name: 'Starting Balances',
is_income: true
}]
}];
await Object(_server_mutators__WEBPACK_IMPORTED_MODULE_8__["runMutator"])(async () => {
for (let group of categoryGroups) {
group.id = await handlers['category-group-create']({
name: group.name,
isIncome: group.is_income ? 1 : 0
});
for (let category of group.categories) {
category.id = await handlers['category-create'](_objectSpread(_objectSpread({}, category), {}, {
isIncome: category.is_income ? 1 : 0,
groupId: group.id
}));
}
}
});
let allGroups = (await Object(_server_mutators__WEBPACK_IMPORTED_MODULE_8__["runHandler"])(handlers['get-categories'])).grouped;
Object(_server_sync__WEBPACK_IMPORTED_MODULE_7__["setSyncingMode"])('import');
await Object(_server_mutators__WEBPACK_IMPORTED_MODULE_8__["runMutator"])(() => Object(_server_sync__WEBPACK_IMPORTED_MODULE_7__["batchMessages"])(async () => {
for (let account of accounts) {
switch (account.type) {
case 'checking':
if (account.name === 'Bank of America') {
await fillPrimaryChecking(handlers, account, payees, allGroups);
} else {
await fillChecking(handlers, account, payees, allGroups);
}
break;
case 'investment':
await fillInvestment(handlers, account, payees, allGroups);
break;
case 'savings':
await fillSavings(handlers, account, payees, allGroups);
break;
case 'mortgage':
await fillMortgage(handlers, account, payees, allGroups);
break;
case 'other':
if (account.name === 'House Asset') {
await fillOther(handlers, account, payees, allGroups);
} else {
await fillChecking(handlers, account, payees, allGroups);
}
break;
default:
}
}
}));
Object(_server_sync__WEBPACK_IMPORTED_MODULE_7__["setSyncingMode"])('import'); // This checks to see if the primary account is in the negative.
// This might happen depending on the transactions added, but we
// don't want to show that as it'd be weird. We modify the latest
// deposit transaction to force it to be positive
let primaryAccount = accounts.find(a => a.name = 'Bank of America');
let _await$aqlQuery = await Object(_server_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_6__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_10__["default"])('transactions').filter({
account: primaryAccount.id
}).calculate({
$sum: '$amount'
}).serialize()),
primaryBalance = _await$aqlQuery.data;
if (primaryBalance < 0) {
let _await$aqlQuery2 = await Object(_server_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_6__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_10__["default"])('transactions').filter({
account: primaryAccount.id,
amount: {
$gt: 0
}
}).limit(1).select(['id', 'amount']).serialize()),
results = _await$aqlQuery2.data;
let lastDeposit = results[0];
await Object(_server_mutators__WEBPACK_IMPORTED_MODULE_8__["runHandler"])(handlers['transaction-update'], _objectSpread(_objectSpread({}, lastDeposit), {}, {
amount: lastDeposit.amount + -primaryBalance + integer(10000, 20000)
}));
} // Bust the cache and reload the spreadsheet
Object(_server_sync__WEBPACK_IMPORTED_MODULE_7__["setSyncingMode"])('disabled');
await _server_prefs__WEBPACK_IMPORTED_MODULE_4__["savePrefs"]({
isCached: false
});
await _server_sheet__WEBPACK_IMPORTED_MODULE_1__["reloadSpreadsheet"](_server_db__WEBPACK_IMPORTED_MODULE_3__);
await _server_budget_base__WEBPACK_IMPORTED_MODULE_2__["createAllBudgets"]();
await _server_sheet__WEBPACK_IMPORTED_MODULE_1__["waitOnSpreadsheet"](); // Create a budget
await createBudget(accounts, payees, allGroups);
}
/***/ }),
/***/ "./packages/loot-core/src/platform/exceptions/index.electron.js":
/*!**********************************************************************!*\
!*** ./packages/loot-core/src/platform/exceptions/index.electron.js ***!
\**********************************************************************/
/*! exports provided: captureException, captureBreadcrumb */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "captureException", function() { return captureException; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "captureBreadcrumb", function() { return captureBreadcrumb; });
function captureException(exc) {
console.log('[Exception]', exc);
if (global.SentryClient) {
global.SentryClient.captureException(exc);
}
}
function captureBreadcrumb(breadcrumb) {
if (global.SentryClient) {
global.SentryClient.addBreadcrumb(breadcrumb);
}
}
/***/ }),
/***/ "./packages/loot-core/src/platform/server/asyncStorage/index.electron.js":
/*!*******************************************************************************!*\
!*** ./packages/loot-core/src/platform/server/asyncStorage/index.electron.js ***!
\*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const lootFs = __webpack_require__(/*! ../fs */ "./packages/loot-core/src/platform/server/fs/index.electron.js");
const fs = __webpack_require__(/*! fs */ "fs");
const _require = __webpack_require__(/*! path */ "path"),
join = _require.join;
let getStorePath = () => join(lootFs.getDataDir(), 'global-store.json');
let store;
let persisted = true;
function init({
persist = true
} = {}) {
if (persist) {
try {
store = JSON.parse(fs.readFileSync(getStorePath(), 'utf8'));
} catch (e) {
store = {};
}
} else {
store = {};
}
persisted = persist;
}
function _saveStore() {
if (persisted) {
return new Promise(function (resolve, reject) {
fs.writeFile(getStorePath(), JSON.stringify(store), 'utf8', function (err, _) {
return err ? reject(err) : resolve();
});
});
}
}
function getItem(key) {
return new Promise(function (resolve) {
return resolve(store[key]);
});
}
function setItem(key, value) {
store[key] = value;
return _saveStore();
}
function removeItem(key) {
delete store[key];
return _saveStore();
}
function multiGet(keys) {
return new Promise(function (resolve) {
return resolve(keys.map(function (key) {
return [key, store[key]];
}));
});
}
function multiSet(keyValues) {
keyValues.forEach(function ([key, value]) {
store[key] = value;
});
return _saveStore();
}
function multiRemove(keys) {
keys.forEach(function (key) {
delete store[key];
});
return _saveStore();
}
module.exports = {
init,
getItem,
setItem,
removeItem,
multiGet,
multiSet,
multiRemove
};
/***/ }),
/***/ "./packages/loot-core/src/platform/server/connection/index.api.js":
/*!************************************************************************!*\
!*** ./packages/loot-core/src/platform/server/connection/index.api.js ***!
\************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function init() {}
function send(type, args) {// Nothing
}
module.exports = {
init,
send
};
/***/ }),
/***/ "./packages/loot-core/src/platform/server/fetch/index.electron.js":
/*!************************************************************************!*\
!*** ./packages/loot-core/src/platform/server/fetch/index.electron.js ***!
\************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
let fs = __webpack_require__(/*! fs */ "fs");
let fetch = __webpack_require__(/*! node-fetch */ "node-fetch");
async function fetchBinary(url, filepath) {
const res = await fetch(url);
return new Promise((resolve, reject) => {
const fileStream = fs.createWriteStream(filepath);
res.body.pipe(fileStream);
res.body.on('error', err => {
reject(err);
});
fileStream.on('finish', function () {
resolve();
});
});
}
module.exports = {
fetch,
fetchBinary
};
/***/ }),
/***/ "./packages/loot-core/src/platform/server/fs/index.electron.js":
/*!*********************************************************************!*\
!*** ./packages/loot-core/src/platform/server/fs/index.electron.js ***!
\*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const fs = __webpack_require__(/*! fs */ "fs");
const path = __webpack_require__(/*! path */ "path");
let documentDir;
let rootPath = path.join(__dirname, '..', '..', '..', '..');
if (__filename.match('bundle')) {
// The file name is not our filename and indicates that we're in the
// bundled form. Because of this, the root path is different.
rootPath = path.join(__dirname, '..');
}
module.exports = {
init: () => {// Nothing to do
},
getDataDir: () => {
if (!process.env.ACTUAL_DATA_DIR) {
throw new Error('ACTUAL_DATA_DIR env variable is required');
}
return process.env.ACTUAL_DATA_DIR;
},
_setDocumentDir: dir => documentDir = dir,
getDocumentDir: () => {
if (!documentDir) {
throw new Error('Document directory is not set');
}
return documentDir;
},
getBudgetDir: id => {
if (!id) {
throw new Error('getDocumentDir: id is falsy: ' + id);
} // TODO: This should be better
//
// A cheesy safe guard. The id is generated from the budget name,
// so it provides an entry point for the user to accidentally (or
// intentionally) access other parts of the system. Always
// restrict it to only access files within the budget directory by
// never allowing slashes.
if (id.match(/[^A-Za-z0-9\-_]/)) {
throw new Error(`Invalid budget id "${id}". Check the id of your budget in the "Advanced" section of the settings page.`);
}
return path.join(module.exports.getDocumentDir(), id);
},
bundledDatabasePath: path.join(rootPath, 'default-db.sqlite'),
migrationsPath: path.join(rootPath, 'migrations'),
demoBudgetPath: path.join(rootPath, 'demo-budget'),
join: path.join,
basename: filepath => path.basename(filepath),
listDir: filepath => new Promise((resolve, reject) => {
fs.readdir(filepath, (err, files) => {
if (err) {
reject(err);
} else {
resolve(files);
}
});
}),
exists: filepath => new Promise(resolve => {
fs.access(filepath, fs.constants.F_OK, err => {
return resolve(!err);
});
}),
mkdir: filepath => new Promise((resolve, reject) => {
fs.mkdir(filepath, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
}),
size: filepath => new Promise((resolve, reject) => {
fs.stat(filepath, (err, stats) => {
if (err) {
reject(err);
} else {
resolve(stats.size);
}
});
}),
copyFile: (frompath, topath) => {
return new Promise((resolve, reject) => {
const readStream = fs.createReadStream(frompath);
const writeStream = fs.createWriteStream(topath);
readStream.on('error', reject);
writeStream.on('error', reject);
writeStream.on('open', () => readStream.pipe(writeStream));
writeStream.once('close', resolve);
});
},
readFile: (filepath, encoding = 'utf8') => {
if (encoding === 'binary') {
// `binary` is not actually a valid encoding, you pass `null` into node if
// you want a buffer
encoding = null;
}
return new Promise((resolve, reject) => {
fs.readFile(filepath, encoding, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
},
writeFile: (filepath, contents) => {
return new Promise(function (resolve, reject) {
fs.writeFile(filepath, contents, 'utf8', function (err, _) {
return err ? reject(err) : resolve();
});
});
},
removeFile: filepath => {
return new Promise(function (resolve, reject) {
fs.unlink(filepath, err => {
return err ? reject(err) : resolve();
});
});
},
removeDir: dirpath => {
return new Promise(function (resolve, reject) {
fs.rmdir(dirpath, err => {
return err ? reject(err) : resolve();
});
});
},
removeDirRecursively: async dirpath => {
const f = module.exports;
if (await f.exists(dirpath)) {
for (let file of await f.listDir(dirpath)) {
const fullpath = f.join(dirpath, file);
if (fs.statSync(fullpath).isDirectory()) {
await f.removeDirRecursively(fullpath);
} else {
await f.removeFile(fullpath);
}
}
await f.removeDir(dirpath);
}
},
getModifiedTime: filepath => {
return new Promise(function (resolve, reject) {
fs.stat(filepath, (err, stats) => {
if (err) {
reject(err);
} else {
resolve(new Date(stats.mtime));
}
});
});
}
};
/***/ }),
/***/ "./packages/loot-core/src/platform/server/log/index.api.js":
/*!*****************************************************************!*\
!*** ./packages/loot-core/src/platform/server/log/index.api.js ***!
\*****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
info: (...args) => {
console.log(...args);
},
warn: (...args) => {
console.warn(...args);
}
});
/***/ }),
/***/ "./packages/loot-core/src/platform/server/sqlite/index.electron.js":
/*!*************************************************************************!*\
!*** ./packages/loot-core/src/platform/server/sqlite/index.electron.js ***!
\*************************************************************************/
/*! exports provided: init, prepare, runQuery, execQuery, transaction, asyncTransaction, openDatabase, closeDatabase, exportDatabase */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "init", function() { return init; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prepare", function() { return prepare; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runQuery", function() { return runQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "execQuery", function() { return execQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transaction", function() { return transaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asyncTransaction", function() { return asyncTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "openDatabase", function() { return openDatabase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "closeDatabase", function() { return closeDatabase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exportDatabase", function() { return exportDatabase; });
const Database = __webpack_require__(/*! better-sqlite3 */ "better-sqlite3");
function verifyParamTypes(sql, arr) {
arr.forEach(val => {
if (typeof val !== 'string' && typeof val !== 'number' && val !== null) {
console.log(sql, arr);
throw new Error('Invalid field type ' + val + ' for sql ' + sql);
}
});
}
async function init() {}
function prepare(db, sql) {
return db.prepare(sql);
}
function runQuery(db, sql, params = [], fetchAll) {
if (params) {
verifyParamTypes(sql, params);
}
let stmt;
try {
stmt = typeof sql === 'string' ? db.prepare(sql) : sql;
} catch (e) {
console.log('error', sql);
throw e;
}
if (fetchAll) {
try {
let result = stmt.all(...params);
return result;
} catch (e) {
console.log('error', sql);
throw e;
}
} else {
try {
let info = stmt.run(...params);
return {
changes: info.changes,
insertId: info.lastInsertRowid
};
} catch (e) {
// console.log('error', sql);
throw e;
}
}
}
function execQuery(db, sql) {
db.exec(sql);
}
function transaction(db, fn) {
db.transaction(fn)();
} // **Important**: this is an unsafe function since sqlite executes
// executes statements sequentially. It would be easy for other code
// to run statements in between our transaction and get caught up in
// it. This is rarely used, and only needed for specific cases (like
// batch importing a bunch of data). Don't use this.
let transactionDepth = 0;
async function asyncTransaction(db, fn) {
// Support nested transactions by "coalescing" them into the parent
// one if one is already started
if (transactionDepth === 0) {
db.exec('BEGIN TRANSACTION');
}
transactionDepth++;
try {
await fn();
} finally {
transactionDepth--; // We always commit because rollback is more dangerous - any
// queries that ran *in-between* this async function would be
// lost. Right now we are only using transactions for speed
// purposes unfortunately
if (transactionDepth === 0) {
db.exec('COMMIT');
}
}
}
function openDatabase(pathOrBuffer) {
return new Database(pathOrBuffer);
}
function closeDatabase(db) {
return db.close();
}
function exportDatabase(db) {
return db.serialize();
}
/***/ }),
/***/ "./packages/loot-core/src/platform/uuid/index.electron.js":
/*!****************************************************************!*\
!*** ./packages/loot-core/src/platform/uuid/index.electron.js ***!
\****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
const uuid = __webpack_require__(/*! uuid */ "./node_modules/uuid/index.js");
module.exports = {
v4: function () {
return Promise.resolve(uuid.v4());
},
v4Sync: function () {
return uuid.v4();
}
};
/***/ }),
/***/ "./packages/loot-core/src/server/accounts/export-to-csv.js":
/*!*****************************************************************!*\
!*** ./packages/loot-core/src/server/accounts/export-to-csv.js ***!
\*****************************************************************/
/*! exports provided: exportToCSV, exportQueryToCSV */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exportToCSV", function() { return exportToCSV; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exportQueryToCSV", function() { return exportQueryToCSV; });
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs */ "fs");
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var csv_stringify_lib_sync__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! csv-stringify/lib/sync */ "./node_modules/csv-stringify/lib/sync.js");
/* harmony import */ var csv_stringify_lib_sync__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(csv_stringify_lib_sync__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _aql_schema_run_query__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../aql/schema/run-query */ "./packages/loot-core/src/server/aql/schema/run-query.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/util */ "./packages/loot-core/src/shared/util.js");
async function exportToCSV(transactions, accounts, categoryGroups, payees) {
const accountNamesById = accounts.reduce((reduced, {
id,
name
}) => {
reduced[id] = name;
return reduced;
}, {});
const categoryNamesById = categoryGroups.reduce((reduced, {
name,
categories: subCategories
}) => {
subCategories.forEach(subCategory => reduced[subCategory.id] = `${name}: ${subCategory.name}`);
return reduced;
}, {});
const payeeNamesById = payees.reduce((reduced, {
id,
name
}) => {
reduced[id] = name;
return reduced;
}, {});
const transactionsForExport = transactions.map(({
account,
date,
payee,
notes,
category,
amount
}) => ({
Account: accountNamesById[account],
Date: date,
Payee: payeeNamesById[payee],
Notes: notes,
Category: categoryNamesById[category],
Amount: amount == null ? 0 : Object(_shared_util__WEBPACK_IMPORTED_MODULE_3__["integerToAmount"])(amount)
}));
return csv_stringify_lib_sync__WEBPACK_IMPORTED_MODULE_1___default()(transactionsForExport, {
header: true
});
}
async function exportQueryToCSV(query) {
let _await$aqlQuery = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_2__["runQuery"])(query.select([{
Id: 'id'
}, {
Account: 'account.name'
}, {
Date: 'date'
}, {
Payee: 'payee.name'
}, {
ParentId: 'parent_id'
}, {
IsParent: 'is_parent'
}, {
Notes: 'notes'
}, {
Category: 'category.name'
}, {
Amount: 'amount'
}]).options({
splits: 'all'
})),
transactions = _await$aqlQuery.data;
let parentsPayees = new Map();
for (let trans of transactions) {
if (trans.IsParent) {
parentsPayees.set(trans.Id, trans.Payee);
}
} // filter out any parent transactions
let noParents = transactions.filter(t => !t.IsParent); // map final properties for export and grab the payee for splits from their parent transaction
let transactionsForExport = noParents.map(trans => {
return {
Account: trans.Account,
Date: trans.Date,
Payee: trans.ParentId ? parentsPayees.get(trans.ParentId) : trans.Payee,
Notes: trans.Notes,
Category: trans.Category,
Amount: trans.Amount == null ? 0 : Object(_shared_util__WEBPACK_IMPORTED_MODULE_3__["integerToAmount"])(trans.Amount)
};
});
return csv_stringify_lib_sync__WEBPACK_IMPORTED_MODULE_1___default()(transactionsForExport, {
header: true
});
}
/***/ }),
/***/ "./packages/loot-core/src/server/accounts/link.js":
/*!********************************************************!*\
!*** ./packages/loot-core/src/server/accounts/link.js ***!
\********************************************************/
/*! exports provided: handoffPublicToken, addAccounts */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "handoffPublicToken", function() { return handoffPublicToken; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addAccounts", function() { return addAccounts; });
/* harmony import */ var _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../platform/server/asyncStorage */ "./packages/loot-core/src/platform/server/asyncStorage/index.electron.js");
/* harmony import */ var _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../config */ "./packages/loot-core/src/server/config.js");
/* harmony import */ var _sync__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./sync */ "./packages/loot-core/src/server/accounts/sync.js");
/* harmony import */ var _shared_accounts__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../shared/accounts */ "./packages/loot-core/src/shared/accounts.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../shared/util */ "./packages/loot-core/src/shared/util.js");
/* harmony import */ var _post__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../post */ "./packages/loot-core/src/server/post.js");
/* harmony import */ var _mutators__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../mutators */ "./packages/loot-core/src/server/mutators.js");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
const uuid = __webpack_require__(/*! ../../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js");
async function handoffPublicToken(institution, publicToken) {
let _await$asyncStorage$m = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_0___default.a.multiGet(['user-id', 'user-key']),
_await$asyncStorage$m2 = _slicedToArray(_await$asyncStorage$m, 2),
_await$asyncStorage$m3 = _slicedToArray(_await$asyncStorage$m2[0], 2),
userId = _await$asyncStorage$m3[1],
_await$asyncStorage$m4 = _slicedToArray(_await$asyncStorage$m2[1], 2),
key = _await$asyncStorage$m4[1];
if (institution == null || !institution.institution_id || !institution.name) {
throw new Error('Invalid institution object');
}
let id = uuid.v4Sync(); // Make sure to generate an access token first before inserting it
// into our local database in case it fails
await Object(_post__WEBPACK_IMPORTED_MODULE_6__["post"])(Object(_config__WEBPACK_IMPORTED_MODULE_2__["getConfig"])().PLAID_SERVER + '/handoff_public_token', {
userId,
key,
item_id: id,
public_token: publicToken
});
await Object(_mutators__WEBPACK_IMPORTED_MODULE_7__["runMutator"])(() => _db__WEBPACK_IMPORTED_MODULE_1__["insertWithUUID"]('banks', {
id,
bank_id: institution.institution_id,
name: institution.name
}));
return id;
}
async function addAccounts(bankId, accountIds, offbudgetIds = []) {
let _await$asyncStorage$m5 = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_0___default.a.multiGet(['user-id', 'user-key']),
_await$asyncStorage$m6 = _slicedToArray(_await$asyncStorage$m5, 2),
_await$asyncStorage$m7 = _slicedToArray(_await$asyncStorage$m6[0], 2),
userId = _await$asyncStorage$m7[1],
_await$asyncStorage$m8 = _slicedToArray(_await$asyncStorage$m6[1], 2),
userKey = _await$asyncStorage$m8[1]; // Get all the available accounts
let accounts = await _sync__WEBPACK_IMPORTED_MODULE_3__["getAccounts"](userId, userKey, bankId); // Only add the selected accounts
accounts = accounts.filter(acct => accountIds.includes(acct.account_id));
return Promise.all(accounts.map(async acct => {
let id = await Object(_mutators__WEBPACK_IMPORTED_MODULE_7__["runMutator"])(async () => {
let id = await _db__WEBPACK_IMPORTED_MODULE_1__["insertAccount"]({
account_id: acct.account_id,
name: acct.name,
official_name: acct.official_name,
type: Object(_shared_accounts__WEBPACK_IMPORTED_MODULE_4__["fromPlaidAccountType"])(acct.type),
balance_current: Object(_shared_util__WEBPACK_IMPORTED_MODULE_5__["amountToInteger"])(acct.balances.current),
mask: acct.mask,
bank: bankId,
offbudget: offbudgetIds.includes(acct.account_id) ? 1 : 0
}); // Create a transfer payee
await _db__WEBPACK_IMPORTED_MODULE_1__["insertPayee"]({
name: '',
transfer_acct: id
});
return id;
}); // Do an initial sync
await _sync__WEBPACK_IMPORTED_MODULE_3__["syncAccount"](userId, userKey, id, acct.account_id, bankId);
return id;
}));
}
/***/ }),
/***/ "./packages/loot-core/src/server/accounts/parse-file.js":
/*!**************************************************************!*\
!*** ./packages/loot-core/src/server/accounts/parse-file.js ***!
\**************************************************************/
/*! exports provided: parseFile */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseFile", function() { return parseFile; });
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../platform/server/fs */ "./packages/loot-core/src/platform/server/fs/index.electron.js");
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _qif2json__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./qif2json */ "./packages/loot-core/src/server/accounts/qif2json.js");
/* harmony import */ var csv_parse_lib_sync__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! csv-parse/lib/sync */ "./node_modules/csv-parse/lib/sync.js");
/* harmony import */ var csv_parse_lib_sync__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(csv_parse_lib_sync__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../shared/util */ "./packages/loot-core/src/shared/util.js");
function parseFile(filepath, options) {
let errors = [];
let m = filepath.match(/\.[^.]*$/);
if (m) {
let ext = m[0];
switch (ext.toLowerCase()) {
case '.qif':
return parseQIF(filepath);
case '.csv':
return parseCSV(filepath, options);
case '.ofx':
case '.qfx':
return parseOFX(filepath);
default:
}
}
errors.push({
message: 'Invalid file type',
internal: ''
});
return {
errors
};
}
async function parseCSV(filepath, options = {}) {
let errors = [];
let contents = await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.readFile(filepath);
let data;
try {
data = csv_parse_lib_sync__WEBPACK_IMPORTED_MODULE_2___default()(contents, {
columns: true,
bom: true,
delimiter: options.delimiter || ',',
quote: '"',
trim: true,
relax_column_count: true
});
} catch (err) {
errors.push({
message: 'Failed parsing: ' + err.message,
internal: err.message
});
return {
errors,
transactions: []
};
}
return {
errors,
transactions: data
};
}
async function parseQIF(filepath) {
let errors = [];
let contents = await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.readFile(filepath);
let data;
try {
data = Object(_qif2json__WEBPACK_IMPORTED_MODULE_1__["default"])(contents);
} catch (err) {
errors.push({
message: "Failed parsing: doesn't look like a valid QIF file.",
internal: err.stack
});
return {
errors,
transactions: []
};
}
return {
errors,
transactions: data.transactions.map(trans => ({
amount: trans.amount != null ? Object(_shared_util__WEBPACK_IMPORTED_MODULE_4__["looselyParseAmount"])(trans.amount) : null,
date: trans.date,
payee_name: trans.payee,
imported_payee: trans.payee,
notes: trans.memo || null
}))
};
}
async function parseOFX(filepath) {
let _await$import = await Promise.resolve(/*! import() */).then(__webpack_require__.t.bind(null, /*! node-libofx */ "node-libofx", 7)),
getOFXTransactions = _await$import.getOFXTransactions,
initModule = _await$import.initModule;
await initModule();
let errors = [];
let contents = await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.readFile(filepath);
let data;
try {
data = getOFXTransactions(contents);
} catch (err) {
errors.push({
message: 'Failed importing file',
internal: err.stack
});
return {
errors
};
}
return {
errors,
transactions: data.map(trans => ({
amount: trans.amount,
imported_id: trans.fi_id,
date: trans.date ? Object(_shared_months__WEBPACK_IMPORTED_MODULE_3__["dayFromDate"])(trans.date * 1000) : null,
payee_name: trans.name,
imported_payee: trans.name,
notes: trans.memo || null
}))
};
}
/***/ }),
/***/ "./packages/loot-core/src/server/accounts/payees.js":
/*!**********************************************************!*\
!*** ./packages/loot-core/src/server/accounts/payees.js ***!
\**********************************************************/
/*! exports provided: createPayee, getStartingBalancePayee */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createPayee", function() { return createPayee; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStartingBalancePayee", function() { return getStartingBalancePayee; });
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
async function createPayee(description) {
// Check to make sure no payee already exists with exactly the same
// name
let row = await _db__WEBPACK_IMPORTED_MODULE_0__["first"](`SELECT id FROM payees WHERE LOWER(name) = ? AND tombstone = 0`, [description.toLowerCase()]);
if (row) {
return row.id;
} else {
return _db__WEBPACK_IMPORTED_MODULE_0__["insertPayee"]({
name: description
});
}
}
async function getStartingBalancePayee() {
let category = await _db__WEBPACK_IMPORTED_MODULE_0__["first"](`
SELECT * FROM categories
WHERE is_income = 1 AND
LOWER(name) = 'starting balances' AND
tombstone = 0
`);
if (category === null) {
category = await _db__WEBPACK_IMPORTED_MODULE_0__["first"]('SELECT * FROM categories WHERE is_income = 1 AND tombstone = 0');
}
let id = await createPayee('Starting Balance');
return {
id,
category: category ? category.id : null
};
}
/***/ }),
/***/ "./packages/loot-core/src/server/accounts/qif2json.js":
/*!************************************************************!*\
!*** ./packages/loot-core/src/server/accounts/qif2json.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return parse; });
function parse(qif, options) {
var lines = qif.split('\n'),
line = lines.shift(),
type = /!Type:([^$]*)$/.exec(line.trim()),
data = {},
transactions = data.transactions = [],
transaction = {};
options = options || {};
if (!type || !type.length) {
throw new Error('File does not appear to be a valid qif file: ' + line);
}
data.type = type[1];
var division = {};
while (line = lines.shift()) {
line = line.trim();
if (line === '^') {
transactions.push(transaction);
transaction = {};
continue;
}
switch (line[0]) {
case 'D':
transaction.date = line.substring(1);
break;
case 'T':
transaction.amount = line.substring(1);
break;
case 'N':
transaction.number = line.substring(1);
break;
case 'M':
transaction.memo = line.substring(1);
break;
case 'A':
transaction.address = (transaction.address || []).concat(line.substring(1));
break;
case 'P':
transaction.payee = line.substring(1).replace(/&amp;/g, '&');
break;
case 'L':
var lArray = line.substring(1).split(':');
transaction.category = lArray[0];
if (lArray[1] !== undefined) {
transaction.subcategory = lArray[1];
}
break;
case 'C':
transaction.clearedStatus = line.substring(1);
break;
case 'S':
var sArray = line.substring(1).split(':');
division.category = sArray[0];
if (sArray[1] !== undefined) {
division.subcategory = sArray[1];
}
break;
case 'E':
division.description = line.substring(1);
break;
case '$':
division.amount = parseFloat(line.substring(1));
if (!(transaction.division instanceof Array)) {
transaction.division = [];
}
transaction.division.push(division);
division = {};
break;
default:
throw new Error('Unknown Detail Code: ' + line[0]);
}
}
if (Object.keys(transaction).length) {
transactions.push(transaction);
}
data.dateFormat = options.dateFormat;
return data;
}
/***/ }),
/***/ "./packages/loot-core/src/server/accounts/rules.js":
/*!*********************************************************!*\
!*** ./packages/loot-core/src/server/accounts/rules.js ***!
\*********************************************************/
/*! exports provided: parseRecurDate, parseDateString, parseBetweenAmount, Condition, Action, Rule, RuleIndexer, rankRules, migrateIds, iterateIds */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseRecurDate", function() { return parseRecurDate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseDateString", function() { return parseDateString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseBetweenAmount", function() { return parseBetweenAmount; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Condition", function() { return Condition; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return Action; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Rule", function() { return Rule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RuleIndexer", function() { return RuleIndexer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rankRules", function() { return rankRules; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "migrateIds", function() { return migrateIds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iterateIds", function() { return iterateIds; });
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors */ "./packages/loot-core/src/server/errors.js");
/* harmony import */ var date_fns__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! date-fns */ "./node_modules/date-fns/esm/index.js");
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/util */ "./packages/loot-core/src/shared/util.js");
/* harmony import */ var _shared_rules__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../shared/rules */ "./packages/loot-core/src/shared/rules.js");
/* harmony import */ var _shared_schedules__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../shared/schedules */ "./packages/loot-core/src/shared/schedules.js");
/* harmony import */ var _util_rschedule__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/rschedule */ "./packages/loot-core/src/server/util/rschedule.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function safeNumber(n) {
return isNaN(n) ? null : n;
}
function safeParseInt(n) {
return safeNumber(parseInt(n));
}
function assert(test, type, msg) {
if (!test) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__["RuleError"](type, msg);
}
}
function parseRecurDate(desc) {
try {
let rules = Object(_shared_schedules__WEBPACK_IMPORTED_MODULE_5__["recurConfigToRSchedule"])(desc);
return {
type: 'recur',
schedule: new _util_rschedule__WEBPACK_IMPORTED_MODULE_6__["Schedule"]({
rrules: rules
})
};
} catch (e) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__["RuleError"]('parse-recur-date', e.message);
}
}
function parseDateString(str) {
if (typeof str !== 'string') {
return null;
} else if (str.length === 10) {
// YYYY-MM-DD
if (!date_fns__WEBPACK_IMPORTED_MODULE_1__["isValid"](date_fns__WEBPACK_IMPORTED_MODULE_1__["parseISO"](str))) {
return null;
}
return {
type: 'date',
date: str
};
} else if (str.length === 7) {
// YYYY-MM
if (!date_fns__WEBPACK_IMPORTED_MODULE_1__["isValid"](date_fns__WEBPACK_IMPORTED_MODULE_1__["parseISO"](str + '-01'))) {
return null;
}
return {
type: 'month',
date: str
};
} else if (str.length === 4) {
// YYYY
if (!date_fns__WEBPACK_IMPORTED_MODULE_1__["isValid"](date_fns__WEBPACK_IMPORTED_MODULE_1__["parseISO"](str + '-01-01'))) {
return null;
}
return {
type: 'year',
date: str
};
}
return null;
}
function parseBetweenAmount(between) {
let num1 = between.num1,
num2 = between.num2;
if (typeof num1 !== 'number' || typeof num2 !== 'number') {
return null;
}
return {
type: 'between',
num1,
num2
};
}
let CONDITION_TYPES = {
date: {
ops: ['is', 'isapprox', 'gt', 'gte', 'lt', 'lte'],
nullable: false,
parse(op, value, fieldName) {
let parsed = typeof value === 'string' ? parseDateString(value) : value.frequency != null ? parseRecurDate(value) : null;
assert(parsed, 'date-format', `Invalid date format (field: ${fieldName})`); // Approximate only works with exact & recurring dates
if (op === 'isapprox') {
assert(parsed.type === 'date' || parsed.type === 'recur', 'date-format', `Invalid date value for "isapprox" (field: ${fieldName})`);
} // These only work with exact dates
else if (op === 'gt' || op === 'gte' || op === 'lt' || op === 'lte') {
assert(parsed.type === 'date', 'date-format', `Invalid date value for "${op}" (field: ${fieldName})`);
}
return parsed;
}
},
id: {
ops: ['is', 'contains', 'oneOf'],
nullable: true,
parse(op, value, fieldName) {
if (op === 'oneOf') {
assert(Array.isArray(value), 'no-empty-array', `oneOf must have an array value (field: ${fieldName})`);
return value;
}
return value;
}
},
string: {
ops: ['is', 'contains', 'oneOf'],
nullable: false,
parse(op, value, fieldName) {
if (op === 'oneOf') {
assert(Array.isArray(value), 'no-empty-array', `oneOf must have an array value (field: ${fieldName}): ${JSON.stringify(value)}`);
return value.filter(Boolean).map(val => val.toLowerCase());
}
if (op === 'contains') {
assert(typeof value === 'string' && value.length > 0, 'no-empty-string', `contains must have non-empty string (field: ${fieldName})`);
}
return value.toLowerCase();
}
},
number: {
ops: ['is', 'isapprox', 'isbetween', 'gt', 'gte', 'lt', 'lte'],
nullable: false,
parse(op, value, fieldName) {
let parsed = typeof value === 'number' ? {
type: 'literal',
value
} : parseBetweenAmount(value);
assert(parsed != null, 'not-number', `Value must be a number or between amount: ${JSON.stringify(value)} (field: ${fieldName})`);
if (op === 'isbetween') {
assert(parsed.type === 'between', 'number-format', `Invalid between value for "${op}" (field: ${fieldName})`);
} else {
assert(parsed.type === 'literal', 'number-format', `Invalid number value for "${op}" (field: ${fieldName})`);
}
return parsed;
}
},
boolean: {
ops: ['is'],
nullable: false,
parse(op, value, fieldName) {
assert(typeof value === 'boolean', 'not-boolean', `Value must be a boolean: ${value} (field: ${fieldName})`);
return value;
}
}
};
class Condition {
constructor(op, field, value, options, fieldTypes) {
let typeName = fieldTypes.get(field);
assert(typeName, 'internal', 'Invalid condition field: ' + field);
let type = CONDITION_TYPES[typeName]; // It's important to validate rules because a faulty rule might mess
// up the user's transaction (and be very confusing)
assert(type, 'internal', `Invalid condition type: ${typeName} (field: ${field})`);
assert(type.ops.includes(op), 'internal', `Invalid condition operator: ${op} (type: ${typeName}, field: ${field})`);
if (type.nullable !== true) {
assert(value != null, 'no-null', `Field cannot be empty: ${field}`);
} // For strings, an empty string is equal to null
if (typeName === 'string' && type.nullable !== true) {
assert(value !== '', 'no-null', `Field cannot be empty: ${field}`);
}
this.rawValue = value;
this.unparsedValue = value;
this.op = op;
this.field = field;
this.value = type.parse ? type.parse(op, value, field) : value;
this.options = options;
this.type = typeName;
}
eval(object) {
let fieldValue = object[this.field];
if (fieldValue === undefined) {
return false;
}
if (typeof fieldValue === 'string') {
fieldValue = fieldValue.toLowerCase();
}
let type = this.type;
if (type === 'number' && this.options) {
if (this.options.outflow) {
if (fieldValue > 0) {
return false;
}
fieldValue = -fieldValue;
} else if (this.options.inflow) {
if (fieldValue < 0) {
return false;
}
}
}
let extractValue = v => type === 'number' ? v.value : v;
switch (this.op) {
case 'isapprox':
case 'is':
if (type === 'date') {
if (fieldValue == null) {
return false;
}
if (this.value.type === 'recur') {
let schedule = this.value.schedule;
if (this.op === 'isapprox') {
let fieldDate = Object(_shared_months__WEBPACK_IMPORTED_MODULE_2__["parseDate"])(fieldValue);
return schedule.occursBetween(date_fns__WEBPACK_IMPORTED_MODULE_1__["subDays"](fieldDate, 2), date_fns__WEBPACK_IMPORTED_MODULE_1__["addDays"](fieldDate, 2));
} else {
return schedule.occursOn({
date: Object(_shared_months__WEBPACK_IMPORTED_MODULE_2__["parseDate"])(fieldValue)
});
}
} else {
let date = this.value.date;
if (this.op === 'isapprox') {
let fullDate = Object(_shared_months__WEBPACK_IMPORTED_MODULE_2__["parseDate"])(date);
let high = Object(_shared_months__WEBPACK_IMPORTED_MODULE_2__["addDays"])(fullDate, 2);
let low = Object(_shared_months__WEBPACK_IMPORTED_MODULE_2__["subDays"])(fullDate, 2);
return fieldValue >= low && fieldValue <= high;
} else {
switch (this.value.type) {
case 'date':
return fieldValue === date;
case 'month':
return Object(_shared_months__WEBPACK_IMPORTED_MODULE_2__["monthFromDate"])(fieldValue) === date;
case 'year':
return Object(_shared_months__WEBPACK_IMPORTED_MODULE_2__["yearFromDate"])(fieldValue) === date;
default:
}
}
}
} else if (type === 'number') {
let number = this.value.value;
if (this.op === 'isapprox') {
let threshold = Object(_shared_rules__WEBPACK_IMPORTED_MODULE_4__["getApproxNumberThreshold"])(number);
return fieldValue >= number - threshold && fieldValue <= number + threshold;
}
return fieldValue === number;
}
return fieldValue === this.value;
case 'isbetween':
{
// The parsing logic already checks that the value is of the
// right type (only numbers with high and low)
let _sortNumbers = Object(_shared_rules__WEBPACK_IMPORTED_MODULE_4__["sortNumbers"])(this.value.num1, this.value.num2),
_sortNumbers2 = _slicedToArray(_sortNumbers, 2),
low = _sortNumbers2[0],
high = _sortNumbers2[1];
return fieldValue >= low && fieldValue <= high;
}
case 'contains':
if (fieldValue === null) {
return false;
}
return fieldValue.indexOf(this.value) !== -1;
case 'oneOf':
if (fieldValue === null) {
return false;
}
return this.value.indexOf(fieldValue) !== -1;
case 'gt':
if (fieldValue === null) {
return false;
} else if (type === 'date') {
return Object(_shared_months__WEBPACK_IMPORTED_MODULE_2__["isAfter"])(fieldValue, this.value.date);
}
return fieldValue > extractValue(this.value);
case 'gte':
if (fieldValue === null) {
return false;
} else if (type === 'date') {
return fieldValue === this.value.date || Object(_shared_months__WEBPACK_IMPORTED_MODULE_2__["isAfter"])(fieldValue, this.value.date);
}
return fieldValue >= extractValue(this.value);
case 'lt':
if (fieldValue === null) {
return false;
} else if (type === 'date') {
return Object(_shared_months__WEBPACK_IMPORTED_MODULE_2__["isBefore"])(fieldValue, this.value.date);
}
return fieldValue < extractValue(this.value);
case 'lte':
if (fieldValue === null) {
return false;
} else if (type === 'date') {
return fieldValue === this.value.date || Object(_shared_months__WEBPACK_IMPORTED_MODULE_2__["isBefore"])(fieldValue, this.value.date);
}
return fieldValue <= extractValue(this.value);
default:
}
return false;
}
getValue() {
return this.value;
}
serialize() {
return _objectSpread({
op: this.op,
field: this.field,
value: this.unparsedValue,
type: this.type
}, this.options ? {
options: this.options
} : null);
}
}
let ACTION_OPS = ['set', 'link-schedule'];
class Action {
constructor(op, field, value, options, fieldTypes) {
assert(ACTION_OPS.includes(op), 'internal', `Invalid action operation: ${op}`);
if (op === 'set') {
let typeName = fieldTypes.get(field);
assert(typeName, 'internal', `Invalid field for action: ${field}`);
this.field = field;
this.type = typeName;
} else if (op === 'link-schedule') {
this.field = null;
this.type = 'id';
}
this.op = op;
this.rawValue = value;
this.value = value;
this.options = options;
}
exec(object) {
switch (this.op) {
case 'set':
object[this.field] = this.value;
break;
case 'link-schedule':
object.schedule = this.value;
break;
default:
}
}
serialize() {
return _objectSpread({
op: this.op,
field: this.field,
value: this.value,
type: this.type
}, this.options ? {
options: this.options
} : null);
}
}
class Rule {
constructor({
id,
stage,
conditions,
actions,
fieldTypes
}) {
this.id = id;
this.stage = stage;
this.conditions = conditions.map(c => new Condition(c.op, c.field, c.value, c.options, fieldTypes));
this.actions = actions.map(a => new Action(a.op, a.field, a.value, a.options, fieldTypes));
}
evalConditions(object) {
if (this.conditions.length === 0) {
return false;
}
return this.conditions.every(condition => {
return condition.eval(object);
});
}
execActions(object) {
let changes = {};
this.actions.forEach(action => action.exec(changes));
return changes;
}
exec(object) {
if (this.evalConditions(object)) {
return this.execActions(object);
}
return null;
} // Apply is similar to exec but applies the changes for you
apply(object) {
let changes = this.exec(object);
return Object.assign({}, object, changes);
}
getId() {
return this.id;
}
serialize() {
return {
id: this.id,
stage: this.stage,
conditions: this.conditions.map(c => c.serialize()),
actions: this.actions.map(a => a.serialize())
};
}
}
class RuleIndexer {
constructor({
field,
method
}) {
this.field = field;
this.method = method;
this.rules = new Map();
}
getIndex(key) {
if (!this.rules.has(key)) {
this.rules.set(key, new Set());
}
return this.rules.get(key);
}
getIndexForValue(value) {
return this.getIndex(this.getKey(value) || '*');
}
getKey(value) {
if (typeof value === 'string' && value !== '') {
if (this.method === 'firstchar') {
return value[0].toLowerCase();
}
return value.toLowerCase();
}
return null;
}
getIndexes(rule) {
let cond = rule.conditions.find(cond => cond.field === this.field);
let indexes = [];
if (cond && (cond.op === 'oneOf' || cond.op === 'is')) {
if (cond.op === 'oneOf') {
cond.value.forEach(val => indexes.push(this.getIndexForValue(val)));
} else {
indexes.push(this.getIndexForValue(cond.value));
}
} else {
indexes.push(this.getIndex('*'));
}
return indexes;
}
index(rule) {
let indexes = this.getIndexes(rule);
indexes.forEach(index => {
index.add(rule);
});
}
remove(rule) {
let indexes = this.getIndexes(rule);
indexes.forEach(index => {
index.delete(rule);
});
}
getApplicableRules(object) {
let indexedRules;
if (this.field in object) {
let key = this.getKey(object[this.field]);
if (key) {
indexedRules = this.rules.get(key);
}
}
return Object(_shared_util__WEBPACK_IMPORTED_MODULE_3__["fastSetMerge"])(indexedRules || new Set(), this.rules.get('*') || new Set());
}
}
const OP_SCORES = {
is: 10,
oneOf: 9,
isapprox: 5,
isbetween: 5,
gt: 1,
gte: 1,
lt: 1,
lte: 1,
contains: 0
};
function computeScore(rule) {
let initialScore = rule.conditions.reduce((score, condition) => {
if (OP_SCORES[condition.op] == null) {
console.log(`Found invalid operation while ranking: ${condition.op}`);
return 0;
}
return score + OP_SCORES[condition.op];
}, 0);
if (rule.conditions.every(cond => cond.op === 'is' || cond.op === 'isapprox' || cond.op === 'oneOf')) {
return initialScore * 2;
}
return initialScore;
}
function _rankRules(rules) {
let scores = new Map();
rules.forEach(rule => {
scores.set(rule, computeScore(rule));
}); // No matter the order of rules, this must always return exactly the same
// order. That's why rules have ids: if two rules have the same score, it
// sorts by id
return [...rules].sort((r1, r2) => {
let score1 = scores.get(r1);
let score2 = scores.get(r2);
if (score1 < score2) {
return -1;
} else if (score1 > score2) {
return 1;
} else {
let id1 = r1.getId();
let id2 = r2.getId();
return id1 < id2 ? -1 : id1 > id2 ? 1 : 0;
}
});
}
function rankRules(rules) {
let pre = [];
let normal = [];
let post = [];
for (let rule of rules) {
switch (rule.stage) {
case 'pre':
pre.push(rule);
break;
case 'post':
post.push(rule);
break;
default:
normal.push(rule);
}
}
pre = _rankRules(pre);
normal = _rankRules(normal);
post = _rankRules(post);
return pre.concat(normal).concat(post);
}
function migrateIds(rule, mappings) {
// Go through the in-memory rules and patch up ids that have been
// "migrated" to other ids. This is a little tricky, but a lot
// easier than trying to keep an up-to-date mapping in the db. This
// is necessary because ids can be transparently mapped as items are
// merged/deleted in the system.
//
// It's very important here that we look at `rawValue` specifically,
// and only apply the patches to the other `value` fields. We always
// need to keep the original id around because undo can walk
// backwards, and we need to be able to consistently apply a
// "projection" of these mapped values. For example: if we have ids
// [1, 2] and applying mappings transforms it to [2, 2], if `1` gets
// mapped to something else there's no way to no to map *only* the
// first id back to make [1, 2]. Keeping the original value around
// solves this.
for (let ci = 0; ci < rule.conditions.length; ci++) {
let cond = rule.conditions[ci];
if (cond.type === 'id') {
switch (cond.op) {
case 'is':
cond.value = mappings.get(cond.rawValue) || cond.rawValue;
cond.unparsedValue = cond.value;
break;
case 'oneOf':
cond.value = cond.rawValue.map(v => mappings.get(v) || v);
cond.unparsedValue = [...cond.value];
break;
default:
}
}
}
for (let ai = 0; ai < rule.actions.length; ai++) {
let action = rule.actions[ai];
if (action.type === 'id') {
if (action.op === 'set') {
action.value = mappings.get(action.rawValue) || action.rawValue;
}
}
}
} // This finds all the rules that reference the `id`
function iterateIds(rules, fieldName, func) {
let counts = {};
let i;
ruleiter: for (i = 0; i < rules.length; i++) {
let rule = rules[i];
for (let ci = 0; ci < rule.conditions.length; ci++) {
let cond = rule.conditions[ci];
if (cond.type === 'id' && cond.field === fieldName) {
switch (cond.op) {
case 'is':
if (func(rule, cond.value)) {
continue ruleiter;
}
break;
case 'oneOf':
for (let vi = 0; vi < cond.value.length; vi++) {
if (func(rule, cond.value[vi])) {
continue ruleiter;
}
}
break;
default:
}
}
}
for (let ai = 0; ai < rule.actions.length; ai++) {
let action = rule.actions[ai];
if (action.type === 'id' && action.field === fieldName) {
// Currently `set` is the only op, but if we add more this
// will need to be extended
if (action.op === 'set') {
if (func(rule, action.value)) {
break;
}
}
}
}
}
}
/***/ }),
/***/ "./packages/loot-core/src/server/accounts/sync.js":
/*!********************************************************!*\
!*** ./packages/loot-core/src/server/accounts/sync.js ***!
\********************************************************/
/*! exports provided: getAccounts, fromPlaid, reconcileTransactions, addTransactions, syncAccount */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAccounts", function() { return getAccounts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromPlaid", function() { return fromPlaid; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reconcileTransactions", function() { return reconcileTransactions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addTransactions", function() { return addTransactions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "syncAccount", function() { return syncAccount; });
/* harmony import */ var _title__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./title */ "./packages/loot-core/src/server/accounts/title/index.js");
/* harmony import */ var _title__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_title__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../shared/util */ "./packages/loot-core/src/shared/util.js");
/* harmony import */ var _shared_transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/transactions */ "./packages/loot-core/src/shared/transactions.js");
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _api_models__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../api-models */ "./packages/loot-core/src/server/api-models.js");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../config */ "./packages/loot-core/src/server/config.js");
/* harmony import */ var _sync__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../sync */ "./packages/loot-core/src/server/sync/index.js");
/* harmony import */ var _mutators__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../mutators */ "./packages/loot-core/src/server/mutators.js");
/* harmony import */ var _payees__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./payees */ "./packages/loot-core/src/server/accounts/payees.js");
/* harmony import */ var _transfer__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./transfer */ "./packages/loot-core/src/server/accounts/transfer.js");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../errors */ "./packages/loot-core/src/server/errors.js");
/* harmony import */ var _transaction_rules__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./transaction-rules */ "./packages/loot-core/src/server/accounts/transaction-rules.js");
/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./transactions */ "./packages/loot-core/src/server/accounts/transactions.js");
const _excluded = ["subtransactions"],
_excluded2 = ["payee_name", "subtransactions"];
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
const dateFns = __webpack_require__(/*! date-fns */ "./node_modules/date-fns/esm/index.js");
const _require = __webpack_require__(/*! ../post */ "./packages/loot-core/src/server/post.js"),
post = _require.post;
const levenshtein = __webpack_require__(/*! damerau-levenshtein */ "./node_modules/damerau-levenshtein/index.js");
const uuid = __webpack_require__(/*! ../../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js"); // Plaid article about API options:
// https://support.plaid.com/customer/en/portal/articles/2612155-transactions-returned-per-request
function BankSyncError(type, code) {
return {
type: 'BankSyncError',
category: type,
code
};
}
function makeSplitTransaction(trans, subtransactions) {
// We need to calculate the final state of split transactions
let _recalculateSplit = Object(_shared_transactions__WEBPACK_IMPORTED_MODULE_3__["recalculateSplit"])(_objectSpread(_objectSpread({}, trans), {}, {
is_parent: true,
subtransactions: subtransactions.map((transaction, idx) => Object(_shared_transactions__WEBPACK_IMPORTED_MODULE_3__["makeChild"])(trans, _objectSpread(_objectSpread({}, transaction), {}, {
sort_order: 0 - idx
})))
})),
sub = _recalculateSplit.subtransactions,
parent = _objectWithoutProperties(_recalculateSplit, _excluded);
return [parent, ...sub];
}
function getAccountBalance(account) {
// Debt account types need their balance reversed
switch (account.type) {
case 'credit':
case 'loan':
return -account.balances.current;
default:
return account.balances.current;
}
}
async function updateAccountBalance(id, balance) {
await _db__WEBPACK_IMPORTED_MODULE_1__["runQuery"]('UPDATE accounts SET balance_current = ? WHERE id = ?', [Object(_shared_util__WEBPACK_IMPORTED_MODULE_2__["amountToInteger"])(balance), id]);
}
async function getAccounts(userId, userKey, id) {
let res = await post(Object(_config__WEBPACK_IMPORTED_MODULE_6__["getConfig"])().PLAID_SERVER + '/accounts', {
userId,
key: userKey,
item_id: id
});
let accounts = res.accounts;
accounts.forEach(acct => {
acct.balances.current = getAccountBalance(acct);
});
return accounts;
}
function fromPlaid(trans) {
return {
imported_id: trans.transaction_id,
payee_name: trans.name,
imported_payee: trans.name,
amount: -Object(_shared_util__WEBPACK_IMPORTED_MODULE_2__["amountToInteger"])(trans.amount),
date: trans.date
};
}
async function downloadTransactions(userId, userKey, acctId, bankId, since, count) {
let allTransactions = [];
let accountBalance = null;
let pageSize = 100;
let offset = 0;
let numDownloaded = 0;
while (1) {
const endDate = _shared_months__WEBPACK_IMPORTED_MODULE_4__["currentDay"]();
const res = await post(Object(_config__WEBPACK_IMPORTED_MODULE_6__["getConfig"])().PLAID_SERVER + '/transactions', {
userId: userId,
key: userKey,
item_id: '' + bankId,
account_id: acctId,
start_date: since,
end_date: endDate,
count: pageSize,
offset
});
if (res.error_code) {
throw BankSyncError(res.error_type, res.error_code);
}
if (res.transactions.length === 0) {
break;
}
numDownloaded += res.transactions.length; // Remove pending transactions for now - we will handle them in
// the future.
allTransactions = allTransactions.concat(res.transactions.filter(t => !t.pending));
accountBalance = getAccountBalance(res.accounts[0]);
if (numDownloaded === res.total_transactions || count != null && allTransactions.length >= count) {
break;
}
offset += pageSize;
}
allTransactions = count != null ? allTransactions.slice(0, count) : allTransactions;
return {
transactions: allTransactions.map(fromPlaid),
accountBalance
};
}
async function resolvePayee(trans, payeeName, payeesToCreate) {
if (trans.payee == null && payeeName) {
// First check our registry of new payees (to avoid a db access)
// then check the db for existing payees
let payee = payeesToCreate.get(payeeName.toLowerCase());
payee = payee || (await _db__WEBPACK_IMPORTED_MODULE_1__["getPayeeByName"](payeeName));
if (payee != null) {
return payee.id;
} else {
// Otherwise we're going to create a new one
let newPayee = {
id: uuid.v4Sync(),
name: payeeName
};
payeesToCreate.set(payeeName.toLowerCase(), newPayee);
return newPayee.id;
}
}
return trans.payee;
}
async function normalizeTransactions(transactions, acctId, {
rawPayeeName
} = {}) {
let payeesToCreate = new Map();
let normalized = [];
for (let trans of transactions) {
// Validate the date because we do some stuff with it. The db
// layer does better validation, but this will give nicer errors
if (trans.date == null) {
throw new Error('`date` is required when adding a transaction');
} // Strip off the irregular properties
let _trans = trans,
payee_name = _trans.payee_name,
subtransactions = _trans.subtransactions,
rest = _objectWithoutProperties(_trans, _excluded2);
trans = rest;
if (payee_name) {
let trimmed = payee_name.trim();
if (trimmed === '') {
payee_name = null;
} else {
payee_name = rawPayeeName ? trimmed : _title__WEBPACK_IMPORTED_MODULE_0___default()(trimmed);
}
}
trans.imported_payee = trans.imported_payee || payee_name;
if (trans.imported_payee) {
trans.imported_payee = trans.imported_payee.trim();
} // It's important to resolve both the account and payee early so
// when rules are run, they have the right data. Resolving payees
// also simplifies the payee creation process
trans.account = acctId;
trans.payee = await resolvePayee(trans, payee_name, payeesToCreate);
normalized.push({
payee_name,
subtransactions: subtransactions ? subtransactions.map(t => _objectSpread(_objectSpread({}, t), {}, {
account: acctId
})) : null,
trans
});
}
return {
normalized,
payeesToCreate
};
}
async function createNewPayees(payeesToCreate, addsAndUpdates) {
let usedPayeeIds = new Set(addsAndUpdates.map(t => t.payee));
await Object(_sync__WEBPACK_IMPORTED_MODULE_7__["batchMessages"])(async () => {
for (let payee of payeesToCreate.values()) {
// Only create the payee if it ended up being used
if (usedPayeeIds.has(payee.id)) {
await _db__WEBPACK_IMPORTED_MODULE_1__["insertPayee"](payee);
}
}
});
}
async function reconcileTransactions(acctId, transactions) {
const hasMatched = new Set();
const updated = [];
const added = [];
let _await$normalizeTrans = await normalizeTransactions(transactions, acctId),
normalized = _await$normalizeTrans.normalized,
payeesToCreate = _await$normalizeTrans.payeesToCreate; // The first pass runs the rules, and preps data for fuzzy matching
let transactionsStep1 = [];
for (let _ref of normalized) {
let payee_name = _ref.payee_name;
let trans = _ref.trans;
let subtransactions = _ref.subtransactions;
// Run the rules
trans = Object(_transaction_rules__WEBPACK_IMPORTED_MODULE_12__["runRules"])(trans);
let match = null;
let fuzzyDataset = null; // First, match with an existing transaction's imported_id. This
// is the highest fidelity match and should always be attempted
// first.
if (trans.imported_id) {
match = await _db__WEBPACK_IMPORTED_MODULE_1__["first"]('SELECT * FROM v_transactions WHERE imported_id = ? AND account = ?', [trans.imported_id, acctId]); // TODO: Pending transactions
if (match) {
hasMatched.add(match.id);
}
} // If it didn't match, query data needed for fuzzy matching
if (!match) {
// Look 1 day ahead and 4 days back when fuzzy matching. This
// needs to select all fields that need to be read from the
// matched transaction. See the final pass below for the needed
// fields.
fuzzyDataset = await _db__WEBPACK_IMPORTED_MODULE_1__["all"](`SELECT id, date, imported_id, payee, category, notes FROM v_transactions
WHERE date >= ? AND date <= ? AND amount = ? AND account = ? AND is_child = 0`, [_db__WEBPACK_IMPORTED_MODULE_1__["toDateRepr"](_shared_months__WEBPACK_IMPORTED_MODULE_4__["subDays"](trans.date, 4)), _db__WEBPACK_IMPORTED_MODULE_1__["toDateRepr"](_shared_months__WEBPACK_IMPORTED_MODULE_4__["addDays"](trans.date, 1)), trans.amount || 0, acctId]);
}
transactionsStep1.push({
payee_name,
trans,
subtransactions,
match,
fuzzyDataset
});
} // Next, do the fuzzy matching. This first pass matches based on the
// payee id. We do this in multiple passes so that higher fidelity
// matching always happens first, i.e. a transaction should match
// match with low fidelity if a later transaction is going to match
// the same one with high fidelity.
let transactionsStep2 = transactionsStep1.map(data => {
if (!data.match && data.fuzzyDataset) {
// Try to find one where the payees match.
let match = data.fuzzyDataset.find(row => !hasMatched.has(row.id) && data.trans.payee === row.payee);
if (match) {
hasMatched.add(match.id);
return _objectSpread(_objectSpread({}, data), {}, {
match
});
}
}
return data;
}); // The final fuzzy matching pass. This is the lowest fidelity
// matching: it just find the first transaction that hasn't been
// matched yet. Remember the the dataset only contains transactions
// around the same date with the same amount.
let transactionsStep3 = transactionsStep2.map(data => {
if (!data.match && data.fuzzyDataset) {
let match = data.fuzzyDataset.find(row => !hasMatched.has(row.id));
if (match) {
hasMatched.add(match.id);
return _objectSpread(_objectSpread({}, data), {}, {
match
});
}
}
return data;
}); // Finally, generate & commit the changes
for (let _ref2 of transactionsStep3) {
let payee_name = _ref2.payee_name;
let trans = _ref2.trans;
let subtransactions = _ref2.subtransactions;
let match = _ref2.match;
if (match) {
// TODO: change the above sql query to use aql
let existing = _objectSpread(_objectSpread({}, match), {}, {
cleared: match.cleared === 1,
date: _db__WEBPACK_IMPORTED_MODULE_1__["fromDateRepr"](match.date)
}); // Update the transaction
const updates = {
date: trans.date,
imported_id: trans.imported_id || null,
payee: existing.payee || trans.payee || null,
category: existing.category || trans.category || null,
imported_payee: trans.imported_payee || null,
notes: existing.notes || trans.notes || null,
cleared: trans.cleared != null ? trans.cleared : true
};
if (Object(_shared_util__WEBPACK_IMPORTED_MODULE_2__["hasFieldsChanged"])(existing, updates, Object.keys(updates))) {
updated.push(_objectSpread({
id: existing.id
}, updates));
}
} else {
// Insert a new transaction
let finalTransaction = _objectSpread(_objectSpread({}, trans), {}, {
id: uuid.v4Sync(),
category: trans.category || null,
cleared: trans.cleared != null ? trans.cleared : true
});
if (subtransactions && subtransactions.length > 0) {
added.push(...makeSplitTransaction(finalTransaction, subtransactions));
} else {
added.push(finalTransaction);
}
}
}
await createNewPayees(payeesToCreate, [...added, ...updated]);
await Object(_transactions__WEBPACK_IMPORTED_MODULE_13__["batchUpdateTransactions"])({
added,
updated
});
return {
added: added.map(trans => trans.id),
updated: updated.map(trans => trans.id)
};
} // This is similar to `reconcileTransactions` except much simpler: it
// does not try to match any transactions. It just adds them
async function addTransactions(acctId, transactions, {
runTransfers = true
} = {}) {
const added = [];
let _await$normalizeTrans2 = await normalizeTransactions(transactions, acctId, {
rawPayeeName: true
}),
normalized = _await$normalizeTrans2.normalized,
payeesToCreate = _await$normalizeTrans2.payeesToCreate;
for (let _ref3 of normalized) {
let payee_name = _ref3.payee_name;
let trans = _ref3.trans;
let subtransactions = _ref3.subtransactions;
// Run the rules
trans = Object(_transaction_rules__WEBPACK_IMPORTED_MODULE_12__["runRules"])(trans);
let finalTransaction = _objectSpread(_objectSpread({
id: uuid.v4Sync()
}, trans), {}, {
account: acctId,
cleared: trans.cleared != null ? trans.cleared : true
}); // Add split transactions if they are given
if (subtransactions && subtransactions.length > 0) {
added.push(...makeSplitTransaction(finalTransaction, subtransactions));
} else {
added.push(finalTransaction);
}
}
await createNewPayees(payeesToCreate, added);
let newTransactions;
if (runTransfers) {
let res = await Object(_transactions__WEBPACK_IMPORTED_MODULE_13__["batchUpdateTransactions"])({
added
});
newTransactions = res.added.map(t => t.id);
} else {
await Object(_sync__WEBPACK_IMPORTED_MODULE_7__["batchMessages"])(async () => {
newTransactions = await Promise.all(added.map(async trans => _db__WEBPACK_IMPORTED_MODULE_1__["insertTransaction"](trans)));
});
}
return newTransactions;
}
async function syncAccount(userId, userKey, id, acctId, bankId) {
// TODO: Handle the case where transactions exist in the future
// (that will make start date after end date)
const latestTransaction = await _db__WEBPACK_IMPORTED_MODULE_1__["first"]('SELECT * FROM v_transactions WHERE account = ? ORDER BY date DESC LIMIT 1', [id]);
if (latestTransaction) {
const startingTransaction = await _db__WEBPACK_IMPORTED_MODULE_1__["first"]('SELECT date FROM v_transactions WHERE account = ? ORDER BY date ASC LIMIT 1', [id]);
const startingDate = _db__WEBPACK_IMPORTED_MODULE_1__["fromDateRepr"](startingTransaction.date); // assert(startingTransaction)
// Get all transactions since the latest transaction, plus any 5
// days before the latest transaction. This gives us a chance to
// resolve any transactions that were entered manually.
//
// TODO: What this really should do is query the last imported_id
// and since then
let date = _shared_months__WEBPACK_IMPORTED_MODULE_4__["subDays"](_db__WEBPACK_IMPORTED_MODULE_1__["fromDateRepr"](latestTransaction.date), 31); // Never download transactions before the starting date. This was
// when the account was added to the system.
if (date < startingDate) {
date = startingDate;
}
let _await$downloadTransa = await downloadTransactions(userId, userKey, acctId, bankId, date),
transactions = _await$downloadTransa.transactions,
accountBalance = _await$downloadTransa.accountBalance;
if (transactions.length === 0) {
return {
added: [],
updated: []
};
}
transactions = transactions.map(trans => _objectSpread(_objectSpread({}, trans), {}, {
account: id
}));
return Object(_mutators__WEBPACK_IMPORTED_MODULE_8__["runMutator"])(async () => {
const result = await reconcileTransactions(id, transactions);
await updateAccountBalance(id, accountBalance);
return result;
});
} else {
const acctRow = await _db__WEBPACK_IMPORTED_MODULE_1__["select"]('accounts', id); // Otherwise, download transaction for the last few days if it's an
// on-budget account, or for the past 30 days if off-budget
const startingDay = _shared_months__WEBPACK_IMPORTED_MODULE_4__["subDays"](_shared_months__WEBPACK_IMPORTED_MODULE_4__["currentDay"](), acctRow.offbudget === 0 ? 1 : 30);
const _await$downloadTransa2 = await downloadTransactions(userId, userKey, acctId, bankId, dateFns.format(dateFns.parseISO(startingDay), 'yyyy-MM-dd')),
transactions = _await$downloadTransa2.transactions; // We need to add a transaction that represents the starting
// balance for everything to balance out. In order to get balance
// before the first imported transaction, we need to get the
// current balance from the accounts table and subtract all the
// imported transactions.
let currentBalance = acctRow.balance_current;
const previousBalance = transactions.reduce((total, trans) => {
return total - trans.amount;
}, currentBalance);
const oldestDate = transactions.length > 0 ? transactions[transactions.length - 1].date : _shared_months__WEBPACK_IMPORTED_MODULE_4__["currentDay"]();
let payee = await Object(_payees__WEBPACK_IMPORTED_MODULE_9__["getStartingBalancePayee"])();
return Object(_mutators__WEBPACK_IMPORTED_MODULE_8__["runMutator"])(async () => {
let initialId = await _db__WEBPACK_IMPORTED_MODULE_1__["insertTransaction"]({
account: id,
amount: previousBalance,
category: acctRow.offbudget === 0 ? payee.category : null,
payee: payee.id,
date: oldestDate,
cleared: true,
starting_balance_flag: true
});
let result = await reconcileTransactions(id, transactions);
return _objectSpread(_objectSpread({}, result), {}, {
added: [initialId, ...result.added]
});
});
}
}
/***/ }),
/***/ "./packages/loot-core/src/server/accounts/title/index.js":
/*!***************************************************************!*\
!*** ./packages/loot-core/src/server/accounts/title/index.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// Utilities
const lowerCase = __webpack_require__(/*! ./lower-case */ "./packages/loot-core/src/server/accounts/title/lower-case.js");
const specials = __webpack_require__(/*! ./specials */ "./packages/loot-core/src/server/accounts/title/specials.js");
let character = '[0-9\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376-\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0523\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0621-\u064A\u066E-\u066F\u0671-\u06D3\u06D5\u06E5-\u06E6\u06EE-\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4-\u07F5\u07FA\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0972\u097B-\u097F\u0985-\u098C\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC-\u09DD\u09DF-\u09E1\u09F0-\u09F1\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33\u0A35-\u0A36\u0A38-\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0-\u0AE1\u0B05-\u0B0C\u0B0F-\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B35-\u0B39\u0B3D\u0B5C-\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58-\u0C59\u0C60-\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0-\u0CE1\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D3D\u0D60-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32-\u0E33\u0E40-\u0E46\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDD\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8B\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065-\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10D0-\u10FA\u10FC\u1100-\u1159\u115F-\u11A2\u11A8-\u11F9\u1200-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u1676\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19A9\u19C1-\u19C7\u1A00-\u1A16\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE-\u1BAF\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u2094\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2C6F\u2C71-\u2C7D\u2C80-\u2CE4\u2D00-\u2D25\u2D30-\u2D65\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31B7\u31F0-\u31FF\u3400\u4DB5\u4E00\u9FC3\uA000-\uA48C\uA500-\uA60C\uA610-\uA61F\uA62A-\uA62B\uA640-\uA65F\uA662-\uA66E\uA67F-\uA697\uA717-\uA71F\uA722-\uA788\uA78B-\uA78C\uA7FB-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA90A-\uA925\uA930-\uA946\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAC00\uD7A3\uF900-\uFA2D\uFA30-\uFA6A\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40-\uFB41\uFB43-\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]';
let regex = new RegExp(`(?:(?:(\\s?(?:^|[.\\(\\)!?;:"-])\\s*)(${character}))|(${character}))(${character}*[']*${character}*)`, 'g');
let convertToRegExp = specials => specials.map(s => [new RegExp(`\\b${s}\\b`, 'gi'), s]);
function parseMatch(match) {
const firstCharacter = match[0]; // test first character
if (/\s/.test(firstCharacter)) {
// if whitespace - trim and return
return match.substr(1);
}
if (/[()]/.test(firstCharacter)) {
// if parens - this shouldn't be replaced
return null;
}
return match;
}
module.exports = (str, options = {}) => {
str = str.toLowerCase().replace(regex, (m, lead = '', forced, lower, rest) => {
const parsedMatch = parseMatch(m);
if (!parsedMatch) {
return m;
}
if (!forced) {
const fullLower = lower + rest;
if (lowerCase.has(fullLower)) {
return parsedMatch;
}
}
return lead + (lower || forced).toUpperCase() + rest;
});
const customSpecials = options.special || [];
const replace = [...specials, ...customSpecials];
const replaceRegExp = convertToRegExp(replace);
replaceRegExp.forEach(([pattern, s]) => {
str = str.replace(pattern, s);
});
return str;
};
/***/ }),
/***/ "./packages/loot-core/src/server/accounts/title/lower-case.js":
/*!********************************************************************!*\
!*** ./packages/loot-core/src/server/accounts/title/lower-case.js ***!
\********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
const conjunctions = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so'];
const articles = ['a', 'an', 'the'];
const prepositions = ['aboard', 'about', 'above', 'across', 'after', 'against', 'along', 'amid', 'among', 'anti', 'around', 'as', 'at', 'before', 'behind', 'below', 'beneath', 'beside', 'besides', 'between', 'beyond', 'but', 'by', 'concerning', 'considering', 'despite', 'down', 'during', 'except', 'excepting', 'excluding', 'following', 'for', 'from', 'in', 'inside', 'into', 'like', 'minus', 'near', 'of', 'off', 'on', 'onto', 'opposite', 'over', 'past', 'per', 'plus', 'regarding', 'round', 'save', 'since', 'than', 'through', 'to', 'toward', 'towards', 'under', 'underneath', 'unlike', 'until', 'up', 'upon', 'versus', 'via', 'with', 'within', 'without'];
module.exports = new Set([...conjunctions, ...articles, ...prepositions]);
/***/ }),
/***/ "./packages/loot-core/src/server/accounts/title/specials.js":
/*!******************************************************************!*\
!*** ./packages/loot-core/src/server/accounts/title/specials.js ***!
\******************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
const intended = ['CLI', 'API', 'HTTP', 'HTTPS', 'JSX', 'DNS', 'URL', 'CI', 'CDN', 'GitHub', 'CSS', 'JS', 'JavaScript', 'TypeScript', 'HTML', 'WordPress', 'JavaScript', 'Next.js', 'Node.js'];
module.exports = intended;
/***/ }),
/***/ "./packages/loot-core/src/server/accounts/transaction-rules.js":
/*!*********************************************************************!*\
!*** ./packages/loot-core/src/server/accounts/transaction-rules.js ***!
\*********************************************************************/
/*! exports provided: iterateIds, resetState, ruleModel, makeRule, loadRules, getRules, insertRule, updateRule, deleteRule, runRules, conditionsToAQL, applyActions, getRulesForPayee, updatePayeeRenameRule, getProbableCategory, updateCategoryRules, migrateOldRules */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resetState", function() { return resetState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ruleModel", function() { return ruleModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeRule", function() { return makeRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadRules", function() { return loadRules; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRules", function() { return getRules; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "insertRule", function() { return insertRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateRule", function() { return updateRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteRule", function() { return deleteRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runRules", function() { return runRules; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conditionsToAQL", function() { return conditionsToAQL; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyActions", function() { return applyActions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRulesForPayee", function() { return getRulesForPayee; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updatePayeeRenameRule", function() { return updatePayeeRenameRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getProbableCategory", function() { return getProbableCategory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateCategoryRules", function() { return updateCategoryRules; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "migrateOldRules", function() { return migrateOldRules; });
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _rules__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./rules */ "./packages/loot-core/src/server/accounts/rules.js");
/* harmony import */ var _db_mappings__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../db/mappings */ "./packages/loot-core/src/server/db/mappings.js");
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _sync_index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../sync/index */ "./packages/loot-core/src/server/sync/index.js");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../errors */ "./packages/loot-core/src/server/errors.js");
/* harmony import */ var _shared_rules__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../shared/rules */ "./packages/loot-core/src/shared/rules.js");
/* harmony import */ var _shared_query__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../shared/query */ "./packages/loot-core/src/shared/query.js");
/* harmony import */ var _models__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../models */ "./packages/loot-core/src/server/models.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../shared/util */ "./packages/loot-core/src/shared/util.js");
/* harmony import */ var _aql_schema__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../aql/schema */ "./packages/loot-core/src/server/aql/schema/index.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "iterateIds", function() { return _rules__WEBPACK_IMPORTED_MODULE_1__["iterateIds"]; });
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const uuid = __webpack_require__(/*! ../../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js"); // TODO: Detect if it looks like the user is creating a rename rule
// and prompt to create it in the pre phase instead
// * We could also make the "create rule" button a dropdown that
// provides different "templates" like "create renaming rule"
let allRules;
let unlistenSync;
let firstcharIndexer;
let payeeIndexer;
function resetState() {
allRules = new Map();
firstcharIndexer = new _rules__WEBPACK_IMPORTED_MODULE_1__["RuleIndexer"]({
field: 'imported_payee',
method: 'firstchar'
});
payeeIndexer = new _rules__WEBPACK_IMPORTED_MODULE_1__["RuleIndexer"]({
field: 'payee'
});
} // Database functions
function invert(obj) {
return Object.fromEntries(Object.entries(obj).map(entry => {
return [entry[1], entry[0]];
}));
}
let internalFields = _aql_schema__WEBPACK_IMPORTED_MODULE_10__["schemaConfig"].views.transactions.fields;
let publicFields = invert(_aql_schema__WEBPACK_IMPORTED_MODULE_10__["schemaConfig"].views.transactions.fields);
function fromInternalField(obj) {
return _objectSpread(_objectSpread({}, obj), {}, {
field: publicFields[obj.field] || obj.field
});
}
function toInternalField(obj) {
return _objectSpread(_objectSpread({}, obj), {}, {
field: internalFields[obj.field] || obj.field
});
}
const ruleModel = {
validate(rule, {
update
} = {}) {
Object(_models__WEBPACK_IMPORTED_MODULE_8__["requiredFields"])('rules', rule, ['conditions', 'actions'], update);
if (!update || 'stage' in rule) {
if (rule.stage !== 'pre' && rule.stage !== 'post' && rule.stage !== null) {
throw new Error('Invalid rule stage: ' + rule.stage);
}
}
return rule;
},
toJS(row) {
function parseArray(str) {
let value;
try {
value = typeof str === 'string' ? JSON.parse(str) : str;
} catch (e) {
throw new _errors__WEBPACK_IMPORTED_MODULE_5__["RuleError"]('internal', 'Cannot parse rule json');
}
if (!Array.isArray(value)) {
throw new _errors__WEBPACK_IMPORTED_MODULE_5__["RuleError"]('internal', 'Rule json must be an array');
}
return value;
}
let rule = _objectSpread({}, row);
rule.conditions = rule.conditions ? parseArray(rule.conditions).map(cond => fromInternalField(cond)) : [];
rule.actions = rule.actions ? parseArray(rule.actions).map(action => fromInternalField(action)) : [];
return rule;
},
fromJS(rule) {
let row = _objectSpread({}, rule);
if ('conditions' in row) {
let conditions = row.conditions.map(cond => toInternalField(cond));
row.conditions = JSON.stringify(conditions);
}
if ('actions' in row) {
let actions = row.actions.map(action => toInternalField(action));
row.actions = JSON.stringify(actions);
}
return row;
}
};
function makeRule(data) {
let rule;
try {
rule = new _rules__WEBPACK_IMPORTED_MODULE_1__["Rule"](_objectSpread(_objectSpread({}, ruleModel.toJS(data)), {}, {
fieldTypes: _shared_rules__WEBPACK_IMPORTED_MODULE_6__["FIELD_TYPES"]
}));
} catch (e) {
console.warn('Invalid rule', e);
if (e instanceof _errors__WEBPACK_IMPORTED_MODULE_5__["RuleError"]) {
return null;
}
throw e;
} // This is needed because we map ids on the fly, and they might
// not be persisted into the db. Mappings allow items to
// transparently merge with other items
Object(_rules__WEBPACK_IMPORTED_MODULE_1__["migrateIds"])(rule, Object(_db_mappings__WEBPACK_IMPORTED_MODULE_2__["getMappings"])());
return rule;
}
async function loadRules() {
resetState();
let rules = await _db__WEBPACK_IMPORTED_MODULE_0__["all"](`
SELECT * FROM rules
WHERE conditions IS NOT NULL AND actions IS NOT NULL AND tombstone = 0
`);
for (let i = 0; i < rules.length; i++) {
let desc = rules[i]; // These are old stages, can be removed before release
if (desc.stage === 'cleanup' || desc.stage === 'modify') {
desc.stage = 'pre';
}
let rule = makeRule(desc);
if (rule) {
allRules.set(rule.id, rule);
firstcharIndexer.index(rule);
payeeIndexer.index(rule);
}
}
if (unlistenSync) {
unlistenSync();
}
unlistenSync = Object(_sync_index__WEBPACK_IMPORTED_MODULE_4__["addSyncListener"])(onApplySync);
}
function getRules() {
// This can simply return the in-memory data
return [...allRules.values()];
}
async function insertRule(rule) {
rule = ruleModel.validate(rule);
return _db__WEBPACK_IMPORTED_MODULE_0__["insertWithUUID"]('rules', ruleModel.fromJS(rule));
}
async function updateRule(rule) {
rule = ruleModel.validate(rule, {
update: true
});
return _db__WEBPACK_IMPORTED_MODULE_0__["update"]('rules', ruleModel.fromJS(rule));
}
async function deleteRule(rule) {
let schedule = await _db__WEBPACK_IMPORTED_MODULE_0__["first"]('SELECT id FROM schedules WHERE rule = ?', [rule.id]);
if (schedule) {
return false;
}
return _db__WEBPACK_IMPORTED_MODULE_0__["delete_"]('rules', rule.id);
} // Sync projections
function onApplySync(oldValues, newValues) {
newValues.forEach((items, table) => {
if (table === 'rules') {
items.forEach(newValue => {
let oldRule = allRules.get(newValue.id);
if (newValue.tombstone === 1) {
// Deleted, need to remove it from in-memory
let rule = allRules.get(newValue.id);
if (rule) {
allRules.delete(rule.getId());
firstcharIndexer.remove(rule);
payeeIndexer.remove(rule);
}
} else {
// Inserted/updated
let rule = makeRule(newValue);
if (rule) {
if (oldRule) {
firstcharIndexer.remove(oldRule);
payeeIndexer.remove(oldRule);
}
allRules.set(newValue.id, rule);
firstcharIndexer.index(rule);
payeeIndexer.index(rule);
}
}
});
}
}); // If any of the mapping tables have changed, we need to refresh the
// ids
let tables = [...newValues.keys()];
if (tables.find(table => table.indexOf('mapping') !== -1)) {
getRules().forEach(rule => {
Object(_rules__WEBPACK_IMPORTED_MODULE_1__["migrateIds"])(rule, Object(_db_mappings__WEBPACK_IMPORTED_MODULE_2__["getMappings"])());
});
}
} // Runner
function runRules(trans) {
let finalTrans = _objectSpread({}, trans);
let allChanges = {};
let rules = Object(_rules__WEBPACK_IMPORTED_MODULE_1__["rankRules"])(Object(_shared_util__WEBPACK_IMPORTED_MODULE_9__["fastSetMerge"])(firstcharIndexer.getApplicableRules(trans), payeeIndexer.getApplicableRules(trans)));
for (let i = 0; i < rules.length; i++) {
finalTrans = rules[i].apply(finalTrans);
}
return finalTrans;
} // This does the inverse: finds all the transactions matching a rule
function conditionsToAQL(conditions, {
recurDateBounds = 100
} = {}) {
let errors = [];
conditions = conditions.map(cond => {
if (cond instanceof _rules__WEBPACK_IMPORTED_MODULE_1__["Condition"]) {
return cond;
}
try {
return new _rules__WEBPACK_IMPORTED_MODULE_1__["Condition"](cond.op, cond.field, cond.value, cond.options, _shared_rules__WEBPACK_IMPORTED_MODULE_6__["FIELD_TYPES"]);
} catch (e) {
errors.push(e.type || 'internal');
console.log('conditionsToAQL: invalid condition: ' + e.message);
return null;
}
}).filter(Boolean); // rule -> actualql
let filters = conditions.map(cond => {
let type = cond.type,
field = cond.field,
op = cond.op,
value = cond.value,
options = cond.options;
let getValue = value => {
if (type === 'number') {
return value.value;
}
return value;
};
let apply = (field, op, value) => {
if (type === 'number') {
if (options) {
if (options.outflow) {
return {
$and: [{
amount: {
$lt: 0
}
}, {
[field]: {
$transform: '$neg',
[op]: value
}
}]
};
} else if (options.inflow) {
return {
$and: [{
amount: {
$gt: 0
}
}, {
[field]: {
[op]: value
}
}]
};
}
}
return {
amount: {
[op]: value
}
};
} else if (type === 'string') {
return {
[field]: {
$transform: '$lower',
[op]: value
}
};
} else if (type === 'date') {
return {
[field]: {
[op]: value.date
}
};
}
return {
[field]: {
[op]: value
}
};
};
switch (op) {
case 'isapprox':
case 'is':
if (type === 'date') {
if (value.type === 'recur') {
let dates = value.schedule.occurrences({
take: recurDateBounds
}).toArray().map(d => Object(_shared_months__WEBPACK_IMPORTED_MODULE_3__["dayFromDate"])(d.date));
let compare = d => ({
$eq: d
});
return {
$or: dates.map(d => {
if (op === 'isapprox') {
return {
$and: [{
date: {
$gte: Object(_shared_months__WEBPACK_IMPORTED_MODULE_3__["subDays"])(d, 2)
}
}, {
date: {
$lte: Object(_shared_months__WEBPACK_IMPORTED_MODULE_3__["addDays"])(d, 2)
}
}]
};
}
return {
date: d
};
})
};
} else {
let date = value.date;
if (op === 'isapprox') {
let fullDate = Object(_shared_months__WEBPACK_IMPORTED_MODULE_3__["parseDate"])(value.date);
let high = Object(_shared_months__WEBPACK_IMPORTED_MODULE_3__["addDays"])(fullDate, 2);
let low = Object(_shared_months__WEBPACK_IMPORTED_MODULE_3__["subDays"])(fullDate, 2);
return {
$and: [{
date: {
$gte: low
}
}, {
date: {
$lte: high
}
}]
};
} else {
switch (value.type) {
case 'date':
return {
date: value.date
};
case 'month':
{
let low = value.date + '-00';
let high = value.date + '-99';
return {
$and: [{
date: {
$gte: low
}
}, {
date: {
$lte: high
}
}]
};
}
case 'year':
{
let low = value.date + '-00-00';
let high = value.date + '-99-99';
return {
$and: [{
date: {
$gte: low
}
}, {
date: {
$lte: high
}
}]
};
}
default:
}
}
}
} else if (type === 'number') {
let number = value.value;
if (op === 'isapprox') {
let threshold = Object(_shared_rules__WEBPACK_IMPORTED_MODULE_6__["getApproxNumberThreshold"])(number);
return {
$and: [apply(field, '$gte', number - threshold), apply(field, '$lte', number + threshold)]
};
}
return apply(field, '$eq', number);
}
return apply(field, '$eq', value);
case 'isbetween':
// This operator is only applicable to the specific `between`
// number type so we don't use `apply`
let _sortNumbers = Object(_shared_rules__WEBPACK_IMPORTED_MODULE_6__["sortNumbers"])(value.num1, value.num2),
_sortNumbers2 = _slicedToArray(_sortNumbers, 2),
low = _sortNumbers2[0],
high = _sortNumbers2[1];
return {
[field]: [{
$gte: low
}, {
$lte: high
}]
};
case 'contains':
// Running contains with id will automatically reach into
// the `name` of the referenced table and do a string match
return apply(type === 'id' ? field + '.name' : field, '$like', '%' + value + '%');
case 'oneOf':
let values = value;
if (values.length === 0) {
// This forces it to match nothing
return {
id: null
};
}
return {
$or: values.map(v => apply(field, '$eq', v))
};
case 'gt':
return apply(field, '$gt', getValue(value));
case 'gte':
return apply(field, '$gte', getValue(value));
case 'lt':
return apply(field, '$lt', getValue(value));
case 'lte':
return apply(field, '$lte', getValue(value));
case 'true':
return apply(field, '$eq', true);
case 'false':
return apply(field, '$eq', false);
default:
throw new Error('Unhandled operator: ' + op);
}
});
return {
filters,
errors
};
}
function applyActions(transactionIds, actions, handlers) {
let parsedActions = actions.map(action => {
if (action instanceof _rules__WEBPACK_IMPORTED_MODULE_1__["Action"]) {
return action;
}
try {
return new _rules__WEBPACK_IMPORTED_MODULE_1__["Action"](action.op, action.field, action.value, action.options, _shared_rules__WEBPACK_IMPORTED_MODULE_6__["FIELD_TYPES"]);
} catch (e) {
console.log('Action error', e);
return null;
}
}).filter(Boolean);
if (parsedActions.length !== actions.length) {
// An error happened while parsing
return null;
}
let updated = transactionIds.map(id => {
let update = {
id
};
for (let action of parsedActions) {
action.exec(update);
}
return update;
});
return handlers['transactions-batch-update']({
updated
});
}
function getRulesForPayee(payeeId) {
let rules = new Set();
Object(_rules__WEBPACK_IMPORTED_MODULE_1__["iterateIds"])(getRules(), 'payee', (rule, id) => {
if (id === payeeId) {
rules.add(rule);
}
});
return Object(_rules__WEBPACK_IMPORTED_MODULE_1__["rankRules"])([...rules]);
}
function* getIsSetterRules(stage, condField, actionField, {
condValue,
actionValue
}) {
let rules = getRules();
for (let i = 0; i < rules.length; i++) {
let rule = rules[i];
if (rule.stage === stage && rule.actions.length === 1 && rule.actions[0].op === 'set' && rule.actions[0].field === actionField && (actionValue === undefined || rule.actions[0].value === actionValue) && rule.conditions.length === 1 && rule.conditions[0].op === 'is' && rule.conditions[0].field === condField && (condValue === undefined || rule.conditions[0].value === condValue)) {
yield rule.serialize();
}
}
return null;
}
function* getOneOfSetterRules(stage, condField, actionField, {
condValue,
actionValue
}) {
let rules = getRules();
for (let i = 0; i < rules.length; i++) {
let rule = rules[i];
if (rule.stage === stage && rule.actions.length === 1 && rule.actions[0].op === 'set' && rule.actions[0].field === actionField && (actionValue == null || rule.actions[0].value === actionValue) && rule.conditions.length === 1 && rule.conditions[0].op === 'oneOf' && rule.conditions[0].field === condField && (condValue == null || rule.conditions[0].value.indexOf(condValue) !== -1)) {
yield rule.serialize();
}
}
return null;
}
async function updatePayeeRenameRule(fromNames, to) {
let renameRule = getOneOfSetterRules('pre', 'imported_payee', 'payee', {
actionValue: to
}).next().value; // Note that we don't check for existing rules that set this
// `imported_payee` to something else. It's important to do
// that for categories because categories will be changes frequently
// for the same payee, but renames won't be changed much. It's a use
// case we could improve in the future, but this is fine for now.
if (renameRule) {
let condition = renameRule.conditions[0];
let newValue = [...Object(_shared_util__WEBPACK_IMPORTED_MODULE_9__["fastSetMerge"])(new Set(condition.value), new Set(fromNames.filter(name => name !== '')))];
let rule = _objectSpread(_objectSpread({}, renameRule), {}, {
conditions: [_objectSpread(_objectSpread({}, condition), {}, {
value: newValue
})]
});
await updateRule(rule);
return renameRule.id;
} else {
let rule = new _rules__WEBPACK_IMPORTED_MODULE_1__["Rule"]({
stage: 'pre',
conditions: [{
op: 'oneOf',
field: 'imported_payee',
value: fromNames
}],
actions: [{
op: 'set',
field: 'payee',
value: to
}],
fieldTypes: _shared_rules__WEBPACK_IMPORTED_MODULE_6__["FIELD_TYPES"]
});
return insertRule(rule.serialize());
}
}
function getProbableCategory(transactions) {
let scores = new Map();
transactions.forEach(trans => {
if (trans.category) {
scores.set(trans.category, (scores.get(trans.category) || 0) + 1);
}
});
let winner = transactions.reduce((winner, trans) => {
let score = scores.get(trans.category);
if (!winner || score > winner.score) {
return {
score,
category: trans.category
};
}
return winner;
}, null);
return winner.score >= 3 ? winner.category : null;
}
async function updateCategoryRules(transactions) {
if (transactions.length === 0) {
return;
}
let payeeIds = new Set(transactions.map(trans => trans.payee));
let transIds = new Set(transactions.map(trans => trans.id)); // It's going to be quickest to get the oldest date and then query
// all transactions since then so we can work in memory
let oldestDate = null;
for (let i = 0; i < transactions.length; i++) {
if (oldestDate === null || transactions[i].date < oldestDate) {
oldestDate = transactions[i].date;
}
} // We look 6 months behind to include any other transaction. This
// makes it so we, 1. don't have to load in all transactions ever
// and 2. "forget" really old transactions which might be nice and
// 3. don't have to individually run a query for each payee
oldestDate = Object(_shared_months__WEBPACK_IMPORTED_MODULE_3__["subDays"])(oldestDate, 180); // Also look 180 days in the future to get any future transactions
// (this might change when we think about scheduled transactions)
let register = await _db__WEBPACK_IMPORTED_MODULE_0__["all"](`SELECT t.* FROM v_transactions t
LEFT JOIN accounts a ON a.id = t.account
WHERE date >= ? AND date <= ? AND is_parent = 0 AND a.closed = 0`, [Object(_models__WEBPACK_IMPORTED_MODULE_8__["toDateRepr"])(oldestDate), Object(_models__WEBPACK_IMPORTED_MODULE_8__["toDateRepr"])(Object(_shared_months__WEBPACK_IMPORTED_MODULE_3__["addDays"])(Object(_shared_months__WEBPACK_IMPORTED_MODULE_3__["currentDay"])(), 180))]);
let allTransactions = Object(_shared_util__WEBPACK_IMPORTED_MODULE_9__["partitionByField"])(register, 'payee');
let categoriesToSet = new Map();
for (let payeeId of payeeIds) {
// Don't do anything if payee is null
if (payeeId) {
let latestTrans = (allTransactions.get(payeeId) || []).slice(0, 5); // Check if one of the latest transactions was one that was
// updated. We only want to update anything if so.
if (latestTrans.find(trans => transIds.has(trans.id))) {
let category = getProbableCategory(latestTrans);
if (category) {
categoriesToSet.set(payeeId, category);
}
}
}
}
await Object(_sync_index__WEBPACK_IMPORTED_MODULE_4__["batchMessages"])(async () => {
for (let _ref of categoriesToSet.entries()) {
var _ref2 = _slicedToArray(_ref, 2);
let payeeId = _ref2[0];
let category = _ref2[1];
let ruleSetters = [...getIsSetterRules(null, 'payee', 'category', {
condValue: payeeId
})];
if (ruleSetters.length > 0) {
// If there are existing rules, change all of them to the new
// category (if they aren't already using it). We set all of
// them because it's possible that multiple rules exist
// because 2 clients made them independently. Not really a big
// deal, but to make sure our update gets applied set it to
// all of them
for (let rule of ruleSetters) {
let action = rule.actions[0];
if (action.value !== category) {
await updateRule(_objectSpread(_objectSpread({}, rule), {}, {
actions: [_objectSpread(_objectSpread({}, action), {}, {
value: category
})]
}));
}
}
} else {
// No existing rules, so create one
let newRule = new _rules__WEBPACK_IMPORTED_MODULE_1__["Rule"]({
stage: null,
conditions: [{
op: 'is',
field: 'payee',
value: payeeId
}],
actions: [{
op: 'set',
field: 'category',
value: category
}],
fieldTypes: _shared_rules__WEBPACK_IMPORTED_MODULE_6__["FIELD_TYPES"]
});
await insertRule(newRule.serialize());
}
}
});
} // This can be removed in the future
async function migrateOldRules() {
let allPayees = await _db__WEBPACK_IMPORTED_MODULE_0__["all"](`SELECT p.*, c.id as category FROM payees p
LEFT JOIN category_mapping cm ON cm.id = p.category
LEFT JOIN categories c ON (c.id = cm.transferId AND c.tombstone = 0)
WHERE p.tombstone = 0 AND transfer_acct IS NULL`);
let allRules = await _db__WEBPACK_IMPORTED_MODULE_0__["all"](`SELECT pr.*, pm.targetId as payee_id FROM payee_rules pr
LEFT JOIN payee_mapping pm ON pm.id = pr.payee_id
WHERE pr.tombstone = 0`);
let payeesById = new Map();
for (let i = 0; i < allPayees.length; i++) {
payeesById.set(allPayees[i].id, allPayees[i]);
}
let rulesByPayeeId = new Map();
for (let i = 0; i < allRules.length; i++) {
let item = allRules[i];
let rules = rulesByPayeeId.get(item.payee_id) || [];
rules.push(item);
rulesByPayeeId.set(item.payee_id, rules);
}
let rules = []; // Convert payee name rules
for (let _ref3 of rulesByPayeeId.entries()) {
var _ref4 = _slicedToArray(_ref3, 2);
let payeeId = _ref4[0];
let payeeRules = _ref4[1];
let equals = payeeRules.filter(r => {
let payee = payeesById.get(r.payee_id);
return (r.type === 'equals' || r.type == null) && (!payee || r.value.toLowerCase() !== payee.name.toLowerCase());
});
let contains = payeeRules.filter(r => r.type === 'contains');
let actions = [{
op: 'set',
field: 'payee',
value: payeeId
}];
if (equals.length > 0) {
rules.push({
stage: null,
conditions: [{
op: 'oneOf',
field: 'imported_payee',
value: equals.map(payeeRule => payeeRule.value)
}],
actions
});
}
if (contains.length > 0) {
rules = rules.concat(contains.map(payeeRule => ({
stage: null,
conditions: [{
op: 'contains',
field: 'imported_payee',
value: payeeRule.value
}],
actions
})));
}
} // Convert category rules
let catRules = allPayees.filter(p => p.category).reduce((map, payee) => {
let ids = map.get(payee.category) || new Set();
ids.add(payee.id);
map.set(payee.category, ids);
return map;
}, new Map());
for (let _ref5 of catRules) {
var _ref6 = _slicedToArray(_ref5, 2);
let catId = _ref6[0];
let payeeIds = _ref6[1];
rules.push({
stage: null,
conditions: [{
op: 'oneOf',
field: 'payee',
value: [...payeeIds]
}],
actions: [{
op: 'set',
field: 'category',
value: catId
}]
});
} // Very important: we never want to sync migration changes, but it
// still has to run through the syncing layer to make sure
// projections are correct. This is only OK because we require a
// sync reset after this.
let prevMode = Object(_sync_index__WEBPACK_IMPORTED_MODULE_4__["setSyncingMode"])('disabled');
await Object(_sync_index__WEBPACK_IMPORTED_MODULE_4__["batchMessages"])(async () => {
for (let rule of rules) {
await insertRule({
stage: rule.stage,
conditions: rule.conditions,
actions: rule.actions
});
}
await _db__WEBPACK_IMPORTED_MODULE_0__["runQuery"]('DELETE FROM payee_rules', []);
});
Object(_sync_index__WEBPACK_IMPORTED_MODULE_4__["setSyncingMode"])(prevMode);
}
/***/ }),
/***/ "./packages/loot-core/src/server/accounts/transactions.js":
/*!****************************************************************!*\
!*** ./packages/loot-core/src/server/accounts/transactions.js ***!
\****************************************************************/
/*! exports provided: batchUpdateTransactions */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchUpdateTransactions", function() { return batchUpdateTransactions; });
/* harmony import */ var _sheet__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../sheet */ "./packages/loot-core/src/server/sheet.js");
/* harmony import */ var _sync__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../sync */ "./packages/loot-core/src/server/sync/index.js");
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _db_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../db/util */ "./packages/loot-core/src/server/db/util.js");
/* harmony import */ var _transfer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./transfer */ "./packages/loot-core/src/server/accounts/transfer.js");
/* harmony import */ var _transaction_rules__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./transaction-rules */ "./packages/loot-core/src/server/accounts/transaction-rules.js");
const connection = __webpack_require__(/*! ../../platform/server/connection */ "./packages/loot-core/src/platform/server/connection/index.api.js");
async function idsWithChildren(ids) {
let whereIds = Object(_db_util__WEBPACK_IMPORTED_MODULE_3__["whereIn"])(ids, 'parent_id');
let rows = await _db__WEBPACK_IMPORTED_MODULE_2__["all"](`SELECT id FROM v_transactions_internal WHERE ${whereIds}`);
let set = new Set(ids);
for (let row of rows) {
set.add(row.id);
}
return [...set];
}
async function getTransactionsByIds(ids) {
// TODO: convert to whereIn
//
// or better yet, use ActualQL
return Object(_db_util__WEBPACK_IMPORTED_MODULE_3__["incrFetch"])((query, params) => _db__WEBPACK_IMPORTED_MODULE_2__["selectWithSchema"]('transactions', query, params), ids, id => `id = '${id}'`, where => `SELECT * FROM v_transactions_internal WHERE ${where}`);
}
async function batchUpdateTransactions({
added,
deleted,
updated,
learnCategories = false,
detectOrphanPayees = true
}) {
// Track the ids of each type of transaction change (see below for why)
let addedIds = [];
let updatedIds = updated ? updated.map(u => u.id) : [];
let deletedIds = deleted ? await idsWithChildren(deleted.map(d => d.id)) : [];
let oldPayees = new Set();
let accounts = await _db__WEBPACK_IMPORTED_MODULE_2__["all"]('SELECT * FROM accounts WHERE tombstone = 0'); // We need to get all the payees of updated transactions _before_
// making changes
if (updated) {
let descUpdatedIds = updated.filter(update => update.payee).map(update => update.id);
let transactions = await getTransactionsByIds(descUpdatedIds);
for (let i = 0; i < transactions.length; i++) {
oldPayees.add(transactions[i].payee);
}
} // Apply all the updates. We can batch this now! This is important
// and makes bulk updates much faster
await Object(_sync__WEBPACK_IMPORTED_MODULE_1__["batchMessages"])(async () => {
if (added) {
addedIds = await Promise.all(added.map(async t => _db__WEBPACK_IMPORTED_MODULE_2__["insertTransaction"](t)));
}
if (deleted) {
await Promise.all( // It's important to use `deletedIds` and not `deleted` here
// because we've expanded it to include children above. The
// inconsistency of the delete APIs is annoying and should
// be fixed (it should only take an id)
deletedIds.map(async id => {
await _db__WEBPACK_IMPORTED_MODULE_2__["deleteTransaction"]({
id
});
}));
}
if (updated) {
await Promise.all(updated.map(async t => {
if (t.account) {
// Moving transactions off budget should always clear the
// category
let account = accounts.find(acct => acct.id === t.account);
if (account.offbudget === 1) {
t.category = null;
}
}
await _db__WEBPACK_IMPORTED_MODULE_2__["updateTransaction"](t);
}));
}
}); // Get all of the full transactions that were changed. This is
// needed to run any cascading logic that depends on the full
// transaction. Things like transfers, analyzing rule updates, and
// more
let allAdded = await getTransactionsByIds(addedIds);
let allUpdated = await getTransactionsByIds(updatedIds);
let allDeleted = await getTransactionsByIds(deletedIds); // Post-processing phase: first do any updates to transfers.
// Transfers update the transactions and we need to return updates
// to the client so that can apply them. Note that added
// transactions just return the full transaction.
let resultAdded = allAdded;
let resultUpdated;
await Object(_sync__WEBPACK_IMPORTED_MODULE_1__["batchMessages"])(async () => {
await Promise.all(allAdded.map(t => _transfer__WEBPACK_IMPORTED_MODULE_4__["onInsert"](t))); // Return any updates from here
resultUpdated = (await Promise.all(allUpdated.map(t => _transfer__WEBPACK_IMPORTED_MODULE_4__["onUpdate"](t)))).filter(Boolean);
await Promise.all(allDeleted.map(t => _transfer__WEBPACK_IMPORTED_MODULE_4__["onDelete"](t)));
});
if (learnCategories) {
// Analyze any updated categories and update rules to learn from
// the user's activity
let ids = new Set([...(added ? added.filter(add => add.category).map(add => add.id) : []), ...(updated ? updated.filter(update => update.category).map(update => update.id) : [])]);
await _transaction_rules__WEBPACK_IMPORTED_MODULE_5__["updateCategoryRules"](allAdded.concat(allUpdated).filter(trans => ids.has(trans.id)));
}
if (detectOrphanPayees) {
// Look for any orphaned payees and notify the user about merging
// them
if (updated) {
let newPayeeIds = updated.map(u => u.payee).filter(Boolean);
if (newPayeeIds.length > 0) {
let allOrphaned = new Set(await _db__WEBPACK_IMPORTED_MODULE_2__["getOrphanedPayees"]());
let orphanedIds = [...oldPayees].filter(id => allOrphaned.has(id));
if (orphanedIds.length > 0) {
connection.send('orphaned-payees', {
orphanedIds,
updatedPayeeIds: newPayeeIds
});
}
}
}
}
return {
added: resultAdded,
updated: resultUpdated
};
}
/***/ }),
/***/ "./packages/loot-core/src/server/accounts/transfer.js":
/*!************************************************************!*\
!*** ./packages/loot-core/src/server/accounts/transfer.js ***!
\************************************************************/
/*! exports provided: addTransfer, removeTransfer, updateTransfer, onInsert, onDelete, onUpdate */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addTransfer", function() { return addTransfer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeTransfer", function() { return removeTransfer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateTransfer", function() { return updateTransfer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onInsert", function() { return onInsert; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onDelete", function() { return onDelete; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onUpdate", function() { return onUpdate; });
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
async function getPayee(acct) {
return _db__WEBPACK_IMPORTED_MODULE_0__["first"]('SELECT * FROM payees WHERE transfer_acct = ?', [acct]);
}
async function getTransferredAccount(transaction) {
if (transaction.payee) {
let _await$db$first = await _db__WEBPACK_IMPORTED_MODULE_0__["first"]('SELECT id, transfer_acct FROM v_payees WHERE id = ?', [transaction.payee]),
transfer_acct = _await$db$first.transfer_acct,
id = _await$db$first.id;
return transfer_acct;
}
return null;
}
async function clearCategory(transaction, transferAcct) {
const _await$db$first2 = await _db__WEBPACK_IMPORTED_MODULE_0__["first"]('SELECT offbudget FROM accounts WHERE id = ?', [transaction.account]),
fromOffBudget = _await$db$first2.offbudget;
const _await$db$first3 = await _db__WEBPACK_IMPORTED_MODULE_0__["first"]('SELECT offbudget FROM accounts WHERE id = ?', [transferAcct]),
toOffBudget = _await$db$first3.offbudget; // We should clear the category to make sure it's not being
// accounted for in the budget, unless it should be in the case of
// transferring from an on-budget to off-budget account
if (fromOffBudget === toOffBudget) {
await _db__WEBPACK_IMPORTED_MODULE_0__["updateTransaction"]({
id: transaction.id,
category: null
});
return true;
}
return false;
}
async function addTransfer(transaction, transferredAccount) {
let _await$db$first4 = await _db__WEBPACK_IMPORTED_MODULE_0__["first"]('SELECT id FROM payees WHERE transfer_acct = ?', [transaction.account]),
fromPayee = _await$db$first4.id; // We need to enforce certain constraints with child transaction transfers
if (transaction.parent_id) {
let row = await _db__WEBPACK_IMPORTED_MODULE_0__["first"](`
SELECT p.id, p.transfer_acct FROM v_transactions t
LEFT JOIN payees p ON p.id = t.payee
WHERE t.id = ?
`, [transaction.parent_id]);
if (row.transfer_acct) {
if (row.id !== transaction.payee) {
// This child transaction is trying to use a transfer payee,
// but the parent is already using a different transfer payee.
// This is not allowed, so not only do we do nothing, we clear
// the payee of the child transaction to make it clear
await _db__WEBPACK_IMPORTED_MODULE_0__["updateTransaction"]({
id: transaction.id,
payee: null
});
return {
id: transaction.id,
payee: null
};
} // The parent has the same transfer payee, so it "owns" the
// transfer logic
return null;
}
}
const id = await _db__WEBPACK_IMPORTED_MODULE_0__["insertTransaction"]({
account: transferredAccount,
amount: -transaction.amount,
payee: fromPayee,
date: transaction.date,
transfer_id: transaction.id,
notes: transaction.notes || null,
cleared: false
});
await _db__WEBPACK_IMPORTED_MODULE_0__["updateTransaction"]({
id: transaction.id,
transfer_id: id
});
const categoryCleared = await clearCategory(transaction, transferredAccount);
return _objectSpread({
id: transaction.id,
transfer_id: id
}, categoryCleared ? {
category: null
} : {});
}
async function removeTransfer(transaction) {
let transferTrans = await _db__WEBPACK_IMPORTED_MODULE_0__["getTransaction"](transaction.transfer_id);
if (transferTrans.is_child) {
// If it's a child transaction, we don't delete it because that
// would invalidate the whole split transaction. Instead of turn
// it into a normal transaction
await _db__WEBPACK_IMPORTED_MODULE_0__["updateTransaction"]({
id: transaction.transfer_id,
transfer_id: null,
payee: null
});
} else {
await _db__WEBPACK_IMPORTED_MODULE_0__["deleteTransaction"]({
id: transaction.transfer_id
});
}
await _db__WEBPACK_IMPORTED_MODULE_0__["updateTransaction"]({
id: transaction.id,
transfer_id: null
});
return {
id: transaction.id,
transfer_id: null
};
}
async function updateTransfer(transaction, transferredAccount) {
let payee = await getPayee(transaction.account);
await _db__WEBPACK_IMPORTED_MODULE_0__["updateTransaction"]({
id: transaction.transfer_id,
account: transferredAccount,
// Make sure to update the payee on the other side in case the
// user moved this transaction into another account
payee: payee.id,
date: transaction.date,
notes: transaction.notes,
amount: -transaction.amount
});
const categoryCleared = await clearCategory(transaction, transferredAccount);
if (categoryCleared) {
return {
id: transaction.id,
category: null
};
}
}
async function onInsert(transaction) {
let transferredAccount = await getTransferredAccount(transaction);
if (transferredAccount) {
return addTransfer(transaction, transferredAccount);
}
}
async function onDelete(transaction) {
if (transaction.transfer_id) {
await removeTransfer(transaction);
}
}
async function onUpdate(transaction) {
const transferredAccount = await getTransferredAccount(transaction);
if (transferredAccount && !transaction.transfer_id) {
return addTransfer(transaction, transferredAccount);
}
if (!transferredAccount && transaction.transfer_id) {
return removeTransfer(transaction);
}
if (transferredAccount && transaction.transfer_id) {
return updateTransfer(transaction, transferredAccount);
}
}
/***/ }),
/***/ "./packages/loot-core/src/server/api-models.js":
/*!*****************************************************!*\
!*** ./packages/loot-core/src/server/api-models.js ***!
\*****************************************************/
/*! exports provided: transactionModel, accountModel, categoryModel, categoryGroupModel, payeeModel, payeeRuleModel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transactionModel", function() { return transactionModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "accountModel", function() { return accountModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "categoryModel", function() { return categoryModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "categoryGroupModel", function() { return categoryGroupModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "payeeModel", function() { return payeeModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "payeeRuleModel", function() { return payeeRuleModel; });
/* harmony import */ var _models__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./models */ "./packages/loot-core/src/server/models.js");
const _excluded = ["group_id"],
_excluded2 = ["tombstone"];
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const transactionModel = _objectSpread(_objectSpread({}, _models__WEBPACK_IMPORTED_MODULE_0__["transactionModel"]), {}, {
toExternal(transactions, idx, payees) {
return transactions; // function convert(t, payee) {
// return {
// id: t.id,
// account_id: t.acct,
// amount: t.amount,
// payee_id: payee ? payee.id : null,
// payee: payee ? payee.name : null,
// imported_payee: t.imported_description,
// category_id: t.category,
// date: t.date,
// notes: t.notes,
// imported_id: t.financial_id,
// transfer_id: t.transferred_id,
// cleared: t.cleared
// };
// }
// let splits = getAllSplitTransactions(transactions, idx);
// if (splits) {
// let payee =
// splits.parent.description && payees[splits.parent.description];
// return {
// ...convert(splits.parent, payee),
// subtransactions: splits.children.map(child => convert(child, payee))
// };
// }
// let transaction = transactions[idx];
// let payee = transaction.description && payees[transaction.description];
// return convert(transaction, payee);
},
fromExternal(transaction) {
let result = {};
if ('id' in transaction) {
result.id = transaction.id;
}
if ('account_id' in transaction) {
result.acct = transaction.account_id;
}
if ('amount' in transaction) {
result.amount = transaction.amount;
}
if ('payee_id' in transaction) {
result.description = transaction.payee_id;
}
if ('imported_payee' in transaction) {
result.imported_description = transaction.imported_payee;
}
if ('category_id' in transaction) {
result.category = transaction.category_id;
}
if ('date' in transaction) {
result.date = transaction.date;
}
if ('notes' in transaction) {
result.notes = transaction.notes;
}
if ('imported_id' in transaction) {
result.financial_id = transaction.imported_id;
}
if ('transfer_id' in transaction) {
result.transferred_id = transaction.transfer_id;
}
if ('cleared' in transaction) {
result.cleared = transaction.cleared;
}
return result;
}
});
const accountModel = _objectSpread(_objectSpread({}, _models__WEBPACK_IMPORTED_MODULE_0__["accountModel"]), {}, {
toExternal(account) {
return {
id: account.id,
name: account.name,
type: account.type,
offbudget: account.offbudget ? true : false,
closed: account.closed ? true : false
};
},
fromExternal(account) {
let result = _objectSpread({}, account);
if ('offbudget' in account) {
result.offbudget = account.offbudget ? 1 : 0;
}
if ('closed' in account) {
result.closed = account.closed ? 1 : 0;
}
return result;
}
});
const categoryModel = _objectSpread(_objectSpread({}, _models__WEBPACK_IMPORTED_MODULE_0__["categoryModel"]), {}, {
toExternal(category) {
return {
id: category.id,
name: category.name,
is_income: category.is_income ? true : false,
group_id: category.cat_group
};
},
fromExternal(category) {
let _ = category.group_id,
result = _objectWithoutProperties(category, _excluded);
if ('is_income' in category) {
result.is_income = category.is_income ? 1 : 0;
}
if ('group_id' in category) {
result.cat_group = category.group_id;
}
return result;
}
});
const categoryGroupModel = _objectSpread(_objectSpread({}, _models__WEBPACK_IMPORTED_MODULE_0__["categoryGroupModel"]), {}, {
toExternal(group) {
return {
id: group.id,
name: group.name,
is_income: group.is_income ? true : false,
categories: group.categories.map(categoryModel.toExternal)
};
},
fromExternal(group) {
let result = _objectSpread({}, group);
if ('is_income' in group) {
result.is_income = group.is_income ? 1 : 0;
}
if ('categories' in group) {
result.categories = group.categories.map(categoryModel.fromExternal);
}
return result;
}
});
const payeeModel = _objectSpread(_objectSpread({}, _models__WEBPACK_IMPORTED_MODULE_0__["payeeModel"]), {}, {
toExternal(payee) {
return {
id: payee.id,
name: payee.name,
category: payee.category,
transfer_acct: payee.transfer_acct
};
},
fromExternal(payee) {
// No translation is needed
return payee;
}
});
const payeeRuleModel = _objectSpread(_objectSpread({}, _models__WEBPACK_IMPORTED_MODULE_0__["payeeRuleModel"]), {}, {
toExternal(rule) {
let tombstone = rule.tombstone,
result = _objectWithoutProperties(rule, _excluded2);
return result;
},
fromExternal(rule) {
return rule;
}
});
/***/ }),
/***/ "./packages/loot-core/src/server/api.js":
/*!**********************************************!*\
!*** ./packages/loot-core/src/server/api.js ***!
\**********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _accounts_sync__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./accounts/sync */ "./packages/loot-core/src/server/accounts/sync.js");
/* harmony import */ var _api_models__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./api-models */ "./packages/loot-core/src/server/api-models.js");
/* harmony import */ var _shared_transactions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../shared/transactions */ "./packages/loot-core/src/shared/transactions.js");
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _sheet__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sheet */ "./packages/loot-core/src/server/sheet.js");
/* harmony import */ var _prefs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./prefs */ "./packages/loot-core/src/server/prefs.js");
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _update__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./update */ "./packages/loot-core/src/server/update.js");
/* harmony import */ var _cloud_storage__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./cloud-storage */ "./packages/loot-core/src/server/cloud-storage.js");
/* harmony import */ var _sync__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./sync */ "./packages/loot-core/src/server/sync/index.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../shared/util */ "./packages/loot-core/src/shared/util.js");
/* harmony import */ var _timestamp__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./timestamp */ "./packages/loot-core/src/server/timestamp.js");
/* harmony import */ var _mutators__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./mutators */ "./packages/loot-core/src/server/mutators.js");
/* harmony import */ var _aql_schema_run_query__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./aql/schema/run-query */ "./packages/loot-core/src/server/aql/schema/run-query.js");
/* harmony import */ var _shared_query__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../shared/query */ "./packages/loot-core/src/shared/query.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const _require = __webpack_require__(/*! ./spreadsheet/util */ "./packages/loot-core/src/server/spreadsheet/util.js"),
resolveName = _require.resolveName;
const connection = __webpack_require__(/*! ../platform/server/connection */ "./packages/loot-core/src/platform/server/connection/index.api.js");
let IMPORT_MODE = false; // This is duplicate from main.js...
function APIError(msg, meta) {
return {
type: 'APIError',
message: msg,
meta
};
} // The API is different in two ways: we never want undo enabled, and
// we also need to notify the UI manually if stuff has changed (if
// they are connecting to an already running instance, the UI should
// update). The wrapper handles that.
function withMutation(handler) {
return args => {
return Object(_mutators__WEBPACK_IMPORTED_MODULE_12__["runMutator"])(async () => {
let latestTimestamp = Object(_timestamp__WEBPACK_IMPORTED_MODULE_11__["getClock"])().timestamp.toString();
let result = await handler(args);
let rows = await _db__WEBPACK_IMPORTED_MODULE_3__["all"]('SELECT DISTINCT dataset FROM messages_crdt WHERE timestamp > ?', [latestTimestamp]); // Only send the sync event if anybody else is connected
if (connection.getNumClients() > 1) {
connection.send('sync-event', {
type: 'success',
tables: rows.map(row => row.dataset)
});
}
return result;
}, {
undoDisabled: true
});
};
}
let handlers = {};
async function validateMonth(month) {
if (!month.match(/^\d{4}-\d{2}$/)) {
throw APIError('Invalid month format, use YYYY-MM: ' + month);
}
if (!IMPORT_MODE) {
let _await$handlers$getB = await handlers['get-budget-bounds'](),
start = _await$handlers$getB.start,
end = _await$handlers$getB.end;
let range = _shared_months__WEBPACK_IMPORTED_MODULE_6__["range"](start, end);
if (!range.includes(month)) {
throw APIError('No budget exists for month: ' + month);
}
}
}
async function validateExpenseCategory(debug, id) {
if (id == null) {
throw APIError(`${debug}: category id is required`);
}
let row = await _db__WEBPACK_IMPORTED_MODULE_3__["first"]('SELECT is_income FROM categories WHERE id = ?', [id]);
if (!row) {
throw APIError(`${debug}: category "${id}" does not exist`);
}
if (row.is_income !== 0) {
throw APIError(`${debug}: category "${id}" is not an expense category`);
}
}
let batchPromise = null;
handlers['api/batch-budget-start'] = async function () {
if (batchPromise) {
throw APIError('Cannot start a batch process: batch already started');
} // If we are importing, all we need to do is start a raw database
// transaction. Updating spreadsheet cells doesn't go through the
// syncing layer in that case.
if (IMPORT_MODE) {
_db__WEBPACK_IMPORTED_MODULE_3__["asyncTransaction"](() => {
return new Promise((resolve, reject) => {
batchPromise = {
resolve,
reject
};
});
});
} else {
Object(_sync__WEBPACK_IMPORTED_MODULE_9__["batchMessages"])(() => {
return new Promise((resolve, reject) => {
batchPromise = {
resolve,
reject
};
});
});
}
};
handlers['api/batch-budget-end'] = async function () {
if (!batchPromise) {
throw APIError('Cannot end a batch process: no batch started');
}
batchPromise.resolve();
batchPromise = null;
};
handlers['api/load-budget'] = async function ({
id
}) {
let _ref = _prefs__WEBPACK_IMPORTED_MODULE_5__["getPrefs"]() || {},
currentId = _ref.id;
if (currentId !== id) {
connection.send('start-load');
let _await$handlers$load = await handlers['load-budget']({
id
}),
error = _await$handlers$load.error;
if (!error) {
connection.send('finish-load');
} else {
connection.send('show-budgets');
if (error === 'out-of-sync-migrations' || error === 'out-of-sync-data') {
throw new Error('This budget cannot be loaded with this version of the app.');
} else if (error === 'budget-not-found') {
throw new Error('Budget "' + id + '" not found. Check the id of your budget in the "Advanced" section of the settings page.');
} else {
throw new Error('We had an unknown problem opening "' + id + '".');
}
}
}
};
handlers['api/start-import'] = async function ({
budgetName
}) {
// Notify UI to close budget
await handlers['close-budget'](); // Create the budget
await handlers['create-budget']({
budgetName,
avoidUpload: true
}); // Clear out the default expense categories
await _db__WEBPACK_IMPORTED_MODULE_3__["runQuery"]('DELETE FROM categories WHERE is_income = 0');
await _db__WEBPACK_IMPORTED_MODULE_3__["runQuery"]('DELETE FROM category_groups WHERE is_income = 0'); // Turn syncing off
Object(_sync__WEBPACK_IMPORTED_MODULE_9__["setSyncingMode"])('import');
connection.send('start-import');
IMPORT_MODE = true;
};
handlers['api/finish-import'] = async function () {
_sheet__WEBPACK_IMPORTED_MODULE_4__["get"]().markCacheDirty(); // We always need to fully reload the app. Importing doesn't touch
// the spreadsheet, but we can't just recreate the spreadsheet
// either; there is other internal state that isn't created
let _prefs$getPrefs = _prefs__WEBPACK_IMPORTED_MODULE_5__["getPrefs"](),
id = _prefs$getPrefs.id;
await handlers['close-budget']();
await handlers['load-budget']({
id
});
await handlers['get-budget-bounds']();
await _sheet__WEBPACK_IMPORTED_MODULE_4__["waitOnSpreadsheet"]();
await _cloud_storage__WEBPACK_IMPORTED_MODULE_8__["upload"]().catch(err => {});
connection.send('finish-import');
IMPORT_MODE = false;
};
handlers['api/abort-import'] = async function () {
if (IMPORT_MODE) {
let _prefs$getPrefs2 = _prefs__WEBPACK_IMPORTED_MODULE_5__["getPrefs"](),
id = _prefs$getPrefs2.id;
await handlers['close-budget']();
await handlers['delete-budget']({
id
});
connection.send('show-budgets');
}
IMPORT_MODE = false;
};
handlers['api/query'] = async function ({
query
}) {
return Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_13__["runQuery"])(query);
};
handlers['api/budget-months'] = async function () {
let _await$handlers$getB2 = await handlers['get-budget-bounds'](),
start = _await$handlers$getB2.start,
end = _await$handlers$getB2.end;
return _shared_months__WEBPACK_IMPORTED_MODULE_6__["range"](start, end);
};
handlers['api/budget-month'] = async function ({
month
}) {
await validateMonth(month);
let groups = await _db__WEBPACK_IMPORTED_MODULE_3__["getCategoriesGrouped"]();
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_6__["sheetForMonth"](month);
function value(name) {
let v = _sheet__WEBPACK_IMPORTED_MODULE_4__["get"]().getCellValue(sheetName, name);
return v === '' ? 0 : v;
} // This is duplicated from main.js because the return format is
// different (for now)
return {
month,
incomeAvailable: value('available-funds'),
lastMonthOverspent: value('last-month-overspent'),
forNextMonth: value('buffered'),
totalBudgeted: value('total-budgeted'),
toBudget: value('to-budget'),
fromLastMonth: value('from-last-month'),
totalIncome: value('total-income'),
totalSpent: value('total-spent'),
totalBalance: value('total-leftover'),
categoryGroups: groups.map(group => {
if (group.is_income) {
return _objectSpread(_objectSpread({}, _api_models__WEBPACK_IMPORTED_MODULE_1__["categoryGroupModel"].toExternal(group)), {}, {
received: value('total-income'),
categories: group.categories.map(cat => _objectSpread(_objectSpread({}, _api_models__WEBPACK_IMPORTED_MODULE_1__["categoryModel"].toExternal(cat)), {}, {
received: value(`sum-amount-${cat.id}`)
}))
});
}
return _objectSpread(_objectSpread({}, _api_models__WEBPACK_IMPORTED_MODULE_1__["categoryGroupModel"].toExternal(group)), {}, {
budgeted: value(`group-budget-${group.id}`),
spent: value(`group-sum-amount-${group.id}`),
balance: value(`group-leftover-${group.id}`),
categories: group.categories.map(cat => _objectSpread(_objectSpread({}, _api_models__WEBPACK_IMPORTED_MODULE_1__["categoryModel"].toExternal(cat)), {}, {
budgeted: value(`budget-${cat.id}`),
spent: value(`sum-amount-${cat.id}`),
balance: value(`leftover-${cat.id}`),
carryover: value(`carryover-${cat.id}`)
}))
});
})
};
};
handlers['api/budget-set-amount'] = withMutation(async function ({
month,
categoryId,
amount
}) {
return handlers['budget/budget-amount']({
month,
category: categoryId,
amount
});
});
handlers['api/budget-set-carryover'] = withMutation(async function ({
month,
categoryId,
flag
}) {
await validateMonth(month);
await validateExpenseCategory('budget-set-carryover', categoryId);
return handlers['budget/set-carryover']({
startMonth: month,
category: categoryId,
flag
});
});
handlers['api/transactions-export'] = async function ({
transactions,
categoryGroups,
payees
}) {
return handlers['transactions-export']({
transactions,
categoryGroups,
payees
});
};
handlers['api/transactions-import'] = withMutation(async function ({
accountId,
transactions
}) {
return handlers['transactions-import']({
accountId,
transactions
});
});
handlers['api/transactions-add'] = withMutation(async function ({
accountId,
transactions
}) {
await Object(_accounts_sync__WEBPACK_IMPORTED_MODULE_0__["addTransactions"])(accountId, transactions, {
runTransfers: false
});
return 'ok';
});
handlers['api/transactions-get'] = async function ({
accountId,
startDate,
endDate
}) {
let _await$aqlQuery = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_13__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_14__["default"])('transactions').filter({
$and: [accountId && {
account: accountId
}, startDate && {
date: {
$gte: startDate
}
}, endDate && {
date: {
$lte: endDate
}
}].filter(Boolean)
}).select('*').options({
splits: 'grouped'
})),
data = _await$aqlQuery.data;
return data;
};
handlers['api/transactions-filter'] = async function ({
text,
accountId
}) {
throw new Error('`filterTransactions` is deprecated, use `runQuery` instead');
};
handlers['api/transaction-update'] = withMutation(async function ({
id,
fields
}) {
let _await$aqlQuery2 = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_13__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_14__["default"])('transactions').filter({
id
}).select('*').options({
splits: 'grouped'
})),
data = _await$aqlQuery2.data;
let transactions = Object(_shared_transactions__WEBPACK_IMPORTED_MODULE_2__["ungroupTransactions"])(data);
if (transactions.length === 0) {
return [];
}
let _updateTransaction = Object(_shared_transactions__WEBPACK_IMPORTED_MODULE_2__["updateTransaction"])(transactions, fields),
diff = _updateTransaction.diff;
return handlers['transactions-batch-update'](diff);
});
handlers['api/transaction-delete'] = withMutation(async function ({
id
}) {
let _await$aqlQuery3 = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_13__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_14__["default"])('transactions').filter({
id
}).select('*').options({
splits: 'grouped'
})),
data = _await$aqlQuery3.data;
let transactions = Object(_shared_transactions__WEBPACK_IMPORTED_MODULE_2__["ungroupTransactions"])(data);
if (transactions.length === 0) {
return [];
}
let _deleteTransaction = Object(_shared_transactions__WEBPACK_IMPORTED_MODULE_2__["deleteTransaction"])(transactions, id),
diff = _deleteTransaction.diff;
return handlers['transactions-batch-update'](diff);
});
handlers['api/accounts-get'] = async function () {
let accounts = await _db__WEBPACK_IMPORTED_MODULE_3__["getAccounts"]();
return accounts.map(account => _api_models__WEBPACK_IMPORTED_MODULE_1__["accountModel"].toExternal(account));
};
handlers['api/account-create'] = withMutation(async function ({
account,
initialBalance = null
}) {
return handlers['account-create']({
name: account.name,
type: account.type,
offBudget: account.offbudget,
closed: account.closed,
// Current the API expects an amount but it really should expect
// an integer
balance: initialBalance != null ? Object(_shared_util__WEBPACK_IMPORTED_MODULE_10__["integerToAmount"])(initialBalance) : null
});
});
handlers['api/account-update'] = withMutation(async function ({
id,
fields
}) {
return _db__WEBPACK_IMPORTED_MODULE_3__["updateAccount"](_objectSpread({
id
}, _api_models__WEBPACK_IMPORTED_MODULE_1__["accountModel"].fromExternal(fields)));
});
handlers['api/account-close'] = withMutation(async function ({
id,
transferAccountId,
transferCategoryId
}) {
return handlers['account-close']({
id,
transferAccountId,
categoryId: transferCategoryId
});
});
handlers['api/account-reopen'] = withMutation(async function ({
id
}) {
return handlers['account-reopen']({
id
});
});
handlers['api/account-delete'] = withMutation(async function ({
id
}) {
return handlers['account-close']({
id,
forced: true
});
});
handlers['api/categories-get'] = async function ({
grouped
} = {}) {
let result = await handlers['get-categories']();
return grouped ? result.grouped.map(_api_models__WEBPACK_IMPORTED_MODULE_1__["categoryGroupModel"].toExternal) : result.list.map(_api_models__WEBPACK_IMPORTED_MODULE_1__["categoryModel"].toExternal);
};
handlers['api/category-group-create'] = withMutation(async function ({
group
}) {
return handlers['category-group-create']({
name: group.name
});
});
handlers['api/category-group-update'] = withMutation(async function ({
id,
fields
}) {
return handlers['category-group-update'](_objectSpread({
id
}, _api_models__WEBPACK_IMPORTED_MODULE_1__["categoryGroupModel"].fromExternal(fields)));
});
handlers['api/category-group-delete'] = withMutation(async function ({
id,
transferCategoryId
}) {
return handlers['category-group-delete']({
id,
transferId: transferCategoryId
});
});
handlers['api/category-create'] = withMutation(async function ({
category
}) {
return handlers['category-create']({
name: category.name,
groupId: category.group_id,
isIncome: category.is_income
});
});
handlers['api/category-update'] = withMutation(async function ({
id,
fields
}) {
return handlers['category-update'](_objectSpread({
id
}, _api_models__WEBPACK_IMPORTED_MODULE_1__["categoryModel"].fromExternal(fields)));
});
handlers['api/category-delete'] = withMutation(async function ({
id,
transferCategoryId
}) {
return handlers['category-delete']({
id,
transferId: transferCategoryId
});
});
handlers['api/payees-get'] = async function () {
let payees = await handlers['payees-get']();
return payees.map(_api_models__WEBPACK_IMPORTED_MODULE_1__["payeeModel"].toExternal);
};
handlers['api/payee-create'] = withMutation(async function ({
payee
}) {
return handlers['payee-create']({
name: payee.name
});
});
handlers['api/payee-update'] = withMutation(async function ({
id,
fields
}) {
return handlers['payees-batch-change']({
updated: [_objectSpread({
id
}, _api_models__WEBPACK_IMPORTED_MODULE_1__["payeeModel"].fromExternal(fields))]
});
});
handlers['api/payee-delete'] = withMutation(async function ({
id
}) {
return handlers['payees-batch-change']({
deleted: [{
id
}]
});
});
handlers['api/payee-rules-get'] = async function ({
payeeId
}) {
let rules = await handlers['payees-get-rules']({
id: payeeId
});
return rules.map(_api_models__WEBPACK_IMPORTED_MODULE_1__["payeeRuleModel"].toExternal);
};
handlers['api/payee-rule-create'] = withMutation(async function ({
payee_id,
rule
}) {
return handlers['payees-add-rule']({
payee_id,
type: rule.type,
value: rule.value || null
});
});
handlers['api/payee-rule-update'] = withMutation(async function ({
id,
fields
}) {
return handlers['payees-update-rule'](_objectSpread({
id
}, _api_models__WEBPACK_IMPORTED_MODULE_1__["payeeRuleModel"].fromExternal(fields)));
});
handlers['api/payee-rule-delete'] = withMutation(async function ({
id
}) {
return handlers['payees-delete-rule']({
id
});
});
/* harmony default export */ __webpack_exports__["default"] = (function (serverHandlers) {
handlers = Object.assign({}, serverHandlers, handlers);
return handlers;
});
/***/ }),
/***/ "./packages/loot-core/src/server/app.js":
/*!**********************************************!*\
!*** ./packages/loot-core/src/server/app.js ***!
\**********************************************/
/*! exports provided: createApp */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createApp", function() { return createApp; });
/* harmony import */ var mitt__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! mitt */ "./packages/loot-core/node_modules/mitt/dist/mitt.es.js");
/* harmony import */ var _platform_exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../platform/exceptions */ "./packages/loot-core/src/platform/exceptions/index.electron.js");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
// This is a simple helper abstraction for defining methods exposed to
// the client. It doesn't do much, but checks for naming conflicts and
// makes it cleaner to combine methods. We call a group of related
// methods an "app".
class App {
constructor() {
this.handlers = {};
this.services = [];
this.events = Object(mitt__WEBPACK_IMPORTED_MODULE_0__["default"])();
this.unlistenServices = [];
}
method(name, func) {
if (this.handlers[name] != null) {
throw new Error('Conflicting method name, names must be globally unique: ' + name);
}
this.handlers[name] = func;
}
service(func) {
this.services.push(func);
}
combine(...apps) {
for (let app of apps) {
Object.keys(app.handlers).forEach(name => {
this.method(name, app.handlers[name]);
});
app.services.forEach(service => {
this.service(service);
});
for (let _ref of app.events.all.entries()) {
var _ref2 = _slicedToArray(_ref, 2);
let name = _ref2[0];
let listeners = _ref2[1];
for (let listener of listeners) {
this.events.on(name, listener);
}
}
}
}
startServices() {
if (this.unlistenServices.length > 0) {
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_1__["captureException"])(new Error('App: startServices called while services are already running'));
}
this.unlistenServices = this.services.map(service => service());
}
stopServices() {
this.unlistenServices.forEach(unlisten => {
if (unlisten) {
unlisten();
}
});
this.unlistenServices = [];
}
}
function createApp() {
return new App();
}
/***/ }),
/***/ "./packages/loot-core/src/server/aql/compiler.js":
/*!*******************************************************!*\
!*** ./packages/loot-core/src/server/aql/compiler.js ***!
\*******************************************************/
/*! exports provided: addTombstone, quoteAlias, isAggregateQuery, compileQuery, defaultConstructQuery, generateSQLWithState, generateSQL */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addTombstone", function() { return addTombstone; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "quoteAlias", function() { return quoteAlias; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isAggregateQuery", function() { return isAggregateQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "compileQuery", function() { return compileQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultConstructQuery", function() { return defaultConstructQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateSQLWithState", function() { return generateSQLWithState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateSQL", function() { return generateSQL; });
const _excluded = ["$transform"],
_excluded2 = ["$dir"];
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
let _uid = 0;
function resetUid() {
_uid = 0;
}
function uid(tableName) {
_uid++;
return tableName + _uid;
}
class CompileError extends Error {}
function nativeDateToInt(date) {
let pad = x => (x < 10 ? '0' : '') + x;
return date.getFullYear() + pad(date.getMonth() + 1) + pad(date.getDate());
}
function dateToInt(date) {
return parseInt(date.replace(/-/g, ''));
}
function addTombstone(schema, tableName, tableId, whereStr) {
let hasTombstone = schema[tableName].tombstone != null;
return hasTombstone ? `${whereStr} AND ${tableId}.tombstone = 0` : whereStr;
}
function popPath(path) {
let parts = path.split('.');
return {
path: parts.slice(0, -1).join('.'),
field: parts[parts.length - 1]
};
}
function isKeyword(str) {
return str === 'group';
}
function quoteAlias(alias) {
return alias.indexOf('.') === -1 && !isKeyword(alias) ? alias : `"${alias}"`;
}
function typed(value, type, {
literal = false
} = {}) {
return {
value,
type,
literal
};
}
function getFieldDescription(schema, tableName, field) {
if (schema[tableName] == null) {
throw new CompileError(`Table "${tableName}" does not exist in the schema`);
}
let fieldDesc = schema[tableName][field];
if (fieldDesc == null) {
throw new CompileError(`Field "${field}" does not exist in table "${tableName}"`);
}
return fieldDesc;
}
function makePath(state, path) {
let schema = state.schema,
paths = state.paths;
let parts = path.split('.');
if (parts.length < 2) {
throw new CompileError('Invalid path: ' + path);
}
let initialTable = parts[0];
let tableName = parts.slice(1).reduce((tableName, field) => {
let table = schema[tableName];
if (table == null) {
throw new CompileError(`Path error: ${tableName} table does not exist`);
}
if (!table[field] || table[field].ref == null) {
throw new CompileError(`Field not joinable on table ${tableName}: "${field}"`);
}
return table[field].ref;
}, initialTable);
let joinTable;
let parentParts = parts.slice(0, -1);
if (parentParts.length === 1) {
joinTable = parentParts[0];
} else {
let parentPath = parentParts.join('.');
let parentDesc = paths.get(parentPath);
if (!parentDesc) {
throw new CompileError('Path does not exist: ' + parentPath);
}
joinTable = parentDesc.tableId;
}
return {
tableName: tableName,
tableId: uid(tableName),
joinField: parts[parts.length - 1],
joinTable
};
}
function resolvePath(state, path) {
let paths = path.split('.');
let tableId;
paths = paths.reduce((acc, name) => {
let fullName = acc.context + '.' + name;
return {
context: fullName,
path: [...acc.path, fullName]
};
}, {
context: state.implicitTableName,
path: []
}).path;
paths.forEach(path => {
if (!state.paths.get(path)) {
state.paths.set(path, makePath(state, path));
}
});
let pathInfo = state.paths.get(paths[paths.length - 1]);
return pathInfo;
}
function transformField(state, name) {
if (typeof name !== 'string') {
throw new CompileError('Invalid field name, must be a string');
}
let _popPath = popPath(name),
path = _popPath.path,
field = _popPath.field;
let pathInfo;
if (path === '') {
pathInfo = {
tableName: state.implicitTableName,
tableId: state.implicitTableId
};
} else {
pathInfo = resolvePath(state, path);
}
let fieldDesc = getFieldDescription(state.schema, pathInfo.tableName, field); // If this is a field that references an item in another table, that
// item could have been deleted. If that's the case, we want to
// return `null` instead of an id pointing to a deleted item. This
// converts an id reference into a path that pulls the id through a
// table join which will filter out dead items, resulting in a
// `null` id if the item is deleted
if (state.validateRefs && fieldDesc.ref && fieldDesc.type === 'id' && field !== 'id') {
let refPath = state.implicitTableName + '.' + name;
let refPathInfo = state.paths.get(refPath);
if (!refPathInfo) {
refPathInfo = makePath(state, refPath);
refPathInfo.noMapping = true;
state.paths.set(refPath, refPathInfo);
}
field = 'id';
pathInfo = refPathInfo;
}
let fieldStr = pathInfo.tableId + '.' + field;
return typed(fieldStr, fieldDesc.type);
}
function parseDate(str) {
let m = str.match(/^(\d{4}-\d{2}-\d{2})$/);
if (m) {
return typed(dateToInt(m[1]), 'date', {
literal: true
});
}
return null;
}
function parseMonth(str) {
let m = str.match(/^(\d{4}-\d{2})$/);
if (m) {
return typed(dateToInt(m[1]), 'date', {
literal: true
});
}
return null;
}
function parseYear(str) {
let m = str.match(/^(\d{4})$/);
if (m) {
return typed(dateToInt(m[1]), 'date', {
literal: true
});
}
return null;
}
function badDateFormat(str, type) {
throw new CompileError(`Bad ${type} format: ${str}`);
}
function inferParam(param, type) {
let existingType = param.paramType;
if (existingType) {
let casts = {
date: ['string'],
'date-month': ['date'],
'date-year': ['date', 'date-month'],
id: ['string'],
float: ['integer']
};
if (existingType !== type && (!casts[type] || !casts[type].includes(existingType))) {
throw new Error(`Parameter "${name}" can't convert to ${type} (already inferred as ${existingType})`);
}
} else {
param.paramType = type;
}
}
function castInput(state, expr, type) {
if (expr.type === type) {
return expr;
} else if (expr.type === 'param') {
inferParam(expr, type);
return typed(expr.value, type);
} else if (expr.type === 'null') {
if (!expr.literal) {
throw new CompileError("A non-literal null doesn't make sense");
}
if (type === 'boolean') {
return typed(0, 'boolean', {
literal: true
});
}
return expr;
} // These are all things that can be safely casted automatically
if (type === 'date') {
if (expr.type === 'string') {
if (expr.literal) {
return parseDate(expr.value) || badDateFormat(expr.value, 'date');
} else {
throw new CompileError('Casting string fields to dates is not supported');
}
}
throw new CompileError(`Can't cast ${expr.type} to date`);
} else if (type === 'date-month') {
let expr2;
if (expr.type === 'date') {
expr2 = expr;
} else if (expr.type === 'string' || expr.type === 'any') {
expr2 = parseMonth(expr.value) || parseDate(expr.value) || badDateFormat(expr.value, 'date-month');
} else {
throw new CompileError(`Can't cast ${expr.type} to date-month`);
}
if (expr2.literal) {
return typed(dateToInt(expr2.value.toString().slice(0, 6)), 'date-month', {
literal: true
});
} else {
return typed(`CAST(SUBSTR(${expr2.value}, 1, 6) AS integer)`, 'date-month');
}
} else if (type === 'date-year') {
let expr2;
if (expr.type === 'date' || expr.type === 'date-month') {
expr2 = expr;
} else if (expr.type === 'string') {
expr2 = parseYear(expr.value) || parseMonth(expr.value) || parseDate(expr.value) || badDateFormat(expr.value, 'date-year');
} else {
throw new CompileError(`Can't cast ${expr.type} to date-year`);
}
if (expr2.literal) {
return typed(dateToInt(expr2.value.toString().slice(0, 4)), 'date-year', {
literal: true
});
} else {
return typed(`CAST(SUBSTR(${expr2.value}, 1, 4) AS integer)`, 'date-year');
}
} else if (type === 'id') {
if (expr.type === 'string') {
return typed(expr.value, 'id', {
literal: expr.literal
});
}
} else if (type === 'float') {
if (expr.type === 'integer') {
return typed(expr.value, 'float', {
literal: expr.literal
});
}
}
if (expr.type === 'any') {
return typed(expr.value, type, {
literal: expr.literal
});
}
throw new CompileError(`Can't convert ${expr.type} to ${type}`);
} // TODO: remove state from these functions
function val(state, expr, type) {
let castedExpr = expr; // Cast the type if necessary
if (type) {
castedExpr = castInput(state, expr, type);
}
if (castedExpr.literal) {
if (castedExpr.type === 'id') {
return `'${castedExpr.value}'`;
} else if (castedExpr.type === 'string') {
// Escape quotes
let value = castedExpr.value.replace(/'/g, "''");
return `'${value}'`;
}
}
return castedExpr.value;
}
function valArray(state, arr, types) {
return arr.map((value, idx) => val(state, value, types ? types[idx] : null));
}
function validateArgLength(arr, min, max) {
if (max == null) {
max = min;
}
if (min != null && arr.length < min) {
throw new CompileError('Too few arguments');
}
if (max != null && arr.length > max) {
throw new CompileError('Too many arguments');
}
} //// Nice errors
function saveStack(type, func) {
return (state, ...args) => {
if (state == null || state.compileStack == null) {
throw new CompileError('This function cannot track error data. ' + 'It needs to accept the compiler state as the first argument.');
}
state.compileStack.push({
type,
args
});
let ret = func(state, ...args);
state.compileStack.pop();
return ret;
};
}
function prettyValue(value) {
if (typeof value === 'string') {
return value;
} else if (value === undefined) {
return 'undefined';
}
let str = JSON.stringify(value);
if (str.length > 70) {
let expanded = JSON.stringify(value, null, 2);
return expanded.split('\n').join('\n ');
}
return str;
}
function getCompileError(error, stack) {
if (stack.length === 0) {
return error;
}
let stackStr = stack.slice(1).reverse().map(entry => {
switch (entry.type) {
case 'expr':
case 'function':
return prettyValue(entry.args[0]);
case 'op':
{
let _entry$args = _slicedToArray(entry.args, 2),
fieldRef = _entry$args[0],
opData = _entry$args[1];
return prettyValue({
[fieldRef]: opData
});
}
case 'value':
return prettyValue(entry.value);
default:
return '';
}
}).map(str => '\n ' + str).join('');
const rootMethod = stack[0].type;
const methodArgs = stack[0].args[0];
stackStr += `\n ${rootMethod}(${prettyValue(methodArgs.length === 1 ? methodArgs[0] : methodArgs)})`; // In production, hide internal stack traces
if (false) {}
error.message = `${error.message}\n\nExpression stack:` + stackStr;
return error;
} //// Compiler
function compileLiteral(value) {
if (value === undefined) {
throw new CompileError('`undefined` is not a valid query value');
} else if (value === null) {
return typed('NULL', 'null', {
literal: true
});
} else if (value instanceof Date) {
return typed(nativeDateToInt(value), 'date', {
literal: true
});
} else if (typeof value === 'string') {
// Allow user to escape $, and quote the string to make it a
// string literal in the output
value = value.replace(/\\\$/g, '$');
return typed(value, 'string', {
literal: true
});
} else if (typeof value === 'boolean') {
return typed(value ? 1 : 0, 'boolean', {
literal: true
});
} else if (typeof value === 'number') {
return typed(value, (value | 0) === value ? 'integer' : 'float', {
literal: true
});
} else if (Array.isArray(value)) {
return typed(value, 'array', {
literal: true
});
} else {
throw new CompileError('Unsupported type of expression: ' + JSON.stringify(value));
}
}
const compileExpr = saveStack('expr', (state, expr) => {
if (typeof expr === 'string') {
// Field reference
if (expr[0] === '$') {
let fieldRef = expr === '$' ? state.implicitField : expr.slice(1);
if (fieldRef == null || fieldRef === '') {
throw new CompileError('Invalid field reference: ' + expr);
}
return transformField(state, fieldRef);
} // Named parameter
if (expr[0] === ':') {
let param = {
value: '?',
type: 'param',
paramName: expr.slice(1)
};
state.namedParameters.push(param);
return param;
}
}
if (expr !== null) {
if (Array.isArray(expr)) {
return compileLiteral(expr);
} else if (typeof expr === 'object' && Object.keys(expr).find(k => k[0] === '$')) {
// It's a function call
return compileFunction(state, expr);
}
}
return compileLiteral(expr);
});
function assertType(name, data, acceptedTypes) {
if (acceptedTypes.indexOf(data.type) === -1) {
throw new CompileError(`Invalid type of expression to ${name}, must be one of ${JSON.stringify(acceptedTypes)}: ${JSON.stringify(data.value)}`);
}
}
function assertArgLength(name, args, len) {
if (args.length !== len) {
throw new CompileError(`Invalid number of args to ${name}: expected ${len} but received ${args.length}`)();
}
}
const compileFunction = saveStack('function', (state, func) => {
let _Object$keys = Object.keys(func),
_Object$keys2 = _slicedToArray(_Object$keys, 1),
name = _Object$keys2[0];
let argExprs = func[name];
if (!Array.isArray(argExprs)) {
argExprs = [argExprs];
}
if (name[0] !== '$') {
throw new CompileError(`Unknown property "${name}". Did you mean to call a function? Try prefixing it with $`);
}
let args = argExprs; // `$condition` is a special-case where it will be evaluated later
if (name !== '$condition') {
args = argExprs.map(arg => compileExpr(state, arg));
}
switch (name) {
// aggregate functions
case '$sum':
{
validateArgLength(args, 1);
let _valArray = valArray(state, args, ['float']),
_valArray2 = _slicedToArray(_valArray, 1),
arg1 = _valArray2[0];
return typed(`SUM(${arg1})`, args[0].type);
}
case '$sumOver':
{
let _valArray3 = valArray(state, args, ['float']),
_valArray4 = _slicedToArray(_valArray3, 1),
arg1 = _valArray4[0];
let order = state.orders ? 'ORDER BY ' + compileOrderBy(state, state.orders) : '';
return typed(`(SUM(${arg1}) OVER (${order} ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING))`, args[0].type);
}
case '$count':
{
validateArgLength(args, 1);
let _valArray5 = valArray(state, args),
_valArray6 = _slicedToArray(_valArray5, 1),
arg1 = _valArray6[0];
return typed(`COUNT(${arg1})`, 'integer');
}
// string functions
case '$substr':
{
validateArgLength(args, 2, 3);
let _valArray7 = valArray(state, args, ['string', 'integer', 'integer']),
_valArray8 = _slicedToArray(_valArray7, 3),
arg1 = _valArray8[0],
arg2 = _valArray8[1],
arg3 = _valArray8[2];
return typed(`SUBSTR(${arg1}, ${arg2}, ${arg3})`, 'string');
}
case '$lower':
{
validateArgLength(args, 1);
let _valArray9 = valArray(state, args, ['string']),
_valArray10 = _slicedToArray(_valArray9, 1),
arg1 = _valArray10[0];
return typed(`LOWER(${arg1})`, 'string');
}
// integer/float functions
case '$neg':
{
validateArgLength(args, 1);
let _valArray11 = valArray(state, args, ['float']),
_valArray12 = _slicedToArray(_valArray11, 1),
arg1 = _valArray12[0];
return typed(`(-${val(state, args[0])})`, args[0].type);
}
case '$abs':
{
validateArgLength(args, 1);
let _valArray13 = valArray(state, args, ['float']),
_valArray14 = _slicedToArray(_valArray13, 1),
arg1 = _valArray14[0];
return typed(`ABS(${val(state, args[0])})`, args[0].type);
}
case '$idiv':
{
validateArgLength(args, 2);
let _valArray15 = valArray(state, args, ['integer', 'integer']),
_valArray16 = _slicedToArray(_valArray15, 2),
arg1 = _valArray16[0],
arg2 = _valArray16[1];
return typed(`(${val(state, args[0])} / ${val(state, args[1])})`, args[0].type);
}
// date functions
case '$month':
{
validateArgLength(args, 1);
return castInput(state, args[0], 'date-month');
}
case '$year':
{
validateArgLength(args, 1);
return castInput(state, args[0], 'date-year');
}
// various functions
case '$condition':
validateArgLength(args, 1);
let conds = compileConditions(state, args[0]);
return typed(conds.join(' AND '), 'boolean');
case '$nocase':
validateArgLength(args, 1);
let _valArray17 = valArray(state, args, ['string']),
_valArray18 = _slicedToArray(_valArray17, 1),
arg1 = _valArray18[0];
return typed(`${arg1} COLLATE NOCASE`, args[0].type);
case '$literal':
{
validateArgLength(args, 1);
if (!args[0].literal) {
throw new CompileError('Literal not passed to $literal');
}
return args[0];
}
default:
throw new CompileError(`Unknown function: ${name}`);
}
});
const compileOp = saveStack('op', (state, fieldRef, opData) => {
let $transform = opData.$transform,
opExpr = _objectWithoutProperties(opData, _excluded);
let _Object$keys3 = Object.keys(opExpr),
_Object$keys4 = _slicedToArray(_Object$keys3, 1),
op = _Object$keys4[0];
let rhs = compileExpr(state, opData[op]);
let lhs;
if ($transform) {
lhs = compileFunction(_objectSpread(_objectSpread({}, state), {}, {
implicitField: fieldRef
}), typeof $transform === 'string' ? {
[$transform]: '$'
} : $transform);
} else {
lhs = compileExpr(state, '$' + fieldRef);
}
switch (op) {
case '$gte':
{
let _valArray19 = valArray(state, [lhs, rhs], [null, lhs.type]),
_valArray20 = _slicedToArray(_valArray19, 2),
left = _valArray20[0],
right = _valArray20[1];
return `${left} >= ${right}`;
}
case '$lte':
{
let _valArray21 = valArray(state, [lhs, rhs], [null, lhs.type]),
_valArray22 = _slicedToArray(_valArray21, 2),
left = _valArray22[0],
right = _valArray22[1];
return `${left} <= ${right}`;
}
case '$gt':
{
let _valArray23 = valArray(state, [lhs, rhs], [null, lhs.type]),
_valArray24 = _slicedToArray(_valArray23, 2),
left = _valArray24[0],
right = _valArray24[1];
return `${left} > ${right}`;
}
case '$lt':
{
let _valArray25 = valArray(state, [lhs, rhs], [null, lhs.type]),
_valArray26 = _slicedToArray(_valArray25, 2),
left = _valArray26[0],
right = _valArray26[1];
return `${left} < ${right}`;
}
case '$eq':
{
if (castInput(state, rhs, lhs.type).type === 'null') {
return `${val(state, lhs)} IS NULL`;
}
let _valArray27 = valArray(state, [lhs, rhs], [null, lhs.type]),
_valArray28 = _slicedToArray(_valArray27, 2),
left = _valArray28[0],
right = _valArray28[1];
if (rhs.type === 'param') {
let orders = state.namedParameters.map(param => {
return param === rhs || param === lhs ? [param, _objectSpread({}, param)] : param;
});
state.namedParameters = [].concat.apply([], orders);
return `CASE
WHEN ${left} IS NULL THEN ${right} IS NULL
ELSE ${left} = ${right}
END`;
}
return `${left} = ${right}`;
}
case '$oneof':
{
let _valArray29 = valArray(state, [lhs, rhs], [null, 'array']),
_valArray30 = _slicedToArray(_valArray29, 2),
left = _valArray30[0],
right = _valArray30[1]; // Dedupe the ids
let ids = [...new Set(right)];
return `${left} IN (` + ids.map(id => `'${id}'`).join(',') + ')';
}
case '$like':
{
let _valArray31 = valArray(state, [lhs, rhs], ['string', 'string']),
_valArray32 = _slicedToArray(_valArray31, 2),
left = _valArray32[0],
right = _valArray32[1];
return `${left} LIKE ${right}`;
}
default:
throw new CompileError(`Unknown operator: ${op}`);
}
});
function compileConditions(state, conds) {
if (!Array.isArray(conds)) {
// Convert the object form `{foo: 1, bar:2}` into the array form
// `[{foo: 1}, {bar:2}]`
conds = Object.entries(conds).map(cond => {
return {
[cond[0]]: cond[1]
};
});
}
return conds.filter(Boolean).reduce((res, condsObj) => {
let compiled = Object.entries(condsObj).map(([field, cond]) => {
// Allow a falsy value in the lhs of $and and $or to allow for
// quick forms like `$or: amount != 0 && ...`
if (field === '$and') {
if (!cond) {
return null;
}
return compileAnd(state, cond);
} else if (field === '$or') {
if (!cond) {
return null;
}
return compileOr(state, cond);
}
if (typeof cond === 'string' || typeof cond === 'number' || typeof cond === 'boolean' || cond instanceof Date || cond == null) {
return compileOp(state, field, {
$eq: cond
});
}
if (Array.isArray(cond)) {
// An array of conditions for a field is implicitly an `and`
return cond.map(c => compileOp(state, field, c)).join(' AND ');
}
return compileOp(state, field, cond);
}).filter(Boolean);
return [...res, ...compiled];
}, []);
}
function compileOr(state, conds) {
// Same as above
if (!conds) {
return '0';
}
let res = compileConditions(state, conds);
if (res.length === 0) {
return '0';
}
return '(' + res.join('\n OR ') + ')';
}
function compileAnd(state, conds) {
// Same as above
if (!conds) {
return '1';
}
let res = compileConditions(state, conds);
if (res.length === 0) {
return '1';
}
return '(' + res.join('\n AND ') + ')';
}
const compileWhere = saveStack('filter', (state, conds) => {
return compileAnd(state, conds);
});
function compileJoins(state, tableRef, internalTableFilters) {
let joins = [];
state.paths.forEach((desc, path) => {
let _state$paths$get = state.paths.get(path),
tableName = _state$paths$get.tableName,
tableId = _state$paths$get.tableId,
joinField = _state$paths$get.joinField,
joinTable = _state$paths$get.joinTable,
noMapping = _state$paths$get.noMapping;
let on = `${tableId}.id = ${tableRef(joinTable)}.${quoteAlias(joinField)}`;
let filters = internalTableFilters(tableName);
if (filters.length > 0) {
on += ' AND ' + compileAnd(_objectSpread(_objectSpread({}, state), {}, {
implicitTableName: tableName,
implicitTableId: tableId
}), filters);
}
joins.push(`LEFT JOIN ${noMapping ? tableName : tableRef(tableName, true)} ${tableId} ON ${addTombstone(state.schema, tableName, tableId, on)}`);
if (state.dependencies.indexOf(tableName) === -1) {
state.dependencies.push(tableName);
}
});
return joins.join('\n');
}
function expandStar(state, expr) {
let path;
let pathInfo;
if (expr === '*') {
pathInfo = {
tableName: state.implicitTableName,
tableId: state.implicitTableId
};
} else if (expr.match(/\.\*$/)) {
let result = popPath(expr);
path = result.path;
pathInfo = resolvePath(state, result.path);
}
let table = state.schema[pathInfo.tableName];
if (table == null) {
throw new Error(`Table "${pathInfo.tableName}" does not exist`);
}
return Object.keys(table).map(field => path ? `${path}.${field}` : field);
}
const compileSelect = saveStack('select', (state, exprs, isAggregate, orders) => {
// Always include the id if it's not an aggregate
if (!isAggregate && !exprs.includes('id') && !exprs.includes('*')) {
exprs = exprs.concat(['id']);
}
let select = exprs.map(expr => {
if (typeof expr === 'string') {
if (expr.indexOf('*') !== -1) {
let fields = expandStar(state, expr);
return fields.map(field => {
let compiled = compileExpr(state, '$' + field);
state.outputTypes.set(field, compiled.type);
return compiled.value + ' AS ' + quoteAlias(field);
}).join(', ');
}
let compiled = compileExpr(state, '$' + expr);
state.outputTypes.set(expr, compiled.type);
return compiled.value + ' AS ' + quoteAlias(expr);
}
let _Object$entries$ = _slicedToArray(Object.entries(expr)[0], 2),
name = _Object$entries$[0],
value = _Object$entries$[1];
if (name[0] === '$') {
state.compileStack.push({
type: 'value',
value: expr
});
throw new CompileError(`Invalid field "${name}", are you trying to select a function? You need to name the expression`);
}
if (typeof value === 'string') {
let compiled = compileExpr(state, '$' + value);
state.outputTypes.set(name, compiled.type);
return `${compiled.value} AS ${quoteAlias(name)}`;
}
let compiled = compileFunction(_objectSpread(_objectSpread({}, state), {}, {
orders
}), value);
state.outputTypes.set(name, compiled.type);
return compiled.value + ` AS ${quoteAlias(name)}`;
});
return select.join(', ');
});
const compileGroupBy = saveStack('groupBy', (state, exprs) => {
let groupBy = exprs.map(expr => {
if (typeof expr === 'string') {
return compileExpr(state, '$' + expr).value;
}
return compileFunction(state, expr).value;
});
return groupBy.join(', ');
});
const compileOrderBy = saveStack('orderBy', (state, exprs) => {
let orderBy = exprs.map(expr => {
let compiled;
let dir = null;
if (typeof expr === 'string') {
compiled = compileExpr(state, '$' + expr).value;
} else {
let entries = Object.entries(expr);
let entry = entries[0]; // Check if this is a field reference
if (entries.length === 1 && entry[0][0] !== '$') {
dir = entry[1];
compiled = compileExpr(state, '$' + entry[0]).value;
} else {
// Otherwise it's a function
let $dir = expr.$dir,
func = _objectWithoutProperties(expr, _excluded2);
dir = $dir;
compiled = compileFunction(state, func).value;
}
}
if (dir != null) {
if (dir !== 'desc' && dir !== 'asc') {
throw new CompileError('Invalid order direction: ' + dir);
}
return `${compiled} ${dir}`;
}
return compiled;
});
return orderBy.join(', ');
});
let AGGREGATE_FUNCTIONS = ['$sum', '$count'];
function isAggregateFunction(expr) {
if (typeof expr !== 'object' || Array.isArray(expr)) {
return false;
}
let _Object$entries$2 = _slicedToArray(Object.entries(expr)[0], 2),
name = _Object$entries$2[0],
argExprs = _Object$entries$2[1];
if (!Array.isArray(argExprs)) {
argExprs = [argExprs];
}
if (AGGREGATE_FUNCTIONS.indexOf(name) !== -1) {
return true;
}
return argExprs.find(ex => isAggregateFunction(ex));
}
function isAggregateQuery(queryState) {
// it's aggregate if:
// either an aggregate function is used in `select`
// or a `groupBy` exists
if (queryState.groupExpressions.length > 0) {
return true;
}
return queryState.selectExpressions.find(expr => {
if (typeof expr !== 'string') {
let _Object$entries$3 = _slicedToArray(Object.entries(expr)[0], 2),
name = _Object$entries$3[0],
value = _Object$entries$3[1];
return isAggregateFunction(value);
}
return false;
});
}
function compileQuery(queryState, schema, schemaConfig = {}) {
let withDead = queryState.withDead,
_queryState$validateR = queryState.validateRefs,
validateRefs = _queryState$validateR === void 0 ? true : _queryState$validateR,
tableOptions = queryState.tableOptions,
rawMode = queryState.rawMode;
let _schemaConfig$tableVi = schemaConfig.tableViews,
tableViews = _schemaConfig$tableVi === void 0 ? {} : _schemaConfig$tableVi,
_schemaConfig$tableFi = schemaConfig.tableFilters,
tableFilters = _schemaConfig$tableFi === void 0 ? name => [] : _schemaConfig$tableFi,
_schemaConfig$customi = schemaConfig.customizeQuery,
customizeQuery = _schemaConfig$customi === void 0 ? queryState => queryState : _schemaConfig$customi;
let internalTableFilters = name => {
let filters = tableFilters(name); // These filters cannot join tables and must be simple strings
for (let filter of filters) {
if (Array.isArray(filter)) {
throw new CompileError('Invalid internal table filter: only object filters are supported');
}
if (Object.keys(filter)[0].indexOf('.') !== -1) {
throw new CompileError('Invalid internal table filter: field names cannot contain paths');
}
}
return filters;
};
let tableRef = (name, isJoin) => {
let view = typeof tableViews === 'function' ? tableViews(name, {
withDead,
isJoin,
tableOptions
}) : tableViews[name];
return view || name;
};
let tableName = queryState.table;
let _customizeQuery = customizeQuery(queryState),
filterExpressions = _customizeQuery.filterExpressions,
selectExpressions = _customizeQuery.selectExpressions,
groupExpressions = _customizeQuery.groupExpressions,
orderExpressions = _customizeQuery.orderExpressions,
limit = _customizeQuery.limit,
offset = _customizeQuery.offset,
calculation = _customizeQuery.calculation;
let select = '';
let where = '';
let joins = '';
let groupBy = '';
let orderBy = '';
let dependences = [];
let state = {
schema,
implicitTableName: tableName,
implicitTableId: tableRef(tableName),
paths: new Map(),
dependencies: [tableName],
compileStack: [],
outputTypes: new Map(),
validateRefs,
namedParameters: []
};
resetUid();
try {
select = compileSelect(state, selectExpressions, isAggregateQuery(queryState), orderExpressions);
if (filterExpressions.length > 0) {
let result = compileWhere(state, filterExpressions);
where = 'WHERE ' + result;
} else {
where = 'WHERE 1';
}
if (!rawMode) {
let filters = internalTableFilters(tableName);
if (filters.length > 0) {
where += ' AND ' + compileAnd(state, filters);
}
}
if (groupExpressions.length > 0) {
let result = compileGroupBy(state, groupExpressions);
groupBy = 'GROUP BY ' + result;
} // Orders don't matter if doing a single calculation
if (orderExpressions.length > 0) {
let result = compileOrderBy(state, orderExpressions);
orderBy = 'ORDER BY ' + result;
}
if (state.paths.size > 0) {
joins = compileJoins(state, tableRef, internalTableFilters);
}
} catch (e) {
if (e instanceof CompileError) {
throw getCompileError(e, state.compileStack);
}
throw e;
}
let sqlPieces = {
select,
from: tableRef(tableName),
joins,
where,
groupBy,
orderBy,
limit,
offset
};
return {
sqlPieces,
state
};
}
function defaultConstructQuery(queryState, state, sqlPieces) {
let s = sqlPieces;
let where = queryState.withDead ? s.where : addTombstone(state.schema, state.implicitTableName, state.implicitTableId, s.where);
return `
SELECT ${s.select} FROM ${s.from}
${s.joins}
${where}
${s.groupBy}
${s.orderBy}
${s.limit != null ? `LIMIT ${s.limit}` : ''}
${s.offset != null ? `OFFSET ${s.offset}` : ''}
`;
}
function generateSQLWithState(queryState, schema, schemaConfig) {
let _compileQuery = compileQuery(queryState, schema, schemaConfig),
sqlPieces = _compileQuery.sqlPieces,
state = _compileQuery.state;
return {
sql: defaultConstructQuery(queryState, state, sqlPieces),
state
};
}
function generateSQL(queryState) {
return generateSQLWithState(queryState).sql;
}
/***/ }),
/***/ "./packages/loot-core/src/server/aql/exec.js":
/*!***************************************************!*\
!*** ./packages/loot-core/src/server/aql/exec.js ***!
\***************************************************/
/*! exports provided: execQuery, runCompiledQuery, runQuery */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "execQuery", function() { return execQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runCompiledQuery", function() { return runCompiledQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runQuery", function() { return runQuery; });
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _compiler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./compiler */ "./packages/loot-core/src/server/aql/compiler.js");
/* harmony import */ var _schema_helpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./schema-helpers */ "./packages/loot-core/src/server/aql/schema-helpers.js");
// TODO (compiler):
// * Properly safeguard all inputs against SQL injection
// * Functions for incr/decr dates
// * Support HAVING
// * Allow creating in-memory tables to run queries against static
// data
// * For aggregate functions on selected ids, manually implement
// them only only support a specific few (sum amount / etc)
// * Select expressions should be evaluated first, and added to a
// global "field lookup" table that other filter/groupBy/etc
// expressions can reference
function applyTypes(data, outputTypes) {
for (let i = 0; i < data.length; i++) {
let item = data[i];
Object.keys(item).forEach(name => {
item[name] = Object(_schema_helpers__WEBPACK_IMPORTED_MODULE_2__["convertOutputType"])(item[name], outputTypes.get(name));
});
}
}
async function execQuery(queryState, state, sqlPieces, params, outputTypes) {
let sql = Object(_compiler__WEBPACK_IMPORTED_MODULE_1__["defaultConstructQuery"])(queryState, state, sqlPieces);
let data = await _db__WEBPACK_IMPORTED_MODULE_0__["all"](sql, params);
applyTypes(data, outputTypes);
return data;
}
async function runCompiledQuery(query, pieces, state, {
params = {},
executors = {}
} = {}) {
let paramArray = state.namedParameters.map(param => {
let name = param.paramName;
if (params[name] === undefined) {
throw new Error(`Parameter ${name} not provided to query`);
}
return Object(_schema_helpers__WEBPACK_IMPORTED_MODULE_2__["convertInputType"])(params[name], param.paramType);
});
let data;
if (executors[state.implicitTableName]) {
data = await executors[state.implicitTableName](state, query, pieces, paramArray, state.outputTypes);
} else {
data = await execQuery(query, state, pieces, paramArray, state.outputTypes);
}
if (query.calculation) {
if (data.length > 0) {
let row = data[0];
let k = Object.keys(row)[0]; // TODO: the function being run should be the one to
// determine the default value, not hardcoded as 0
data = row[k] || 0;
} else {
data = null;
}
}
return data;
}
async function runQuery(schema, schemaConfig, query, options) {
let _compileQuery = Object(_compiler__WEBPACK_IMPORTED_MODULE_1__["compileQuery"])(query, schema, schemaConfig),
sqlPieces = _compileQuery.sqlPieces,
state = _compileQuery.state;
let data = await runCompiledQuery(query, sqlPieces, state, options);
return {
data,
dependencies: state.dependencies
};
}
/***/ }),
/***/ "./packages/loot-core/src/server/aql/schema-helpers.js":
/*!*************************************************************!*\
!*** ./packages/loot-core/src/server/aql/schema-helpers.js ***!
\*************************************************************/
/*! exports provided: convertInputType, convertOutputType, conform, convertForInsert, convertForUpdate, convertFromSelect */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertInputType", function() { return convertInputType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertOutputType", function() { return convertOutputType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conform", function() { return conform; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertForInsert", function() { return convertForInsert; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertForUpdate", function() { return convertForUpdate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertFromSelect", function() { return convertFromSelect; });
/* harmony import */ var _models__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../models */ "./packages/loot-core/src/server/models.js");
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../shared/months */ "./packages/loot-core/src/shared/months.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function isRequired(name, fieldDesc) {
return fieldDesc.required || name === 'id';
} // TODO: All of the data type needs to check the input value. This
// doesn't just convert, it casts. See integer handling.
function convertInputType(value, type) {
if (value === undefined) {
throw new Error('Query value cannot be undefined');
} else if (value === null) {
if (type === 'boolean') {
return 0;
}
return null;
}
switch (type) {
case 'date':
if (value instanceof Date) {
return Object(_models__WEBPACK_IMPORTED_MODULE_0__["toDateRepr"])(Object(_shared_months__WEBPACK_IMPORTED_MODULE_1__["dayFromDate"])(value));
} else if (value.match(/^\d{4}-\d{2}-\d{2}$/) == null || value.date < '2000-01-01') {
throw new Error('Invalid date: ' + value);
}
return Object(_models__WEBPACK_IMPORTED_MODULE_0__["toDateRepr"])(value);
case 'date-month':
return Object(_models__WEBPACK_IMPORTED_MODULE_0__["toDateRepr"])(value.slice(0, 7));
case 'date-year':
return Object(_models__WEBPACK_IMPORTED_MODULE_0__["toDateRepr"])(value.slice(0, 4));
case 'boolean':
return value ? 1 : 0;
case 'id':
if (typeof value !== 'string' && value !== null) {
throw new Error('Invalid id, must be string: ' + value);
}
return value;
case 'integer':
if (typeof value === 'number' && (value | 0) === value) {
return value;
} else {
throw new Error("Can't convert to integer: " + JSON.stringify(value));
}
case 'json':
return JSON.stringify(value);
default:
}
return value;
}
function convertOutputType(value, type) {
if (value === null) {
if (type === 'boolean') {
return false;
}
return null;
}
switch (type) {
case 'date':
return Object(_models__WEBPACK_IMPORTED_MODULE_0__["fromDateRepr"])(value);
case 'date-month':
return Object(_models__WEBPACK_IMPORTED_MODULE_0__["fromDateRepr"])(value).slice(0, 7);
case 'date-year':
return Object(_models__WEBPACK_IMPORTED_MODULE_0__["fromDateRepr"])(value).slice(0, 4);
case 'boolean':
return value === 1;
case 'json':
case 'json/fallback':
try {
return JSON.parse(value);
} catch (e) {
return type === 'json/fallback' ? value : null;
}
default:
}
return value;
}
function conform(schema, schemaConfig, table, obj, {
skipNull
} = {}) {
let tableSchema = schema[table];
if (tableSchema == null) {
throw new Error(`Table "${table}" does not exist`);
}
let views = schemaConfig.views || {}; // Rename fields if necessary
let fieldRef = field => {
if (views[table] && views[table].fields) {
return views[table].fields[field] || field;
}
return field;
};
return Object.fromEntries(Object.keys(obj).map(field => {
// Fields that start with an underscore are ignored
if (field[0] === '_') {
return null;
}
let fieldDesc = tableSchema[field];
if (fieldDesc == null) {
throw new Error(`Field "${field}" does not exist on table ${table}: ${JSON.stringify(obj)}`);
}
if (isRequired(field, fieldDesc) && obj[field] == null) {
throw new Error(`"${field}" is required for table "${table}": ${JSON.stringify(obj)}`);
} // This option removes null values (see `convertForInsert`)
if (skipNull && obj[field] == null) {
return null;
}
return [fieldRef(field), convertInputType(obj[field], fieldDesc.type)];
}).filter(Boolean));
}
function convertForInsert(schema, schemaConfig, table, rawObj) {
let obj = _objectSpread({}, rawObj);
let tableSchema = schema[table];
if (tableSchema == null) {
throw new Error(`Error inserting: table "${table}" does not exist`);
} // Inserting checks all the fields in the table and adds any default
// values necessary
Object.keys(tableSchema).forEach(field => {
let fieldDesc = tableSchema[field];
if (obj[field] == null) {
if (fieldDesc.default !== undefined) {
obj[field] = typeof fieldDesc.default === 'function' ? fieldDesc.default() : fieldDesc.default;
} else if (isRequired(field, fieldDesc)) {
// Although this check is also done in `conform`, it only
// checks the fields in `obj`. For insert, we need to do it
// here to check that all required fields in the table exist
throw new Error(`"${field}" is required for table "${table}": ${JSON.stringify(obj)}`);
}
}
}); // We use `skipNull` to remove any null values. There's no need to
// set those when inserting, that will be the default and it reduces
// the amount of messages generated to sync
return conform(schema, schemaConfig, table, obj, {
skipNull: true
});
}
function convertForUpdate(schema, schemaConfig, table, rawObj) {
let obj = _objectSpread({}, rawObj);
let tableSchema = schema[table];
if (tableSchema == null) {
throw new Error(`Error updating: table "${table}" does not exist`);
}
return conform(schema, schemaConfig, table, obj);
}
function convertFromSelect(schema, schemaConfig, table, obj) {
let tableSchema = schema[table];
if (tableSchema == null) {
throw new Error(`Table "${table}" does not exist`);
}
let fields = Object.keys(tableSchema);
let result = {};
for (let i = 0; i < fields.length; i++) {
let fieldName = fields[i];
let fieldDesc = tableSchema[fieldName];
result[fieldName] = convertOutputType(obj[fieldName], fieldDesc.type);
}
return result;
}
/***/ }),
/***/ "./packages/loot-core/src/server/aql/schema/executors.js":
/*!***************************************************************!*\
!*** ./packages/loot-core/src/server/aql/schema/executors.js ***!
\***************************************************************/
/*! exports provided: toGroup, isHappyPathQuery, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toGroup", function() { return toGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHappyPathQuery", function() { return isHappyPathQuery; });
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _db_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../db/util */ "./packages/loot-core/src/server/db/util.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../shared/util */ "./packages/loot-core/src/shared/util.js");
/* harmony import */ var _compiler__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../compiler */ "./packages/loot-core/src/server/aql/compiler.js");
/* harmony import */ var _schema_helpers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../schema-helpers */ "./packages/loot-core/src/server/aql/schema-helpers.js");
/* harmony import */ var _exec__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../exec */ "./packages/loot-core/src/server/aql/exec.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
// Transactions executor
function toGroup(parents, children, mapper = x => x) {
return parents.reduce((list, parent) => {
let childs = children.get(parent.id) || [];
list.push(_objectSpread(_objectSpread({}, mapper(parent)), {}, {
subtransactions: childs.map(mapper)
}));
return list;
}, []);
} // These two queries will return very different things:
//
// q('transactions').select({ $count: 'id' })
// q('transactions', { splits: "grouped" }).select({ $count: 'id' })
//
// The first will return the count of non-split and child
// transactions, and the second will return the count of all parent
// (or non-split) transactions
function execTransactions(state, query, sql, params, outputTypes) {
let tableOptions = query.tableOptions || {};
let splitType = tableOptions.splits || 'inline';
if (['all', 'inline', 'none', 'grouped'].indexOf(splitType) === -1) {
throw new Error(`Invalid "splits" option for transactions: "${splitType}"`);
}
if (splitType === 'all' || splitType === 'inline' || splitType === 'none') {
return execTransactionsBasic(state, query, sql, params, splitType, outputTypes);
} else if (splitType === 'grouped') {
return execTransactionsGrouped(state, query, sql, params, splitType, outputTypes);
}
}
function _isUnhappy(filter) {
// These fields can be filtered - all split transactions will
// still be returned regardless
for (let key of Object.keys(filter)) {
if (key === '$or' || key === '$and') {
if (filter[key] && _isUnhappy(filter[key])) {
return true;
}
} else if (!(key.indexOf('account') === 0 || key === 'date')) {
return true;
}
}
return false;
}
function isHappyPathQuery(queryState) {
return queryState.filterExpressions.find(_isUnhappy) == null;
}
async function execTransactionsGrouped(state, queryState, sql, params, splitType, outputTypes) {
let tableName = queryState.table,
withDead = queryState.withDead;
let whereDead = withDead ? '' : `AND ${sql.from}.tombstone = 0`;
if (Object(_compiler__WEBPACK_IMPORTED_MODULE_3__["isAggregateQuery"])(queryState)) {
let allSql = `
SELECT ${sql.select}
FROM ${sql.from}
${sql.joins}
${sql.where} AND is_parent = 0 ${whereDead}
${sql.groupBy}
${sql.orderBy}
${sql.limit != null ? `LIMIT ${sql.limit}` : ''}
${sql.offset != null ? `OFFSET ${sql.offset}` : ''}
`;
return _db__WEBPACK_IMPORTED_MODULE_0__["all"](allSql);
}
let rows;
let matched = null;
if (isHappyPathQuery(queryState)) {
// This is just an optimization - we can just filter out children
// directly and only list parents
let rowSql = `
SELECT ${sql.from}.id as group_id
FROM ${sql.from}
${sql.joins}
${sql.where} AND is_child = 0 ${whereDead}
${sql.orderBy}
${sql.limit != null ? `LIMIT ${sql.limit}` : ''}
${sql.offset != null ? `OFFSET ${sql.offset}` : ''}
`;
rows = await _db__WEBPACK_IMPORTED_MODULE_0__["all"](rowSql, params);
} else {
// TODO: phew, what a doozy. write docs why it works this way
//
// prettier-ignore
let rowSql = `
SELECT group_id, matched FROM (
SELECT
group_id,
GROUP_CONCAT(id) as matched
FROM (
SELECT ${sql.from}.id, IFNULL(${sql.from}.parent_id, ${sql.from}.id) as group_id
FROM ${sql.from}
LEFT JOIN transactions _t2 ON ${sql.from}.is_child = 1 AND _t2.id = ${sql.from}.parent_id
${sql.joins}
${sql.where} AND ${sql.from}.tombstone = 0 AND IFNULL(_t2.tombstone, 0) = 0
)
GROUP BY group_id
)
LEFT JOIN ${sql.from} ON ${sql.from}.id = group_id
${sql.joins}
${sql.orderBy}
${sql.limit != null ? `LIMIT ${sql.limit}` : ''}
${sql.offset != null ? `OFFSET ${sql.offset}` : ''}
`;
rows = await _db__WEBPACK_IMPORTED_MODULE_0__["all"](rowSql, params);
matched = new Set([].concat.apply([], rows.map(row => row.matched.split(','))));
}
let where = Object(_db_util__WEBPACK_IMPORTED_MODULE_1__["whereIn"])(rows.map(row => row.group_id), `IFNULL(${sql.from}.parent_id, ${sql.from}.id)`);
let finalSql = `
SELECT ${sql.select}, parent_id AS _parent_id FROM ${sql.from}
${sql.joins}
WHERE ${where} ${whereDead}
${sql.orderBy}
`;
let start = Date.now();
let allRows = await _db__WEBPACK_IMPORTED_MODULE_0__["all"](finalSql); // Group the parents and children up
let _allRows$reduce = allRows.reduce((acc, trans) => {
let pid = trans._parent_id;
delete trans._parent_id;
if (pid == null) {
acc.parents.push(trans);
} else {
let arr = acc.children.get(pid) || [];
arr.push(trans);
acc.children.set(pid, arr);
}
return acc;
}, {
parents: [],
children: new Map()
}),
parents = _allRows$reduce.parents,
children = _allRows$reduce.children;
let mapper = trans => {
Object.keys(trans).forEach(name => {
trans[name] = Object(_schema_helpers__WEBPACK_IMPORTED_MODULE_4__["convertOutputType"])(trans[name], outputTypes.get(name));
});
if (matched && !matched.has(trans.id)) {
trans._unmatched = true;
}
return trans;
};
return toGroup(parents, children, mapper);
}
async function execTransactionsBasic(state, queryState, sql, params, splitType, outputTypes) {
let s = _objectSpread({}, sql);
if (splitType !== 'all') {
if (splitType === 'none') {
s.where = `${s.where} AND ${s.from}.parent_id IS NULL`;
} else {
s.where = `${s.where} AND ${s.from}.is_parent = 0`;
}
}
return Object(_exec__WEBPACK_IMPORTED_MODULE_5__["execQuery"])(queryState, state, s, params, outputTypes);
}
/* harmony default export */ __webpack_exports__["default"] = ({
transactions: execTransactions
});
/***/ }),
/***/ "./packages/loot-core/src/server/aql/schema/index.js":
/*!***********************************************************!*\
!*** ./packages/loot-core/src/server/aql/schema/index.js ***!
\***********************************************************/
/*! exports provided: schema, schemaConfig */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "schema", function() { return schema; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "schemaConfig", function() { return schemaConfig; });
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function f(type, opts) {
return _objectSpread({
type
}, opts);
} // This is the table schema!
//
// The schema itself is the public API for querying and updating data.
// The schema config provides a lot of control over how queries are
// constructed other metadata used by the executors. The goal is to
// provide a simple interface to the app, but allow the backend to
// highly optimize how queries are run.
//
// A few notes:
//
// * `transactions` is a special table and is has a highly customized
// executor (see `executors.js`) for performace. It should mostly be
// transparent to you, but it's worth reading the comments in there if
// requirements change, especially regarding split transactions.
//
// * You should rarely change the schema and only add to it, but it is
// relatively safe to change if needed. The only problem is changing a
// public API, but that could be mitigated with an option in schema
// config to map field name for backwards compatibility.
//
// * It's important that the table names here in the schema map to the
// real tables in sqlite that are updated. Otherwise subscriptions
// might not work because the dependencies are wrong. If needed in the
// future, we can provide another option in the schema config to map a
// table name the internal table that is updated.
const schema = {
transactions: {
id: f('id'),
is_parent: f('boolean'),
is_child: f('boolean'),
parent_id: f('id'),
account: f('id', {
ref: 'accounts',
required: true
}),
category: f('id', {
ref: 'categories'
}),
amount: f('integer', {
default: 0,
required: true
}),
payee: f('id', {
ref: 'payees'
}),
notes: f('string'),
date: f('date', {
required: true
}),
imported_id: f('string'),
error: f('json'),
imported_payee: f('string'),
starting_balance_flag: f('boolean'),
transfer_id: f('id'),
sort_order: f('float', {
default: () => Date.now()
}),
cleared: f('boolean', {
default: true
}),
tombstone: f('boolean'),
schedule: f('id', {
ref: 'schedules'
}) // subtransactions is a special field added if the table has the
// `splits: grouped` option
},
payees: {
id: f('id'),
name: f('string', {
required: true
}),
transfer_acct: f('id', {
ref: 'accounts'
}),
tombstone: f('boolean')
},
accounts: {
id: f('id'),
name: f('string', {
required: true
}),
// TODO: enum
type: f('string'),
offbudget: f('boolean'),
closed: f('boolean'),
sort_order: f('float'),
tombstone: f('boolean')
},
categories: {
id: f('id'),
name: f('string'),
is_income: f('boolean'),
group: f('id', {
ref: 'category_groups'
}),
sort_order: f('float'),
tombstone: f('boolean')
},
category_groups: {
id: f('id'),
name: f('string'),
is_income: f('boolean'),
sort_order: f('float'),
tombstone: f('boolean')
},
schedules: {
id: f('id'),
rule: f('id', {
ref: 'rules',
required: true
}),
next_date: f('date'),
completed: f('boolean'),
posts_transaction: f('boolean'),
tombstone: f('boolean'),
// These are special fields that are actually pulled from the
// underlying rule
_payee: f('id', {
ref: 'payees'
}),
_account: f('id', {
ref: 'accounts'
}),
_amount: f('json/fallback'),
_amountOp: f('string'),
_date: f('json/fallback'),
_conditions: f('json'),
_actions: f('json')
},
rules: {
id: f('id'),
stage: f('string'),
conditions: f('json'),
actions: f('json'),
tombstone: f('boolean')
},
notes: {
id: f('id'),
note: f('string')
}
};
const schemaConfig = {
// Note: these views *must* represent the underlying table that we
// are mapping here. The compiler makes optimizations with this
// assumption
tableViews(name, {
isJoin,
withDead,
tableOptions = {}
}) {
switch (name) {
case 'transactions':
{
// If joining, we always only show alive transactions. There's
// no way to configure join behavior yet
if (isJoin) {
return 'v_transactions_internal_alive';
}
let splitType = tableOptions.splits || 'inline'; // Use the view to exclude dead transactions if using `inline` or `none`
if (!withDead && (splitType === 'inline' || splitType === 'none')) {
return 'v_transactions_internal_alive';
} // Otherwse we disregard the `withDead` option here and handle
// that in the executors to improve performance
return 'v_transactions_internal';
}
case 'schedules':
return 'v_schedules';
case 'categories':
return 'v_categories';
case 'payees':
return 'v_payees';
default:
}
return name;
},
customizeQuery(queryState) {
let tableName = queryState.table,
_queryState$tableOpti = queryState.tableOptions,
tableOptions = _queryState$tableOpti === void 0 ? {} : _queryState$tableOpti;
function orderBy(orders) {
// If order was specified, always add id as the last sort to make
// it deterministic
if (orders.length > 0) {
return orders.concat(['id']);
} // Otherwise, these are the default orders for each table
switch (tableName) {
case 'transactions':
return [{
date: 'desc'
}, 'starting_balance_flag', {
sort_order: 'desc'
}, 'id'];
case 'payees':
return [{
$condition: {
transfer_acct: null
},
$dir: 'desc'
}, {
$nocase: '$name'
}];
case 'accounts':
return ['sort_order', 'name'];
case 'schedules':
return [{
$condition: {
completed: true
}
}, 'next_date'];
default:
}
return [];
}
return _objectSpread(_objectSpread({}, queryState), {}, {
orderExpressions: orderBy(queryState.orderExpressions)
});
},
views: {
payees: {
v_payees: internalFields => {
let fields = internalFields({
name: 'COALESCE(__accounts.name, _.name)'
});
return `
SELECT ${fields} FROM payees _
LEFT JOIN accounts __accounts ON (_.transfer_acct = __accounts.id AND __accounts.tombstone = 0)
-- We never want to show transfer payees that are pointing to deleted accounts.
-- Either this isn't a transfer payee, if the account exists
WHERE _.transfer_acct IS NULL OR __accounts.id IS NOT NULL
`;
}
},
categories: {
fields: {
group: 'cat_group'
},
v_categories: internalFields => {
let fields = internalFields({
group: 'cat_group'
});
return `SELECT ${fields} FROM categories _`;
}
},
schedules: {
v_schedules: internalFields => {
let fields = internalFields({
next_date: `
CASE
WHEN _nd.local_next_date_ts = _nd.base_next_date_ts THEN _nd.local_next_date
ELSE _nd.base_next_date
END
`,
_payee: `pm.targetId`,
_account: `json_extract(_rules.conditions, _paths.account || '.value')`,
_amount: `json_extract(_rules.conditions, _paths.amount || '.value')`,
_amountOp: `json_extract(_rules.conditions, _paths.amount || '.op')`,
_date: `json_extract(_rules.conditions, _paths.date || '.value')`,
_conditions: '_rules.conditions',
_actions: '_rules.actions'
});
return `
SELECT ${fields} FROM schedules _
LEFT JOIN schedules_next_date _nd ON _nd.schedule_id = _.id
LEFT JOIN schedules_json_paths _paths ON _paths.schedule_id = _.id
LEFT JOIN rules _rules ON _rules.id = _.rule
LEFT JOIN payee_mapping pm ON pm.id = json_extract(_rules.conditions, _paths.payee || '.value')
`;
}
},
transactions: {
fields: {
is_parent: 'isParent',
is_child: 'isChild',
account: 'acct',
imported_id: 'financial_id',
imported_payee: 'imported_description',
transfer_id: 'transferred_id',
payee: 'description'
},
v_transactions_internal: internalFields => {
// Override some fields to make custom stuff
let fields = internalFields({
payee: 'pm.targetId',
category: `CASE WHEN _.isParent = 1 THEN NULL ELSE cm.transferId END`,
amount: `IFNULL(_.amount, 0)`,
parent_id: 'CASE WHEN _.isChild = 0 THEN NULL ELSE _.parent_id END'
});
return `
SELECT ${fields} FROM transactions _
LEFT JOIN category_mapping cm ON cm.id = _.category
LEFT JOIN payee_mapping pm ON pm.id = _.description
WHERE
_.date IS NOT NULL AND
_.acct IS NOT NULL AND
(_.isChild = 0 OR _.parent_id IS NOT NULL)
`;
},
// We join on t2 to only include valid child transactions. We
// want to only include ones with valid parents, which is when
// an alive parent transaction exists
v_transactions_internal_alive: `
SELECT _.* FROM v_transactions_internal _
LEFT JOIN transactions t2 ON (_.is_child = 1 AND t2.id = _.parent_id)
WHERE IFNULL(_.tombstone, 0) = 0 AND (_.is_child = 0 OR t2.tombstone = 0)
`,
v_transactions: (_, publicFields) => {
let fields = publicFields({
payee: 'p.id',
category: 'c.id',
account: 'a.id'
}); // This adds an order, and also validates any id references by
// selecting the ids through a join which return null if they
// are dead
return `
SELECT ${fields} FROM v_transactions_internal_alive _
LEFT JOIN payees p ON (p.id = _.payee AND p.tombstone = 0)
LEFT JOIN categories c ON (c.id = _.category AND c.tombstone = 0)
LEFT JOIN accounts a ON (a.id = _.account AND a.tombstone = 0)
ORDER BY _.date desc, _.starting_balance_flag, _.sort_order desc, _.id;
`;
}
}
}
};
/***/ }),
/***/ "./packages/loot-core/src/server/aql/schema/run-query.js":
/*!***************************************************************!*\
!*** ./packages/loot-core/src/server/aql/schema/run-query.js ***!
\***************************************************************/
/*! exports provided: runCompiledQuery, runQuery */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runCompiledQuery", function() { return runCompiledQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runQuery", function() { return runQuery; });
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./index */ "./packages/loot-core/src/server/aql/schema/index.js");
/* harmony import */ var _executors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./executors */ "./packages/loot-core/src/server/aql/schema/executors.js");
/* harmony import */ var _exec__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../exec */ "./packages/loot-core/src/server/aql/exec.js");
/* harmony import */ var _shared_query__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../shared/query */ "./packages/loot-core/src/shared/query.js");
function runCompiledQuery(query, sqlPieces, state, params) {
return Object(_exec__WEBPACK_IMPORTED_MODULE_2__["runCompiledQuery"])(query, sqlPieces, state, {
params,
executors: _executors__WEBPACK_IMPORTED_MODULE_1__["default"]
});
}
function runQuery(query, params) {
if (query instanceof _shared_query__WEBPACK_IMPORTED_MODULE_3__["Query"]) {
query = query.serialize();
}
return Object(_exec__WEBPACK_IMPORTED_MODULE_2__["runQuery"])(_index__WEBPACK_IMPORTED_MODULE_0__["schema"], _index__WEBPACK_IMPORTED_MODULE_0__["schemaConfig"], query, {
params,
executors: _executors__WEBPACK_IMPORTED_MODULE_1__["default"]
});
}
/***/ }),
/***/ "./packages/loot-core/src/server/aql/views.js":
/*!****************************************************!*\
!*** ./packages/loot-core/src/server/aql/views.js ***!
\****************************************************/
/*! exports provided: makeViews */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeViews", function() { return makeViews; });
/* harmony import */ var _compiler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./compiler */ "./packages/loot-core/src/server/aql/compiler.js");
const _excluded = ["fields"];
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function selectFields(fields) {
return Object.keys(fields).map(as => {
let field = fields[as];
let needsAs = field !== as; // If it's just an identifier, we automatically prefix it with
// `_.` which makes sure it references the root table
if (!field.match(/[ .]/)) {
field = `_.${field}`;
}
return needsAs ? `${field} AS ${Object(_compiler__WEBPACK_IMPORTED_MODULE_0__["quoteAlias"])(as)}` : `${field}`;
}).join(', ');
}
function makeViews(schema, schemaConfig) {
let views = schemaConfig.views;
let viewStrs = [];
Object.keys(views).forEach(table => {
let _views$table = views[table],
_views$table$fields = _views$table.fields,
fieldMappings = _views$table$fields === void 0 ? {} : _views$table$fields,
tableViews = _objectWithoutProperties(_views$table, _excluded);
let publicFields = Object.fromEntries(Object.keys(schema[table]).map(name => [name, name]));
let internalFields = _objectSpread(_objectSpread({}, publicFields), fieldMappings);
Object.keys(tableViews).forEach(viewName => {
let publicMaker = overrides => {
let fields = _objectSpread(_objectSpread({}, publicFields), overrides);
return selectFields(fields);
};
let internalMaker = overrides => {
let fields = _objectSpread(_objectSpread({}, internalFields), overrides);
return selectFields(fields);
};
let sql;
if (typeof tableViews[viewName] === 'function') {
sql = tableViews[viewName](internalMaker, publicMaker);
} else {
sql = tableViews[viewName];
}
sql = sql.trim().replace(/;$/, '');
viewStrs.push(`
DROP VIEW IF EXISTS ${viewName};
CREATE VIEW ${viewName} AS ${sql};
`);
});
});
return viewStrs.join('\n');
}
/***/ }),
/***/ "./packages/loot-core/src/server/backups.js":
/*!**************************************************!*\
!*** ./packages/loot-core/src/server/backups.js ***!
\**************************************************/
/*! exports provided: getBackups, getLatestBackup, getAvailableBackups, updateBackups, makeBackup, loadBackup, startBackupService, stopBackupService */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBackups", function() { return getBackups; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLatestBackup", function() { return getLatestBackup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAvailableBackups", function() { return getAvailableBackups; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateBackups", function() { return updateBackups; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeBackup", function() { return makeBackup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadBackup", function() { return loadBackup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startBackupService", function() { return startBackupService; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stopBackupService", function() { return stopBackupService; });
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../platform/server/fs */ "./packages/loot-core/src/platform/server/fs/index.electron.js");
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../platform/server/sqlite */ "./packages/loot-core/src/platform/server/sqlite/index.electron.js");
/* harmony import */ var _prefs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./prefs */ "./packages/loot-core/src/server/prefs.js");
/* harmony import */ var _cloud_storage__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./cloud-storage */ "./packages/loot-core/src/server/cloud-storage.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const connection = __webpack_require__(/*! ../platform/server/connection */ "./packages/loot-core/src/platform/server/connection/index.api.js");
const uuid = __webpack_require__(/*! ../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js");
const dateFns = __webpack_require__(/*! date-fns */ "./node_modules/date-fns/esm/index.js"); // A special backup that represents the latest version of the db that
// can be reverted to after loading a backup
const LATEST_BACKUP_FILENAME = 'db.latest.sqlite';
let serviceInterval = null;
async function getBackups(id) {
const budgetDir = _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.getBudgetDir(id);
const backupDir = _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'backups');
let paths = [];
if (await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.exists(backupDir)) {
paths = await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.listDir(backupDir);
paths = paths.filter(file => file.match(/\.sqlite$/));
}
const backups = await Promise.all(paths.map(async path => {
const mtime = await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.getModifiedTime(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(backupDir, path));
return {
id: path,
date: new Date(mtime)
};
}));
backups.sort((b1, b2) => {
if (b1.date < b2.date) {
return 1;
} else if (b1.date > b2.date) {
return -1;
}
return 0;
});
return backups;
}
async function getLatestBackup(id) {
const budgetDir = _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.getBudgetDir(id);
if (await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.exists(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, LATEST_BACKUP_FILENAME))) {
return {
id: LATEST_BACKUP_FILENAME,
date: null,
isLatest: true
};
}
return null;
}
async function getAvailableBackups(id) {
let backups = await getBackups(id);
let latestBackup = await getLatestBackup(id);
if (latestBackup) {
backups.unshift(latestBackup);
}
backups = backups.map(backup => _objectSpread(_objectSpread({}, backup), {}, {
date: backup.date ? dateFns.format(backup.date, 'yyyy-MM-dd h:mm') : null
}));
return backups;
}
async function updateBackups(backups) {
const byDay = backups.reduce((groups, backup) => {
const day = dateFns.format(backup.date, 'yyyy-MM-dd');
groups[day] = groups[day] || [];
groups[day].push(backup);
return groups;
}, {});
const removed = [];
for (let day of Object.keys(byDay)) {
const dayBackups = byDay[day];
const isToday = day === _shared_months__WEBPACK_IMPORTED_MODULE_1__["currentDay"](); // Allow 3 backups of the current day (so fine-grained edits are
// kept around). Otherwise only keep around one backup per day.
// And only keep a total of 10 backups.
for (let backup of dayBackups.slice(isToday ? 3 : 1)) {
removed.push(backup.id);
}
} // Get the list of remaining backups and only keep the latest 10
const currentBackups = backups.filter(backup => !removed.includes(backup.id));
return removed.concat(currentBackups.slice(10).map(backup => backup.id));
}
async function makeBackup(id) {
const budgetDir = _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.getBudgetDir(id); // When making a backup, we no longer consider the user to be
// viewing any backups. If there exists a "latest backup" we should
// delete it and consider whatever is current as the latest
if (await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.exists(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, LATEST_BACKUP_FILENAME))) {
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.removeFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.getBudgetDir(id), LATEST_BACKUP_FILENAME));
}
let backupId = `${uuid.v4Sync()}.sqlite`;
let backupPath = _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'backups', backupId);
if (!(await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.exists(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'backups')))) {
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.mkdir(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'backups'));
}
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.copyFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'db.sqlite'), backupPath); // Remove all the messages from the backup
const db = _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_2__["openDatabase"](backupPath);
await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_2__["runQuery"](db, 'DELETE FROM messages_crdt');
await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_2__["runQuery"](db, 'DELETE FROM messages_clock');
_platform_server_sqlite__WEBPACK_IMPORTED_MODULE_2__["closeDatabase"](db);
const toRemove = await updateBackups(await getBackups(id));
for (let id of toRemove) {
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.removeFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'backups', id));
}
connection.send('backups-updated', await getAvailableBackups(id));
}
async function loadBackup(id, backupId) {
const budgetDir = _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.getBudgetDir(id);
if (!(await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.exists(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, LATEST_BACKUP_FILENAME)))) {
// If this is the first time we're loading a backup, save the
// current version so the user can easily revert back to it
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.copyFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'db.sqlite'), _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, LATEST_BACKUP_FILENAME));
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.copyFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'metadata.json'), _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'metadata.latest.json')); // Restart the backup service to make sure the user has the full
// amount of time to figure out which one they want
stopBackupService();
startBackupService(id);
await _prefs__WEBPACK_IMPORTED_MODULE_3__["loadPrefs"](id);
}
if (backupId === LATEST_BACKUP_FILENAME) {
console.log('Reverting backup'); // If reverting back to the latest, copy and delete the latest
// backup
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.copyFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, LATEST_BACKUP_FILENAME), _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'db.sqlite'));
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.copyFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'metadata.latest.json'), _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'metadata.json'));
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.removeFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, LATEST_BACKUP_FILENAME));
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.removeFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'metadata.latest.json')); // Re-upload the new file
try {
await _cloud_storage__WEBPACK_IMPORTED_MODULE_4__["upload"]();
} catch (e) {}
_prefs__WEBPACK_IMPORTED_MODULE_3__["unloadPrefs"]();
} else {
console.log('Loading backup', backupId); // This function is only ever called when a budget isn't loaded,
// so it's safe to load our prefs in. We need to forget about any
// syncing data if we are loading a backup (the current sync data
// will be restored if the user reverts to the original version)
await _prefs__WEBPACK_IMPORTED_MODULE_3__["loadPrefs"](id);
await _prefs__WEBPACK_IMPORTED_MODULE_3__["savePrefs"]({
groupId: null,
lastSyncedTimestamp: null,
lastUploaded: null
}); // Re-upload the new file
try {
await _cloud_storage__WEBPACK_IMPORTED_MODULE_4__["upload"]();
} catch (e) {}
_prefs__WEBPACK_IMPORTED_MODULE_3__["unloadPrefs"]();
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.copyFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'backups', backupId), _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'db.sqlite'));
}
}
function startBackupService(id) {
if (serviceInterval) {
clearInterval(serviceInterval);
} // Make a backup every 15 minutes
serviceInterval = setInterval(async () => {
console.log('Making backup');
await makeBackup(id);
}, 1000 * 60 * 15);
}
function stopBackupService() {
clearInterval(serviceInterval);
serviceInterval = null;
}
/***/ }),
/***/ "./packages/loot-core/src/server/budget/actions.js":
/*!*********************************************************!*\
!*** ./packages/loot-core/src/server/budget/actions.js ***!
\*********************************************************/
/*! exports provided: getBudget, setBudget, setBuffer, copyPreviousMonth, setZero, set3MonthAvg, setAllFuture, holdForNextMonth, holdForFutureMonths, resetHold, coverOverspending, transferAvailable, transferCategory, setCategoryCarryover */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBudget", function() { return getBudget; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setBudget", function() { return setBudget; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setBuffer", function() { return setBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "copyPreviousMonth", function() { return copyPreviousMonth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setZero", function() { return setZero; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "set3MonthAvg", function() { return set3MonthAvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setAllFuture", function() { return setAllFuture; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "holdForNextMonth", function() { return holdForNextMonth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "holdForFutureMonths", function() { return holdForFutureMonths; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resetHold", function() { return resetHold; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "coverOverspending", function() { return coverOverspending; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transferAvailable", function() { return transferAvailable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transferCategory", function() { return transferCategory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setCategoryCarryover", function() { return setCategoryCarryover; });
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _sync__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../sync */ "./packages/loot-core/src/server/sync/index.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/util */ "./packages/loot-core/src/shared/util.js");
/* harmony import */ var _prefs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../prefs */ "./packages/loot-core/src/server/prefs.js");
/* harmony import */ var _sheet__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../sheet */ "./packages/loot-core/src/server/sheet.js");
async function getSheetValue(sheetName, cell) {
const node = await _sheet__WEBPACK_IMPORTED_MODULE_5__["getCell"](sheetName, cell);
return typeof node.value === 'number' ? node.value : 0;
} // We want to only allow the positive movement of money back and
// forth. buffered should never be allowed to go into the negative,
// and you shouldn't be allowed to pull non-existant money from
// leftover.
function calcBufferedAmount(toBudget, buffered, amount) {
amount = Math.min(Math.max(amount, -buffered), Math.max(toBudget, 0));
return buffered + amount;
}
function getBudgetTable() {
let _ref = _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]() || {},
budgetType = _ref.budgetType;
return budgetType === 'report' ? 'reflect_budgets' : 'zero_budgets';
}
function isReflectBudget() {
let _prefs$getPrefs = _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"](),
budgetType = _prefs$getPrefs.budgetType;
return budgetType === 'report';
}
function isZeroBudget() {
let _prefs$getPrefs2 = _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"](),
budgetType = _prefs$getPrefs2.budgetType;
return budgetType === 'rollover';
}
function dbMonth(month) {
return parseInt(month.replace('-', ''));
}
function getBudgetData(table, month) {
return _db__WEBPACK_IMPORTED_MODULE_1__["all"](`
SELECT b.*, c.is_income FROM v_categories c
LEFT JOIN ${table} b ON b.category = c.id
WHERE c.tombstone = 0 AND b.month = ?
`, [month]);
}
function getAllMonths(startMonth) {
let _sheet$get$meta = _sheet__WEBPACK_IMPORTED_MODULE_5__["get"]().meta(),
createdMonths = _sheet$get$meta.createdMonths;
let latest = null;
for (let month of createdMonths) {
if (latest == null || month > latest) {
latest = month;
}
}
return _shared_months__WEBPACK_IMPORTED_MODULE_0__["rangeInclusive"](startMonth, latest);
} // TODO: Valid month format in all the functions below
function getBudget({
category,
month
}) {
let table = getBudgetTable();
let existing = _db__WEBPACK_IMPORTED_MODULE_1__["firstSync"](`SELECT * FROM ${table} WHERE month = ? AND category = ?`, [dbMonth(month), category]);
return existing ? existing.amount || 0 : 0;
}
function setBudget({
category,
month,
amount
}) {
if (typeof amount !== 'number') {
amount = 0;
}
const table = getBudgetTable();
let existing = _db__WEBPACK_IMPORTED_MODULE_1__["firstSync"](`SELECT id FROM ${table} WHERE month = ? AND category = ?`, [dbMonth(month), category]);
if (existing) {
return _db__WEBPACK_IMPORTED_MODULE_1__["update"](table, {
id: existing.id,
amount
});
}
return _db__WEBPACK_IMPORTED_MODULE_1__["insert"](table, {
id: `${dbMonth(month)}-${category}`,
month: dbMonth(month),
category,
amount
});
}
function setBuffer(month, amount) {
let existing = _db__WEBPACK_IMPORTED_MODULE_1__["firstSync"](`SELECT id FROM zero_budget_months WHERE id = ?`, [month]);
if (existing) {
return _db__WEBPACK_IMPORTED_MODULE_1__["update"]('zero_budget_months', {
id: existing.id,
buffered: amount
});
}
return _db__WEBPACK_IMPORTED_MODULE_1__["insert"]('zero_budget_months', {
id: month,
buffered: amount
});
}
function setCarryover(table, category, month, flag) {
let existing = _db__WEBPACK_IMPORTED_MODULE_1__["firstSync"](`SELECT id FROM ${table} WHERE month = ? AND category = ?`, [month, category]);
if (existing) {
return _db__WEBPACK_IMPORTED_MODULE_1__["update"](table, {
id: existing.id,
carryover: flag ? 1 : 0
});
}
return _db__WEBPACK_IMPORTED_MODULE_1__["insert"](table, {
id: `${month}-${category}`,
month,
category,
carryover: flag ? 1 : 0
});
} // Actions
async function copyPreviousMonth({
month
}) {
let prevMonth = dbMonth(_shared_months__WEBPACK_IMPORTED_MODULE_0__["prevMonth"](month));
let table = getBudgetTable();
let budgetData = await getBudgetData(table, prevMonth);
await Object(_sync__WEBPACK_IMPORTED_MODULE_2__["batchMessages"])(() => {
budgetData.forEach(prevBudget => {
if (prevBudget.is_income === 1 && !isReflectBudget()) {
return;
}
setBudget({
category: prevBudget.category,
month,
amount: prevBudget.amount
});
});
});
}
async function setZero({
month
}) {
let categories = await _db__WEBPACK_IMPORTED_MODULE_1__["all"]('SELECT * FROM v_categories WHERE tombstone = 0');
await Object(_sync__WEBPACK_IMPORTED_MODULE_2__["batchMessages"])(() => {
categories.forEach(cat => {
if (cat.is_income === 1 && !isReflectBudget()) {
return;
}
setBudget({
category: cat.id,
month,
amount: 0
});
});
});
}
async function set3MonthAvg({
month
}) {
let categories = await _db__WEBPACK_IMPORTED_MODULE_1__["all"]('SELECT * FROM v_categories WHERE tombstone = 0');
let prevMonth1 = _shared_months__WEBPACK_IMPORTED_MODULE_0__["prevMonth"](month);
let prevMonth2 = _shared_months__WEBPACK_IMPORTED_MODULE_0__["prevMonth"](prevMonth1);
let prevMonth3 = _shared_months__WEBPACK_IMPORTED_MODULE_0__["prevMonth"](prevMonth2);
await Object(_sync__WEBPACK_IMPORTED_MODULE_2__["batchMessages"])(async () => {
for (let cat of categories) {
if (cat.is_income === 1 && !isReflectBudget()) {
continue;
}
let spent1 = await getSheetValue(_shared_months__WEBPACK_IMPORTED_MODULE_0__["sheetForMonth"](prevMonth1), 'sum-amount-' + cat.id);
let spent2 = await getSheetValue(_shared_months__WEBPACK_IMPORTED_MODULE_0__["sheetForMonth"](prevMonth2), 'sum-amount-' + cat.id);
let spent3 = await getSheetValue(_shared_months__WEBPACK_IMPORTED_MODULE_0__["sheetForMonth"](prevMonth3), 'sum-amount-' + cat.id);
const avg = (spent1 + spent2 + spent3) / 3 | 0;
setBudget({
category: cat.id,
month,
amount: -avg
});
}
});
}
async function setAllFuture({
startMonth
}) {
if (!isReflectBudget()) {
throw new Error('setAllFuture only applies to report budget type');
}
let table = getBudgetTable();
let budgetData = await getBudgetData(table, dbMonth(startMonth));
let months = getAllMonths(_shared_months__WEBPACK_IMPORTED_MODULE_0__["addMonths"](startMonth, 1));
Object(_sync__WEBPACK_IMPORTED_MODULE_2__["batchMessages"])(() => {
for (let month of months) {
budgetData.forEach(budget => {
if (budget.is_income === 1 && !isReflectBudget()) {
return;
}
setBudget({
category: budget.category,
month,
amount: budget.amount
});
});
}
});
}
async function holdForNextMonth({
month,
amount
}) {
let row = await _db__WEBPACK_IMPORTED_MODULE_1__["first"]('SELECT buffered FROM zero_budget_months WHERE id = ?', [month]);
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_0__["sheetForMonth"](month);
let toBudget = await getSheetValue(sheetName, 'to-budget');
if (toBudget > 0) {
let bufferedAmount = calcBufferedAmount(toBudget, row && row.buffered || 0, amount);
await setBuffer(month, bufferedAmount);
return true;
}
return false;
}
async function holdForFutureMonths({
startMonth,
amount
}) {
let months = getAllMonths(startMonth);
await Object(_sync__WEBPACK_IMPORTED_MODULE_2__["batchMessages"])(async () => {
for (let month of months) {
if (!(await holdForNextMonth({
month,
amount
}))) {
break;
}
}
});
}
async function resetHold({
month
}) {
await setBuffer(month, 0);
}
async function coverOverspending({
month,
to,
from
}) {
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_0__["sheetForMonth"](month);
let toBudgeted = await getSheetValue(sheetName, 'budget-' + to);
let leftover = await getSheetValue(sheetName, 'leftover-' + to);
let leftoverFrom = await getSheetValue(sheetName, from === 'to-be-budgeted' ? 'to-budget' : 'leftover-' + from);
if (leftover >= 0 || leftoverFrom <= 0) {
return;
}
let amountCovered = Math.min(-leftover, leftoverFrom); // If we are covering it from the to be budgeted amount, ignore this
if (from !== 'to-be-budgeted') {
const fromBudgeted = await getSheetValue(sheetName, 'budget-' + from);
await setBudget({
category: from,
month,
amount: fromBudgeted - amountCovered
});
}
await setBudget({
category: to,
month,
amount: toBudgeted + amountCovered
});
}
async function transferAvailable({
month,
amount,
category
}) {
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_0__["sheetForMonth"](month);
let leftover = await getSheetValue(sheetName, 'to-budget');
amount = Math.max(Math.min(amount, leftover), 0);
let budgeted = await getSheetValue(sheetName, 'budget-' + category);
await setBudget({
category,
month,
amount: budgeted + amount
});
}
async function transferCategory({
month,
amount,
from,
to
}) {
const sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_0__["sheetForMonth"](month);
const fromBudgeted = await getSheetValue(sheetName, 'budget-' + from);
await setBudget({
category: from,
month,
amount: fromBudgeted - amount
}); // If we are simply moving it back into available cash to budget,
// don't do anything else
if (to !== 'to-be-budgeted') {
const toBudgeted = await getSheetValue(sheetName, 'budget-' + to);
await setBudget({
category: to,
month,
amount: toBudgeted + amount
});
}
}
async function setCategoryCarryover({
startMonth,
category,
flag
}) {
let table = getBudgetTable();
let months = getAllMonths(startMonth);
await Object(_sync__WEBPACK_IMPORTED_MODULE_2__["batchMessages"])(() => {
for (let month of months) {
setCarryover(table, category, dbMonth(month), flag);
}
});
}
/***/ }),
/***/ "./packages/loot-core/src/server/budget/app.js":
/*!*****************************************************!*\
!*** ./packages/loot-core/src/server/budget/app.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _app__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../app */ "./packages/loot-core/src/server/app.js");
/* harmony import */ var _mutators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../mutators */ "./packages/loot-core/src/server/mutators.js");
/* harmony import */ var _undo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../undo */ "./packages/loot-core/src/server/undo.js");
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./actions */ "./packages/loot-core/src/server/budget/actions.js");
let app = Object(_app__WEBPACK_IMPORTED_MODULE_0__["createApp"])();
app.method('budget/budget-amount', Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_2__["undoable"])(_actions__WEBPACK_IMPORTED_MODULE_3__["setBudget"])));
app.method('budget/copy-previous-month', Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_2__["undoable"])(_actions__WEBPACK_IMPORTED_MODULE_3__["copyPreviousMonth"])));
app.method('budget/set-zero', Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_2__["undoable"])(_actions__WEBPACK_IMPORTED_MODULE_3__["setZero"])));
app.method('budget/set-3month-avg', Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_2__["undoable"])(_actions__WEBPACK_IMPORTED_MODULE_3__["set3MonthAvg"])));
app.method('budget/set-all-future', Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_2__["undoable"])(_actions__WEBPACK_IMPORTED_MODULE_3__["setAllFuture"])));
app.method('budget/hold-for-next-month', Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_2__["undoable"])(_actions__WEBPACK_IMPORTED_MODULE_3__["holdForNextMonth"])));
app.method('budget/hold-for-future-months', Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_2__["undoable"])(_actions__WEBPACK_IMPORTED_MODULE_3__["holdForFutureMonths"])));
app.method('budget/reset-hold', Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_2__["undoable"])(_actions__WEBPACK_IMPORTED_MODULE_3__["resetHold"])));
app.method('budget/cover-overspending', Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_2__["undoable"])(_actions__WEBPACK_IMPORTED_MODULE_3__["coverOverspending"])));
app.method('budget/transfer-available', Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_2__["undoable"])(_actions__WEBPACK_IMPORTED_MODULE_3__["transferAvailable"])));
app.method('budget/transfer-category', Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_2__["undoable"])(_actions__WEBPACK_IMPORTED_MODULE_3__["transferCategory"])));
app.method('budget/set-carryover', Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_2__["undoable"])(_actions__WEBPACK_IMPORTED_MODULE_3__["setCategoryCarryover"])));
/* harmony default export */ __webpack_exports__["default"] = (app);
/***/ }),
/***/ "./packages/loot-core/src/server/budget/base.js":
/*!******************************************************!*\
!*** ./packages/loot-core/src/server/budget/base.js ***!
\******************************************************/
/*! exports provided: getBudgetType, getBudgetRange, triggerBudgetChanges, doTransfer, createBudget, createAllBudgets, setType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBudgetType", function() { return getBudgetType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBudgetRange", function() { return getBudgetRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "triggerBudgetChanges", function() { return triggerBudgetChanges; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "doTransfer", function() { return doTransfer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createBudget", function() { return createBudget; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createAllBudgets", function() { return createAllBudgets; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setType", function() { return setType; });
/* harmony import */ var _sheet__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../sheet */ "./packages/loot-core/src/server/sheet.js");
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/util */ "./packages/loot-core/src/shared/util.js");
/* harmony import */ var _spreadsheet_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../spreadsheet/util */ "./packages/loot-core/src/server/spreadsheet/util.js");
/* harmony import */ var _spreadsheet_util__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_spreadsheet_util__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _report__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./report */ "./packages/loot-core/src/server/budget/report.js");
/* harmony import */ var _rollover__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./rollover */ "./packages/loot-core/src/server/budget/rollover.js");
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./util */ "./packages/loot-core/src/server/budget/util.js");
/* harmony import */ var _budget_actions__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../budget/actions */ "./packages/loot-core/src/server/budget/actions.js");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function mergeUpdates(updates) {
const merged = {};
updates.forEach(update => {
Object.keys(update).forEach(sheet => {
if (merged[sheet]) {
merged[sheet] = _objectSpread(_objectSpread({}, merged[sheet]), update[sheet]);
} else {
merged[sheet] = update[sheet];
}
});
});
return merged;
}
function getBudgetType() {
let meta = _sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().meta();
return meta.budgetType || 'rollover';
}
function getBudgetRange(start, end) {
start = _shared_months__WEBPACK_IMPORTED_MODULE_2__["getMonth"](start);
end = _shared_months__WEBPACK_IMPORTED_MODULE_2__["getMonth"](end); // The start date should never be after the end date. If that
// happened, the month range might be a valid range and weird
// things happen
if (start > end) {
start = end;
} // Budgets should exist 3 months before the earliest needed date
// (either the oldest transaction or the current month if no
// transactions yet), and a year from the current date. There's no
// need to ever have budgets outside that range.
start = _shared_months__WEBPACK_IMPORTED_MODULE_2__["subMonths"](start, 3);
end = _shared_months__WEBPACK_IMPORTED_MODULE_2__["addMonths"](end, 12);
return {
start,
end,
range: _shared_months__WEBPACK_IMPORTED_MODULE_2__["rangeInclusive"](start, end)
};
}
function createCategory(cat, sheetName, prevSheetName, start, end) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'sum-amount-' + cat.id, {
initialValue: 0,
run: () => {
// Making this sync is faster!
let rows = _db__WEBPACK_IMPORTED_MODULE_1__["runQuery"](`SELECT SUM(amount) as amount FROM v_transactions_internal_alive t
LEFT JOIN accounts a ON a.id = t.account
WHERE t.date >= ${start} AND t.date <= ${end}
AND category = '${cat.id}' AND a.offbudget = 0`, [], true);
let row = rows[0];
let amount = row ? row.amount : 0;
return amount || 0;
}
});
if (getBudgetType() === 'rollover') {
_rollover__WEBPACK_IMPORTED_MODULE_6__["createCategory"](cat, sheetName, prevSheetName);
} else {
_report__WEBPACK_IMPORTED_MODULE_5__["createCategory"](cat, sheetName, prevSheetName);
}
}
function createCategoryGroup(group, sheetName) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'group-sum-amount-' + group.id, {
initialValue: 0,
dependencies: group.categories.map(cat => `sum-amount-${cat.id}`),
run: _util__WEBPACK_IMPORTED_MODULE_7__["sumAmounts"]
});
if (!group.is_income || getBudgetType() !== 'rollover') {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'group-budget-' + group.id, {
initialValue: 0,
dependencies: group.categories.map(cat => `budget-${cat.id}`),
run: _util__WEBPACK_IMPORTED_MODULE_7__["sumAmounts"]
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'group-leftover-' + group.id, {
initialValue: 0,
dependencies: group.categories.map(cat => `leftover-${cat.id}`),
run: _util__WEBPACK_IMPORTED_MODULE_7__["sumAmounts"]
});
}
}
function handleAccountChange(months, oldValue, newValue) {
if (!oldValue || oldValue.offbudget !== newValue.offbudget) {
let rows = _db__WEBPACK_IMPORTED_MODULE_1__["runQuery"](`
SELECT DISTINCT(category) as category FROM transactions
WHERE acct = ?
`, [newValue.id], true);
months.forEach(month => {
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_2__["sheetForMonth"](month, getBudgetType());
rows.forEach(row => {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().recompute(Object(_spreadsheet_util__WEBPACK_IMPORTED_MODULE_4__["resolveName"])(sheetName, 'sum-amount-' + row.category));
});
});
}
}
function handleTransactionChange(transaction, changedFields) {
if ((changedFields.has('date') || changedFields.has('acct') || changedFields.has('amount') || changedFields.has('category') || changedFields.has('tombstone') || changedFields.has('isParent')) && transaction.date && transaction.category) {
let month = _shared_months__WEBPACK_IMPORTED_MODULE_2__["monthFromDate"](_db__WEBPACK_IMPORTED_MODULE_1__["fromDateRepr"](transaction.date));
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_2__["sheetForMonth"](month, getBudgetType());
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().recompute(Object(_spreadsheet_util__WEBPACK_IMPORTED_MODULE_4__["resolveName"])(sheetName, 'sum-amount-' + transaction.category));
}
}
function handleCategoryMappingChange(months, oldValue, newValue) {
months.forEach(month => {
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_2__["sheetForMonth"](month, getBudgetType());
if (oldValue) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().recompute(Object(_spreadsheet_util__WEBPACK_IMPORTED_MODULE_4__["resolveName"])(sheetName, 'sum-amount-' + oldValue.transferId));
}
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().recompute(Object(_spreadsheet_util__WEBPACK_IMPORTED_MODULE_4__["resolveName"])(sheetName, 'sum-amount-' + newValue.transferId));
});
}
function handleCategoryChange(months, oldValue, newValue) {
function addDeps(sheetName, groupId, catId) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().addDependencies(sheetName, `group-sum-amount-${groupId}`, [`sum-amount-${catId}`]);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().addDependencies(sheetName, `group-budget-${groupId}`, [`budget-${catId}`]);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().addDependencies(sheetName, `group-leftover-${groupId}`, [`leftover-${catId}`]);
}
function removeDeps(sheetName, groupId, catId) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().removeDependencies(sheetName, `group-sum-amount-${groupId}`, [`sum-amount-${catId}`]);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().removeDependencies(sheetName, `group-budget-${groupId}`, [`budget-${catId}`]);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().removeDependencies(sheetName, `group-leftover-${groupId}`, [`leftover-${catId}`]);
}
let budgetType = getBudgetType();
if (oldValue && oldValue.tombstone === 0 && newValue.tombstone === 1) {
let id = newValue.id;
let groupId = newValue.cat_group;
months.forEach(month => {
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_2__["sheetForMonth"](month);
removeDeps(sheetName, groupId, id);
});
} else if (newValue.tombstone === 0 && (!oldValue || oldValue.tombstone === 1)) {
if (budgetType === 'rollover') {
_rollover__WEBPACK_IMPORTED_MODULE_6__["createBlankCategory"](newValue, months);
}
months.forEach(month => {
let prevMonth = _shared_months__WEBPACK_IMPORTED_MODULE_2__["prevMonth"](month);
let prevSheetName = _shared_months__WEBPACK_IMPORTED_MODULE_2__["sheetForMonth"](prevMonth, budgetType);
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_2__["sheetForMonth"](month, budgetType);
let _monthUtils$bounds = _shared_months__WEBPACK_IMPORTED_MODULE_2__["bounds"](month),
start = _monthUtils$bounds.start,
end = _monthUtils$bounds.end;
createCategory(newValue, sheetName, prevSheetName, start, end);
let id = newValue.id;
let groupId = newValue.cat_group;
if (getBudgetType() === 'rollover') {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().addDependencies(sheetName, 'last-month-overspent', [`${prevSheetName}!leftover-${id}`, `${prevSheetName}!carryover-${id}`]);
}
addDeps(sheetName, groupId, id);
});
} else if (oldValue && oldValue.cat_group !== newValue.cat_group) {
// The category moved so we need to update the dependencies
let id = newValue.id;
months.forEach(month => {
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_2__["sheetForMonth"](month, budgetType);
removeDeps(sheetName, oldValue.cat_group, id);
addDeps(sheetName, newValue.cat_group, id);
});
}
}
function handleCategoryGroupChange(months, oldValue, newValue) {
let budgetType = getBudgetType();
function addDeps(sheetName, groupId) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().addDependencies(sheetName, 'total-budgeted', [`group-budget-${groupId}`]);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().addDependencies(sheetName, 'total-spent', [`group-sum-amount-${groupId}`]);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().addDependencies(sheetName, 'total-leftover', [`group-leftover-${groupId}`]);
}
function removeDeps(sheetName, groupId) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().removeDependencies(sheetName, 'total-budgeted', [`group-budget-${groupId}`]);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().removeDependencies(sheetName, 'total-spent', [`group-sum-amount-${groupId}`]);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().removeDependencies(sheetName, 'total-leftover', [`group-leftover-${groupId}`]);
}
if (newValue.tombstone === 1 && oldValue && oldValue.tombstone === 0) {
let id = newValue.id;
months.forEach(month => {
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_2__["sheetForMonth"](month, budgetType);
removeDeps(sheetName, id);
});
} else if (newValue.tombstone === 0 && (!oldValue || oldValue.tombstone === 1)) {
let group = newValue;
if (!group.is_income || budgetType !== 'rollover') {
months.forEach(month => {
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_2__["sheetForMonth"](month, budgetType); // Dirty, dirty hack. These functions should not be async, but this is
// OK because we're leveraging the sync nature of queries. Ideally we
// wouldn't be querying here. But I think we have to. At least for now
// we do
let categories = _db__WEBPACK_IMPORTED_MODULE_1__["runQuery"]('SELECT * FROM categories WHERE tombstone = 0 AND cat_group = ?', [group.id], true);
createCategoryGroup(_objectSpread(_objectSpread({}, group), {}, {
categories
}), sheetName);
addDeps(sheetName, group.id);
});
}
}
}
function handleBudgetMonthChange(budget) {
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_2__["sheetForMonth"](budget.id);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().set(`${sheetName}!buffered`, budget.buffered);
}
function handleBudgetChange(budget) {
if (budget.category) {
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_2__["sheetForMonth"](budget.month.toString());
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().set(`${sheetName}!budget-${budget.category}`, budget.amount || 0);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().set(`${sheetName}!carryover-${budget.category}`, budget.carryover === 1 ? true : false);
}
}
function triggerBudgetChanges(oldValues, newValues) {
let _sheet$get$meta = _sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().meta(),
_sheet$get$meta$creat = _sheet$get$meta.createdMonths,
createdMonths = _sheet$get$meta$creat === void 0 ? new Set() : _sheet$get$meta$creat;
_sheet__WEBPACK_IMPORTED_MODULE_0__["startTransaction"]();
try {
newValues.forEach((items, table) => {
let old = oldValues.get(table);
items.forEach(newValue => {
let oldValue = old && old.get(newValue.id);
if (table === 'zero_budget_months') {
handleBudgetMonthChange(newValue);
} else if (table === 'zero_budgets' || table === 'reflect_budgets') {
handleBudgetChange(newValue);
} else if (table === 'transactions') {
let changed = new Set(Object.keys(Object(_shared_util__WEBPACK_IMPORTED_MODULE_3__["getChangedValues"])(oldValue || {}, newValue) || {}));
if (oldValue) {
handleTransactionChange(oldValue, changed);
}
handleTransactionChange(newValue, changed);
} else if (table === 'category_mapping') {
handleCategoryMappingChange(createdMonths, oldValue, newValue);
} else if (table === 'categories') {
handleCategoryChange(createdMonths, oldValue, newValue);
} else if (table === 'category_groups') {
handleCategoryGroupChange(createdMonths, oldValue, newValue);
} else if (table === 'accounts') {
handleAccountChange(createdMonths, oldValue, newValue);
}
});
});
} finally {
_sheet__WEBPACK_IMPORTED_MODULE_0__["endTransaction"]();
}
}
async function doTransfer(categoryIds, transferId) {
let _sheet$get$meta2 = _sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().meta(),
months = _sheet$get$meta2.createdMonths;
[...months].map(month => {
let totalValue = categoryIds.map(id => {
return _budget_actions__WEBPACK_IMPORTED_MODULE_8__["getBudget"]({
month,
category: id
});
}).reduce((total, value) => total + value, 0);
let transferValue = _budget_actions__WEBPACK_IMPORTED_MODULE_8__["getBudget"]({
month,
category: transferId
});
_budget_actions__WEBPACK_IMPORTED_MODULE_8__["setBudget"]({
month,
category: transferId,
amount: totalValue + transferValue
});
});
}
async function createBudget(months) {
const categories = await _db__WEBPACK_IMPORTED_MODULE_1__["getCategories"]();
const groups = await _db__WEBPACK_IMPORTED_MODULE_1__["getCategoriesGrouped"]();
_sheet__WEBPACK_IMPORTED_MODULE_0__["startTransaction"]();
let meta = _sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().meta();
meta.createdMonths = meta.createdMonths || new Set();
let budgetType = getBudgetType();
if (budgetType === 'rollover') {
_rollover__WEBPACK_IMPORTED_MODULE_6__["createBudget"](meta, categories, months);
}
months.forEach(month => {
if (!meta.createdMonths.has(month)) {
let prevMonth = _shared_months__WEBPACK_IMPORTED_MODULE_2__["prevMonth"](month);
let _monthUtils$bounds2 = _shared_months__WEBPACK_IMPORTED_MODULE_2__["bounds"](month),
start = _monthUtils$bounds2.start,
end = _monthUtils$bounds2.end;
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_2__["sheetForMonth"](month, budgetType);
let prevSheetName = _shared_months__WEBPACK_IMPORTED_MODULE_2__["sheetForMonth"](prevMonth, budgetType);
categories.forEach(cat => {
createCategory(cat, sheetName, prevSheetName, start, end);
});
groups.forEach(group => {
createCategoryGroup(group, sheetName);
});
if (budgetType === 'rollover') {
_rollover__WEBPACK_IMPORTED_MODULE_6__["createSummary"](groups, categories, prevSheetName, sheetName);
} else {
_report__WEBPACK_IMPORTED_MODULE_5__["createSummary"](groups, categories, sheetName);
}
meta.createdMonths.add(month);
}
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().setMeta(meta);
_sheet__WEBPACK_IMPORTED_MODULE_0__["endTransaction"](); // Wait for the spreadsheet to finish computing. Normally this won't
// do anything (as values are cached) but on first run this need to
// show the loading screen while it initially sets up.
await _sheet__WEBPACK_IMPORTED_MODULE_0__["waitOnSpreadsheet"]();
}
async function createAllBudgets() {
let earliestTransaction = await _db__WEBPACK_IMPORTED_MODULE_1__["first"]('SELECT * FROM transactions WHERE isChild=0 AND date IS NOT NULL ORDER BY date ASC LIMIT 1');
let earliestDate = earliestTransaction && _db__WEBPACK_IMPORTED_MODULE_1__["fromDateRepr"](earliestTransaction.date);
let currentMonth = _shared_months__WEBPACK_IMPORTED_MODULE_2__["currentMonth"](); // Get the range based off of the earliest transaction and the
// current month. If no transactions currently exist the current
// month is also used as the starting month
let _getBudgetRange = getBudgetRange(earliestDate || currentMonth, currentMonth),
start = _getBudgetRange.start,
end = _getBudgetRange.end,
range = _getBudgetRange.range;
let meta = _sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().meta();
let createdMonths = meta.createdMonths || new Set();
let newMonths = range.filter(m => !createdMonths.has(m));
if (newMonths.length > 0) {
await createBudget(range);
}
return {
start,
end
};
}
async function setType(type) {
let meta = _sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().meta();
if (type === meta.budgetType) {
return;
}
meta.budgetType = type;
meta.createdMonths = new Set(); // Go through and force all the cells to be recomputed
let nodes = _sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().getNodes();
_db__WEBPACK_IMPORTED_MODULE_1__["transaction"](() => {
for (let name of nodes.keys()) {
let _name$split = name.split('!'),
_name$split2 = _slicedToArray(_name$split, 2),
sheetName = _name$split2[0],
cellName = _name$split2[1];
if (sheetName.match(/^budget\d+/)) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().deleteCell(sheetName, cellName);
}
}
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().startCacheBarrier();
_sheet__WEBPACK_IMPORTED_MODULE_0__["loadUserBudgets"](_db__WEBPACK_IMPORTED_MODULE_1__);
let bounds = await createAllBudgets();
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().endCacheBarrier();
return bounds;
}
/***/ }),
/***/ "./packages/loot-core/src/server/budget/report.js":
/*!********************************************************!*\
!*** ./packages/loot-core/src/server/budget/report.js ***!
\********************************************************/
/*! exports provided: createCategory, createSummary */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createCategory", function() { return createCategory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createSummary", function() { return createSummary; });
/* harmony import */ var _sheet__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../sheet */ "./packages/loot-core/src/server/sheet.js");
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./util */ "./packages/loot-core/src/server/budget/util.js");
const _require = __webpack_require__(/*! ../spreadsheet/util */ "./packages/loot-core/src/server/spreadsheet/util.js"),
resolveName = _require.resolveName;
async function createCategory(cat, sheetName, prevSheetName) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createStatic(sheetName, `budget-${cat.id}`, 0); // This makes the app more robust by "fixing up" null budget values.
// Those should not be allowed, but in case somehow a null value
// ends up there, we are resilient to it. Preferrably the
// spreadsheet would have types and be more strict about what is
// allowed to be set.
if (_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().getCellValue(sheetName, `budget-${cat.id}`) == null) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().set(resolveName(sheetName, `budget-${cat.id}`), 0);
}
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, `leftover-${cat.id}`, {
initialValue: 0,
dependencies: [`budget-${cat.id}`, `sum-amount-${cat.id}`, `${prevSheetName}!carryover-${cat.id}`, `${prevSheetName}!leftover-${cat.id}`],
run: (budgeted, sumAmount, prevCarryover, prevLeftover) => {
if (cat.is_income) {
return Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(budgeted) - Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(sumAmount) + (prevCarryover ? Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(prevLeftover) : 0);
}
return Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(budgeted) + Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(sumAmount) + (prevCarryover ? Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(prevLeftover) : 0);
}
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, `spent-with-carryover-${cat.id}`, {
initialValue: 0,
dependencies: [`budget-${cat.id}`, `sum-amount-${cat.id}`, `carryover-${cat.id}`],
// TODO: Why refresh??
refresh: true,
run: (budgeted, sumAmount, carryover) => {
return carryover ? Math.max(0, Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(budgeted) + Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(sumAmount)) : sumAmount;
}
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createStatic(sheetName, `carryover-${cat.id}`, false);
}
function createSummary(groups, categories, sheetName) {
let incomeGroup = groups.filter(group => group.is_income)[0];
let expenseCategories = categories.filter(cat => !cat.is_income);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'total-budgeted', {
initialValue: 0,
dependencies: groups.filter(group => !group.is_income).map(group => `group-budget-${group.id}`),
run: _util__WEBPACK_IMPORTED_MODULE_2__["sumAmounts"]
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'total-spent', {
initialValue: 0,
refresh: true,
dependencies: expenseCategories.map(cat => `${sheetName}!spent-with-carryover-${cat.id}`),
run: _util__WEBPACK_IMPORTED_MODULE_2__["sumAmounts"]
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'total-income', {
initialValue: 0,
dependencies: [`group-sum-amount-${incomeGroup.id}`],
run: amount => amount
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'total-leftover', {
initialValue: 0,
dependencies: ['total-budgeted', 'total-spent'],
run: _util__WEBPACK_IMPORTED_MODULE_2__["sumAmounts"]
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'total-budget-income', {
initialValue: 0,
dependencies: [`group-budget-${incomeGroup.id}`],
run: amount => amount
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'total-saved', {
initialValue: 0,
dependencies: ['total-budget-income', 'total-budgeted'],
run: (income, budgeted) => {
return income - budgeted;
}
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'real-saved', {
initialValue: 0,
dependencies: ['total-income', 'total-spent'],
run: (income, spent) => {
return income - -spent;
}
});
}
/***/ }),
/***/ "./packages/loot-core/src/server/budget/rollover.js":
/*!**********************************************************!*\
!*** ./packages/loot-core/src/server/budget/rollover.js ***!
\**********************************************************/
/*! exports provided: createBlankCategory, createCategory, createSummary, createBudget */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createBlankCategory", function() { return createBlankCategory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createCategory", function() { return createCategory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createSummary", function() { return createSummary; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createBudget", function() { return createBudget; });
/* harmony import */ var _sheet__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../sheet */ "./packages/loot-core/src/server/sheet.js");
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./util */ "./packages/loot-core/src/server/budget/util.js");
const _require = __webpack_require__(/*! ../spreadsheet/util */ "./packages/loot-core/src/server/spreadsheet/util.js"),
resolveName = _require.resolveName;
function getBlankSheet(months) {
let blankMonth = _shared_months__WEBPACK_IMPORTED_MODULE_1__["prevMonth"](months[0]);
return _shared_months__WEBPACK_IMPORTED_MODULE_1__["sheetForMonth"](blankMonth, 'rollover');
}
function createBlankCategory(cat, months) {
if (months.length > 0) {
let sheetName = getBlankSheet(months);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createStatic(sheetName, `carryover-${cat.id}`, false);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createStatic(sheetName, `leftover-${cat.id}`, 0);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createStatic(sheetName, `leftover-pos-${cat.id}`, 0);
}
}
function createBlankMonth(categories, sheetName, months) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createStatic(sheetName, 'is-blank', true);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createStatic(sheetName, 'to-budget', 0);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createStatic(sheetName, 'buffered', 0);
categories.forEach(cat => createBlankCategory(cat, months));
}
function createCategory(cat, sheetName, prevSheetName) {
if (!cat.is_income) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createStatic(sheetName, `budget-${cat.id}`, 0); // This makes the app more robust by "fixing up" null budget values.
// Those should not be allowed, but in case somehow a null value
// ends up there, we are resilient to it. Preferrably the
// spreadsheet would have types and be more strict about what is
// allowed to be set.
if (_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().getCellValue(sheetName, `budget-${cat.id}`) == null) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().set(resolveName(sheetName, `budget-${cat.id}`), 0);
}
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createStatic(sheetName, `carryover-${cat.id}`, false);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, `leftover-${cat.id}`, {
initialValue: 0,
dependencies: [`budget-${cat.id}`, `sum-amount-${cat.id}`, `${prevSheetName}!carryover-${cat.id}`, `${prevSheetName}!leftover-${cat.id}`, `${prevSheetName}!leftover-pos-${cat.id}`],
run: (budgeted, spent, prevCarryover, prevLeftover, prevLeftoverPos) => {
return Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(budgeted) + Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(spent) + (prevCarryover ? Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(prevLeftover) : Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(prevLeftoverPos));
}
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'leftover-pos-' + cat.id, {
initialValue: 0,
dependencies: [`leftover-${cat.id}`],
run: leftover => {
return leftover < 0 ? 0 : leftover;
}
});
}
}
function createSummary(groups, categories, prevSheetName, sheetName) {
let incomeGroup = groups.filter(group => group.is_income)[0];
let expenseCategories = categories.filter(cat => !cat.is_income);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createStatic(sheetName, 'buffered', 0);
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'from-last-month', {
initialValue: 0,
dependencies: [`${prevSheetName}!to-budget`, `${prevSheetName}!buffered`],
run: (toBudget, buffered) => Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(toBudget) + Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(buffered)
}); // Alias the group income total to `total-income`
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'total-income', {
initialValue: 0,
dependencies: [`group-sum-amount-${incomeGroup.id}`],
run: amount => amount
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'available-funds', {
initialValue: 0,
dependencies: ['total-income', 'from-last-month'],
run: (income, fromLastMonth) => Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(income) + Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(fromLastMonth)
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'last-month-overspent', {
initialValue: 0,
dependencies: Object(_util__WEBPACK_IMPORTED_MODULE_2__["flatten2"])(expenseCategories.map(cat => [`${prevSheetName}!leftover-${cat.id}`, `${prevSheetName}!carryover-${cat.id}`])),
run: (...data) => {
data = Object(_util__WEBPACK_IMPORTED_MODULE_2__["unflatten2"])(data);
return data.reduce((total, [leftover, carryover]) => {
if (carryover) {
return total;
}
return total + Math.min(0, Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(leftover));
}, 0);
}
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'total-budgeted', {
initialValue: 0,
dependencies: groups.filter(group => !group.is_income).map(group => `group-budget-${group.id}`),
run: (...amounts) => {
// Negate budgeted amount
return -Object(_util__WEBPACK_IMPORTED_MODULE_2__["sumAmounts"])(...amounts);
}
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'buffered', {
initialValue: 0
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'to-budget', {
initialValue: 0,
dependencies: ['available-funds', 'last-month-overspent', 'total-budgeted', 'buffered'],
run: (available, lastOverspent, totalBudgeted, buffered) => {
return Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(available) + Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(lastOverspent) + Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(totalBudgeted) - Object(_util__WEBPACK_IMPORTED_MODULE_2__["number"])(buffered);
}
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'total-spent', {
initialValue: 0,
dependencies: groups.filter(group => !group.is_income).map(group => `group-sum-amount-${group.id}`),
run: _util__WEBPACK_IMPORTED_MODULE_2__["sumAmounts"]
});
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().createDynamic(sheetName, 'total-leftover', {
initialValue: 0,
dependencies: groups.filter(group => !group.is_income).map(group => `group-leftover-${group.id}`),
run: _util__WEBPACK_IMPORTED_MODULE_2__["sumAmounts"]
});
}
function createBudget(meta, categories, months) {
// The spreadsheet is now strict - so we need to fill in some
// default values for the month before the first month. Only do this
// if it doesn't already exist
let blankSheet = getBlankSheet(months);
if (meta.blankSheet !== blankSheet) {
_sheet__WEBPACK_IMPORTED_MODULE_0__["get"]().clearSheet(meta.blankSheet);
createBlankMonth(categories, blankSheet, months);
meta.blankSheet = blankSheet;
}
}
/***/ }),
/***/ "./packages/loot-core/src/server/budget/util.js":
/*!******************************************************!*\
!*** ./packages/loot-core/src/server/budget/util.js ***!
\******************************************************/
/*! exports provided: number, sumAmounts, flatten2, unflatten2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sumAmounts", function() { return sumAmounts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "flatten2", function() { return flatten2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unflatten2", function() { return unflatten2; });
/* harmony import */ var _spreadsheet_globals__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../spreadsheet/globals */ "./packages/loot-core/src/server/spreadsheet/globals.js");
/* harmony import */ var _spreadsheet_globals__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_spreadsheet_globals__WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "number", function() { return _spreadsheet_globals__WEBPACK_IMPORTED_MODULE_0__["number"]; });
function sumAmounts(...amounts) {
return amounts.reduce((total, amount) => {
return total + Object(_spreadsheet_globals__WEBPACK_IMPORTED_MODULE_0__["number"])(amount);
}, 0);
}
function flatten2(arr) {
return Array.prototype.concat.apply([], arr);
}
function unflatten2(arr) {
let res = [];
for (let i = 0; i < arr.length; i += 2) {
res.push([arr[i], arr[i + 1]]);
}
return res;
}
/***/ }),
/***/ "./packages/loot-core/src/server/cloud-storage.js":
/*!********************************************************!*\
!*** ./packages/loot-core/src/server/cloud-storage.js ***!
\********************************************************/
/*! exports provided: checkKey, resetSyncState, exportBuffer, upload, possiblyUpload, removeFile, listRemoteFiles, download */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkKey", function() { return checkKey; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resetSyncState", function() { return resetSyncState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exportBuffer", function() { return exportBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "upload", function() { return upload; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "possiblyUpload", function() { return possiblyUpload; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeFile", function() { return removeFile; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "listRemoteFiles", function() { return listRemoteFiles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "download", function() { return download; });
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../platform/server/fs */ "./packages/loot-core/src/platform/server/fs/index.electron.js");
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../platform/server/asyncStorage */ "./packages/loot-core/src/platform/server/asyncStorage/index.electron.js");
/* harmony import */ var _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _platform_server_fetch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../platform/server/fetch */ "./packages/loot-core/src/platform/server/fetch/index.electron.js");
/* harmony import */ var _platform_server_fetch__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_platform_server_fetch__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../platform/server/sqlite */ "./packages/loot-core/src/platform/server/sqlite/index.electron.js");
/* harmony import */ var _prefs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./prefs */ "./packages/loot-core/src/server/prefs.js");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./config */ "./packages/loot-core/src/server/config.js");
/* harmony import */ var _mutators__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./mutators */ "./packages/loot-core/src/server/mutators.js");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./errors */ "./packages/loot-core/src/server/errors.js");
/* harmony import */ var _encryption__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./encryption */ "./packages/loot-core/src/server/encryption.js");
/* harmony import */ var _post__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./post */ "./packages/loot-core/src/server/post.js");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
let uuid = __webpack_require__(/*! ../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js");
let AdmZip = __webpack_require__(/*! adm-zip */ "./packages/loot-core/node_modules/adm-zip/adm-zip.js");
let UPLOAD_FREQUENCY_IN_DAYS = 7;
async function checkHTTPStatus(res) {
if (res.status !== 200) {
return res.text().then(str => {
throw new _errors__WEBPACK_IMPORTED_MODULE_8__["HTTPError"](res.status, str);
});
} else {
return res;
}
}
async function fetchJSON(...args) {
let res = await Object(_platform_server_fetch__WEBPACK_IMPORTED_MODULE_2__["fetch"])(...args);
res = await checkHTTPStatus(res);
return res.json();
}
async function checkKey() {
let userToken = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_1___default.a.getItem('user-token');
let _prefs$getPrefs = _prefs__WEBPACK_IMPORTED_MODULE_5__["getPrefs"](),
cloudFileId = _prefs$getPrefs.cloudFileId,
encryptKeyId = _prefs$getPrefs.encryptKeyId;
let res;
try {
res = await Object(_post__WEBPACK_IMPORTED_MODULE_10__["post"])(Object(_config__WEBPACK_IMPORTED_MODULE_6__["getConfig"])().SYNC_SERVER + '/user-get-key', {
token: userToken,
fileId: cloudFileId
});
} catch (e) {
console.log(e);
return {
error: {
reason: 'network'
}
};
} // This == comparison is important, they could be null or undefined
// eslint-disable-next-line
return {
valid: res.id == encryptKeyId && ( // eslint-disable-line
encryptKeyId == null || _encryption__WEBPACK_IMPORTED_MODULE_9__["default"].hasKey(encryptKeyId))
};
}
async function resetSyncState(newKeyState) {
let userToken = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_1___default.a.getItem('user-token');
let _prefs$getPrefs2 = _prefs__WEBPACK_IMPORTED_MODULE_5__["getPrefs"](),
cloudFileId = _prefs$getPrefs2.cloudFileId;
if (process.env.IS_BETA) {
return {
error: {
reason: 'beta-version'
}
};
}
try {
await Object(_post__WEBPACK_IMPORTED_MODULE_10__["post"])(Object(_config__WEBPACK_IMPORTED_MODULE_6__["getConfig"])().SYNC_SERVER + '/reset-user-file', {
token: userToken,
fileId: cloudFileId
});
} catch (e) {
if (e instanceof _errors__WEBPACK_IMPORTED_MODULE_8__["PostError"]) {
return {
error: {
reason: e.reason === 'unauthorized' ? 'unauthorized' : 'network'
}
};
}
return {
error: {
reason: 'internal'
}
};
}
if (newKeyState) {
try {
await Object(_post__WEBPACK_IMPORTED_MODULE_10__["post"])(Object(_config__WEBPACK_IMPORTED_MODULE_6__["getConfig"])().SYNC_SERVER + '/user-create-key', {
token: userToken,
fileId: cloudFileId,
keyId: newKeyState.key.getId(),
keySalt: newKeyState.salt,
testContent: newKeyState.testContent
});
} catch (e) {
if (e instanceof _errors__WEBPACK_IMPORTED_MODULE_8__["PostError"]) {
return {
error: {
reason: 'network'
}
};
}
return {
error: {
reason: 'internal'
}
};
}
}
return {};
}
async function exportBuffer() {
let _prefs$getPrefs3 = _prefs__WEBPACK_IMPORTED_MODULE_5__["getPrefs"](),
id = _prefs$getPrefs3.id,
budgetName = _prefs$getPrefs3.budgetName;
if (!budgetName) {
return null;
}
let budgetDir = _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.getBudgetDir(id); // create zip
let zipped = new AdmZip(); // We run this in a mutator even though its not mutating anything
// because we are reading the sqlite file from disk. We want to make
// sure that we get a valid snapshot of it so we want this to be
// serialized with all other mutations.
await Object(_mutators__WEBPACK_IMPORTED_MODULE_7__["runMutator"])(async () => {
let rawDbContent = await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.readFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'db.sqlite'), 'binary'); // Do some post-processing of the database. We NEVER upload the cache with
// the database; this forces new downloads to always recompute everything
// which is not only safer, but reduces the filesize a lot.
let memDb = await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_4__["openDatabase"](rawDbContent);
_platform_server_sqlite__WEBPACK_IMPORTED_MODULE_4__["execQuery"](memDb, `
DELETE FROM kvcache;
DELETE FROM kvcache_key;
`);
let dbContent = _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_4__["exportDatabase"](memDb);
_platform_server_sqlite__WEBPACK_IMPORTED_MODULE_4__["closeDatabase"](memDb); // mark it as a file that needs a new clock so when a new client
// downloads it, it'll get set to a unique node
let meta = JSON.parse(await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.readFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'metadata.json')));
meta.resetClock = true;
let metaContent = Buffer.from(JSON.stringify(meta), 'utf8');
zipped.addFile('db.sqlite', dbContent);
zipped.addFile('metadata.json', metaContent);
});
return zipped.toBuffer();
}
async function upload() {
let userToken = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_1___default.a.getItem('user-token');
if (!userToken) {
throw Object(_errors__WEBPACK_IMPORTED_MODULE_8__["FileUploadError"])('unauthorized');
} // We never change the server from the beta version
if (process.env.IS_BETA) {
throw Object(_errors__WEBPACK_IMPORTED_MODULE_8__["FileUploadError"])('beta-version');
}
let zipContent = await exportBuffer();
if (zipContent == null) {
return;
}
let _prefs$getPrefs4 = _prefs__WEBPACK_IMPORTED_MODULE_5__["getPrefs"](),
id = _prefs$getPrefs4.id,
groupId = _prefs$getPrefs4.groupId,
budgetName = _prefs$getPrefs4.budgetName,
cloudFileId = _prefs$getPrefs4.cloudFileId,
encryptKeyId = _prefs$getPrefs4.encryptKeyId;
let uploadContent = zipContent;
let uploadMeta = null; // The upload process encrypts with the key tagged in the prefs for
// the file. It will upload the file and the server is responsible
// for checking that the key is up-to-date and rejecting it if not
if (encryptKeyId) {
let encrypted;
try {
encrypted = await _encryption__WEBPACK_IMPORTED_MODULE_9__["default"].encrypt(zipContent, encryptKeyId);
} catch (e) {
throw Object(_errors__WEBPACK_IMPORTED_MODULE_8__["FileUploadError"])('encrypt-failure', {
isMissingKey: e.message === 'missing-key'
});
}
uploadContent = encrypted.value;
uploadMeta = encrypted.meta;
}
if (!cloudFileId) {
cloudFileId = uuid.v4Sync();
}
let res;
try {
res = await fetchJSON(Object(_config__WEBPACK_IMPORTED_MODULE_6__["getConfig"])().SYNC_SERVER + '/upload-user-file', {
method: 'POST',
headers: _objectSpread(_objectSpread({
'Content-Length': uploadContent.length,
'Content-Type': 'application/encrypted-file',
'X-ACTUAL-TOKEN': userToken,
'X-ACTUAL-FILE-ID': cloudFileId,
'X-ACTUAL-NAME': encodeURIComponent(budgetName),
'X-ACTUAL-FORMAT': 2
}, uploadMeta ? {
'X-ACTUAL-ENCRYPT-META': JSON.stringify(uploadMeta)
} : null), groupId ? {
'X-ACTUAL-GROUP-ID': groupId
} : null),
body: uploadContent
});
} catch (err) {
console.log('Upload failure', err);
let reason = err instanceof _errors__WEBPACK_IMPORTED_MODULE_8__["PostError"] ? err.reason : 'network';
if (err instanceof _errors__WEBPACK_IMPORTED_MODULE_8__["PostError"]) {
throw new _errors__WEBPACK_IMPORTED_MODULE_8__["FileUploadError"](err.reason === 'unauthorized' ? 'unauthorized' : err.reason || 'network');
}
throw Object(_errors__WEBPACK_IMPORTED_MODULE_8__["FileUploadError"])('internal');
}
if (res.status === 'ok') {
// Only save it if we are still working on the same file
if (_prefs__WEBPACK_IMPORTED_MODULE_5__["getPrefs"]() && _prefs__WEBPACK_IMPORTED_MODULE_5__["getPrefs"]().id === id) {
await _prefs__WEBPACK_IMPORTED_MODULE_5__["savePrefs"]({
lastUploaded: _shared_months__WEBPACK_IMPORTED_MODULE_3__["currentDay"](),
cloudFileId,
groupId: res.groupId
});
}
} else {
throw Object(_errors__WEBPACK_IMPORTED_MODULE_8__["FileUploadError"])('internal');
}
}
async function possiblyUpload() {
let _prefs$getPrefs5 = _prefs__WEBPACK_IMPORTED_MODULE_5__["getPrefs"](),
cloudFileId = _prefs$getPrefs5.cloudFileId,
groupId = _prefs$getPrefs5.groupId,
lastUploaded = _prefs$getPrefs5.lastUploaded,
id = _prefs$getPrefs5.id;
let threshold = lastUploaded && _shared_months__WEBPACK_IMPORTED_MODULE_3__["addDays"](lastUploaded, UPLOAD_FREQUENCY_IN_DAYS);
let currentDay = _shared_months__WEBPACK_IMPORTED_MODULE_3__["currentDay"](); // We only want to try to upload every UPLOAD_FREQUENCY_IN_DAYS days
if (lastUploaded && currentDay < threshold) {
return;
} // We only want to upload existing cloud files that are part of a
// valid group
if (!cloudFileId || !groupId) {
return;
} // Don't block on uploading
upload().catch(err => {});
}
async function removeFile(fileId) {
const _await$asyncStorage$m = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_1___default.a.multiGet(['user-id', 'user-key']),
_await$asyncStorage$m2 = _slicedToArray(_await$asyncStorage$m, 2),
_await$asyncStorage$m3 = _slicedToArray(_await$asyncStorage$m2[0], 2),
userId = _await$asyncStorage$m3[1],
_await$asyncStorage$m4 = _slicedToArray(_await$asyncStorage$m2[1], 2),
userKey = _await$asyncStorage$m4[1];
await Object(_post__WEBPACK_IMPORTED_MODULE_10__["post"])(Object(_config__WEBPACK_IMPORTED_MODULE_6__["getConfig"])().SYNC_SERVER + '/delete-user-file', {
userId,
key: userKey,
fileId
});
}
async function listRemoteFiles() {
let userToken = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_1___default.a.getItem('user-token');
if (!userToken) {
return null;
}
let res;
try {
res = await fetchJSON(Object(_config__WEBPACK_IMPORTED_MODULE_6__["getConfig"])().SYNC_SERVER + '/list-user-files', {
headers: {
'X-ACTUAL-TOKEN': userToken
}
});
} catch (e) {
console.log('Error', e);
return null;
}
if (res.status === 'error') {
return null;
}
console.log(res.data);
return res.data.map(file => _objectSpread(_objectSpread({}, file), {}, {
hasKey: _encryption__WEBPACK_IMPORTED_MODULE_9__["default"].hasKey(file.encryptKeyId)
}));
}
async function download(fileId, replace) {
let userToken = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_1___default.a.getItem('user-token');
let buffer;
try {
buffer = await Object(_platform_server_fetch__WEBPACK_IMPORTED_MODULE_2__["fetch"])(Object(_config__WEBPACK_IMPORTED_MODULE_6__["getConfig"])().SYNC_SERVER + '/download-user-file', {
headers: {
'X-ACTUAL-TOKEN': userToken,
'X-ACTUAL-FILE-ID': fileId
}
}).then(checkHTTPStatus).then(res => {
if (res.arrayBuffer) {
return res.arrayBuffer().then(ab => Buffer.from(ab));
}
return res.buffer();
});
} catch (err) {
console.log('Download failure', err);
throw Object(_errors__WEBPACK_IMPORTED_MODULE_8__["FileDownloadError"])('download-failure');
}
let res;
try {
res = await fetchJSON(Object(_config__WEBPACK_IMPORTED_MODULE_6__["getConfig"])().SYNC_SERVER + '/get-user-file-info', {
headers: {
'X-ACTUAL-TOKEN': userToken,
'X-ACTUAL-FILE-ID': fileId
}
});
} catch (err) {
throw Object(_errors__WEBPACK_IMPORTED_MODULE_8__["FileDownloadError"])('internal', {
fileId
});
}
if (res.status !== 'ok') {
throw Object(_errors__WEBPACK_IMPORTED_MODULE_8__["FileDownloadError"])('internal', {
fileId
});
}
let fileData = res.data; // The download process checks if the server gave us decrypt
// information. It is assumed that this key has already been loaded
// in, which is done in a previous step
if (fileData.encryptMeta) {
try {
buffer = await _encryption__WEBPACK_IMPORTED_MODULE_9__["default"].decrypt(buffer, fileData.encryptMeta);
} catch (e) {
throw Object(_errors__WEBPACK_IMPORTED_MODULE_8__["FileDownloadError"])('decrypt-failure', {
isMissingKey: e.message === 'missing-key'
});
}
}
let zipped = new AdmZip(buffer);
let entries = zipped.getEntries();
let dbEntry = entries.find(e => e.entryName.includes('db.sqlite'));
let metaEntry = entries.find(e => e.entryName.includes('metadata.json'));
if (!dbEntry || !metaEntry) {
throw Object(_errors__WEBPACK_IMPORTED_MODULE_8__["FileDownloadError"])('invalid-zip-file');
}
let dbContent = zipped.readFile(dbEntry);
let metaContent = zipped.readFile(metaEntry);
let meta;
try {
meta = JSON.parse(metaContent.toString('utf8'));
} catch (err) {
throw Object(_errors__WEBPACK_IMPORTED_MODULE_8__["FileDownloadError"])('invalid-meta-file');
} // Update the metadata. The stored file on the server might be
// out-of-date with a few keys
meta = _objectSpread(_objectSpread({}, meta), {}, {
cloudFileId: fileData.fileId,
groupId: fileData.groupId,
lastUploaded: _shared_months__WEBPACK_IMPORTED_MODULE_3__["currentDay"](),
encryptKeyId: fileData.encryptMeta ? fileData.encryptMeta.keyId : null
});
let budgetDir = _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.getBudgetDir(meta.id);
if (await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.exists(budgetDir)) {
if (replace) {
// Don't remove the directory so that backups are retained
let dbFile = _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'db.sqlite');
let metaFile = _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'metadata.json');
if (await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.exists(dbFile)) {
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.removeFile(dbFile);
}
if (await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.exists(metaFile)) {
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.removeFile(metaFile);
}
} else {
throw Object(_errors__WEBPACK_IMPORTED_MODULE_8__["FileDownloadError"])('file-exists', {
id: meta.id
});
}
} else {
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.mkdir(budgetDir);
}
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.writeFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'db.sqlite'), dbContent);
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.writeFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(budgetDir, 'metadata.json'), JSON.stringify(meta));
return {
id: meta.id
};
}
/***/ }),
/***/ "./packages/loot-core/src/server/config.js":
/*!*************************************************!*\
!*** ./packages/loot-core/src/server/config.js ***!
\*************************************************/
/*! exports provided: setConfig, getConfig */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setConfig", function() { return setConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getConfig", function() { return getConfig; });
let config = {
SYNC_SERVER: 'https://sync.actualbudget.com/sync',
SIGNUP_SERVER: 'https://sync.actualbudget.com/account',
PLAID_SERVER: 'https://sync.actualbudget.com/plaid'
};
function setConfig(c) {
config = c;
}
function getConfig() {
return config;
}
/***/ }),
/***/ "./packages/loot-core/src/server/db/index.js":
/*!***************************************************!*\
!*** ./packages/loot-core/src/server/db/index.js ***!
\***************************************************/
/*! exports provided: toDateRepr, fromDateRepr, getDatabasePath, openDatabase, reopenDatabase, closeDatabase, setDatabase, getDatabase, loadClock, runQuery, execQuery, cache, transaction, asyncTransaction, all, first, firstSync, run, select, update, insertWithUUID, insert, delete_, selectWithSchema, selectFirstWithSchema, insertWithSchema, updateWithSchema, getCategories, getCategoriesGrouped, insertCategoryGroup, updateCategoryGroup, moveCategoryGroup, deleteCategoryGroup, insertCategory, updateCategory, moveCategory, deleteCategory, getPayee, insertPayee, deletePayee, deleteTransferPayee, updatePayee, mergePayees, getPayees, getOrphanedPayees, getPayeeByName, insertPayeeRule, deletePayeeRule, updatePayeeRule, getPayeeRules, getAccounts, insertAccount, updateAccount, deleteAccount, moveAccount, getTransaction, getTransactionsByDate, getTransactions, insertTransaction, updateTransaction, deleteTransaction */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDatabasePath", function() { return getDatabasePath; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "openDatabase", function() { return openDatabase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reopenDatabase", function() { return reopenDatabase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "closeDatabase", function() { return closeDatabase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setDatabase", function() { return setDatabase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDatabase", function() { return getDatabase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadClock", function() { return loadClock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runQuery", function() { return runQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "execQuery", function() { return execQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cache", function() { return cache; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transaction", function() { return transaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asyncTransaction", function() { return asyncTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "all", function() { return all; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "first", function() { return first; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "firstSync", function() { return firstSync; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "run", function() { return run; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "select", function() { return select; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "update", function() { return update; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "insertWithUUID", function() { return insertWithUUID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "insert", function() { return insert; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "delete_", function() { return delete_; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selectWithSchema", function() { return selectWithSchema; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selectFirstWithSchema", function() { return selectFirstWithSchema; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "insertWithSchema", function() { return insertWithSchema; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateWithSchema", function() { return updateWithSchema; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCategories", function() { return getCategories; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCategoriesGrouped", function() { return getCategoriesGrouped; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "insertCategoryGroup", function() { return insertCategoryGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateCategoryGroup", function() { return updateCategoryGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "moveCategoryGroup", function() { return moveCategoryGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteCategoryGroup", function() { return deleteCategoryGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "insertCategory", function() { return insertCategory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateCategory", function() { return updateCategory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "moveCategory", function() { return moveCategory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteCategory", function() { return deleteCategory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPayee", function() { return getPayee; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "insertPayee", function() { return insertPayee; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deletePayee", function() { return deletePayee; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteTransferPayee", function() { return deleteTransferPayee; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updatePayee", function() { return updatePayee; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergePayees", function() { return mergePayees; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPayees", function() { return getPayees; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getOrphanedPayees", function() { return getOrphanedPayees; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPayeeByName", function() { return getPayeeByName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "insertPayeeRule", function() { return insertPayeeRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deletePayeeRule", function() { return deletePayeeRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updatePayeeRule", function() { return updatePayeeRule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPayeeRules", function() { return getPayeeRules; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAccounts", function() { return getAccounts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "insertAccount", function() { return insertAccount; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateAccount", function() { return updateAccount; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteAccount", function() { return deleteAccount; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "moveAccount", function() { return moveAccount; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTransaction", function() { return getTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTransactionsByDate", function() { return getTransactionsByDate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTransactions", function() { return getTransactions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "insertTransaction", function() { return insertTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateTransaction", function() { return updateTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteTransaction", function() { return deleteTransaction; });
/* harmony import */ var lru_cache__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lru-cache */ "./packages/loot-core/node_modules/lru-cache/index.js");
/* harmony import */ var lru_cache__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lru_cache__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../platform/server/sqlite */ "./packages/loot-core/src/platform/server/sqlite/index.electron.js");
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../platform/server/fs */ "./packages/loot-core/src/platform/server/fs/index.electron.js");
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_platform_server_fs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _sync__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../sync */ "./packages/loot-core/src/server/sync/index.js");
/* harmony import */ var _aql_schema__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../aql/schema */ "./packages/loot-core/src/server/aql/schema/index.js");
/* harmony import */ var _models__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../models */ "./packages/loot-core/src/server/models.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../shared/util */ "./packages/loot-core/src/shared/util.js");
/* harmony import */ var _timestamp__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../timestamp */ "./packages/loot-core/src/server/timestamp.js");
/* harmony import */ var _aql_schema_helpers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../aql/schema-helpers */ "./packages/loot-core/src/server/aql/schema-helpers.js");
/* harmony import */ var _sort__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./sort */ "./packages/loot-core/src/server/db/sort.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toDateRepr", function() { return _models__WEBPACK_IMPORTED_MODULE_5__["toDateRepr"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromDateRepr", function() { return _models__WEBPACK_IMPORTED_MODULE_5__["fromDateRepr"]; });
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const uuid = __webpack_require__(/*! ../../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js");
let dbPath;
let db; // Util
function getDatabasePath() {
return dbPath;
}
async function openDatabase(id) {
if (db) {
await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["closeDatabase"](db);
}
dbPath = _platform_server_fs__WEBPACK_IMPORTED_MODULE_2___default.a.join(_platform_server_fs__WEBPACK_IMPORTED_MODULE_2___default.a.getBudgetDir(id), 'db.sqlite');
setDatabase(await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["openDatabase"](dbPath)); // await execQuery('PRAGMA journal_mode = WAL');
}
async function reopenDatabase() {
await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["closeDatabase"](db);
setDatabase(await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["openDatabase"](dbPath));
}
async function closeDatabase() {
if (db) {
await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["closeDatabase"](db);
setDatabase(null);
}
}
function setDatabase(db_) {
db = db_;
resetQueryCache();
}
function getDatabase() {
return db;
}
async function loadClock() {
let row = await first('SELECT * FROM messages_clock');
if (row) {
let clock = Object(_timestamp__WEBPACK_IMPORTED_MODULE_7__["deserializeClock"])(row.clock);
Object(_timestamp__WEBPACK_IMPORTED_MODULE_7__["setClock"])(clock);
} else {
// No clock exists yet (first run of the app), so create a default
// one.
let timestamp = new _timestamp__WEBPACK_IMPORTED_MODULE_7__["default"](0, 0, Object(_timestamp__WEBPACK_IMPORTED_MODULE_7__["makeClientId"])());
let clock = Object(_timestamp__WEBPACK_IMPORTED_MODULE_7__["makeClock"])(timestamp);
Object(_timestamp__WEBPACK_IMPORTED_MODULE_7__["setClock"])(clock);
await runQuery('INSERT INTO messages_clock (id, clock) VALUES (?, ?)', [1, Object(_timestamp__WEBPACK_IMPORTED_MODULE_7__["serializeClock"])(clock)]);
}
} // Functions
function runQuery(sql, params, fetchAll) {
// const unrecord = perf.record('sqlite');
const result = _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["runQuery"](db, sql, params, fetchAll); // unrecord();
return result;
}
function execQuery(sql) {
_platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["execQuery"](db, sql);
} // This manages an LRU cache of prepared query statements. This is
// only needed in hot spots when you are running lots of queries.
let _queryCache = new lru_cache__WEBPACK_IMPORTED_MODULE_0___default.a({
max: 100
});
function cache(sql) {
let cached = _queryCache.get(sql);
if (cached) {
return cached;
}
let prepared = _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["prepare"](db, sql);
_queryCache.set(sql, prepared);
return prepared;
}
function resetQueryCache() {
_queryCache = new lru_cache__WEBPACK_IMPORTED_MODULE_0___default.a({
max: 100
});
}
function transaction(fn) {
return _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["transaction"](db, fn);
}
function asyncTransaction(fn) {
return _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["asyncTransaction"](db, fn);
} // This function is marked as async because `runQuery` is no longer
// async. We return a promise here until we've audited all the code to
// make sure nothing calls `.then` on this.
async function all(sql, params) {
return runQuery(sql, params, true);
}
async function first(sql, params) {
const arr = await runQuery(sql, params, true);
return arr.length === 0 ? null : arr[0];
} // The underlying sql system is now sync, but we can't update `first` yet
// without auditing all uses of it
function firstSync(sql, params) {
const arr = runQuery(sql, params, true);
return arr.length === 0 ? null : arr[0];
} // This function is marked as async because `runQuery` is no longer
// async. We return a promise here until we've audited all the code to
// make sure nothing calls `.then` on this.
async function run(sql, params) {
return runQuery(sql, params);
}
async function select(table, id) {
const rows = await runQuery('SELECT * FROM ' + table + ' WHERE id = ?', [id], true);
return rows[0];
}
async function update(table, params) {
let fields = Object.keys(params).filter(k => k !== 'id');
if (params.id == null) {
throw new Error('update: id is required');
}
await Object(_sync__WEBPACK_IMPORTED_MODULE_3__["sendMessages"])(fields.map(k => {
return {
dataset: table,
row: params.id,
column: k,
value: params[k],
timestamp: _timestamp__WEBPACK_IMPORTED_MODULE_7__["default"].send()
};
}));
}
async function insertWithUUID(table, row) {
if (!row.id) {
row = _objectSpread(_objectSpread({}, row), {}, {
id: uuid.v4Sync()
});
}
await insert(table, row); // We can't rely on the return value of insert because if the
// primary key is text, sqlite returns the internal row id which we
// don't care about. We want to return the generated UUID.
return row.id;
}
async function insert(table, row) {
let fields = Object.keys(row).filter(k => k !== 'id');
if (row.id == null) {
throw new Error('insert: id is required');
}
await Object(_sync__WEBPACK_IMPORTED_MODULE_3__["sendMessages"])(fields.map(k => {
return {
dataset: table,
row: row.id,
column: k,
value: row[k],
timestamp: _timestamp__WEBPACK_IMPORTED_MODULE_7__["default"].send()
};
}));
}
async function delete_(table, id) {
await Object(_sync__WEBPACK_IMPORTED_MODULE_3__["sendMessages"])([{
dataset: table,
row: id,
column: 'tombstone',
value: 1,
timestamp: _timestamp__WEBPACK_IMPORTED_MODULE_7__["default"].send()
}]);
}
async function selectWithSchema(table, sql, params) {
let rows = await runQuery(sql, params, true);
return rows.map(row => Object(_aql_schema_helpers__WEBPACK_IMPORTED_MODULE_8__["convertFromSelect"])(_aql_schema__WEBPACK_IMPORTED_MODULE_4__["schema"], _aql_schema__WEBPACK_IMPORTED_MODULE_4__["schemaConfig"], table, row)).filter(Boolean);
}
async function selectFirstWithSchema(table, sql, params) {
let rows = await selectWithSchema(table, sql, params);
return rows.length > 0 ? rows[0] : null;
}
function insertWithSchema(table, row) {
// Even though `insertWithUUID` does this, we need to do it here so
// the schema validation passes
if (!row.id) {
row = _objectSpread(_objectSpread({}, row), {}, {
id: uuid.v4Sync()
});
}
return insertWithUUID(table, Object(_aql_schema_helpers__WEBPACK_IMPORTED_MODULE_8__["convertForInsert"])(_aql_schema__WEBPACK_IMPORTED_MODULE_4__["schema"], _aql_schema__WEBPACK_IMPORTED_MODULE_4__["schemaConfig"], table, row));
}
function updateWithSchema(table, fields) {
return update(table, Object(_aql_schema_helpers__WEBPACK_IMPORTED_MODULE_8__["convertForUpdate"])(_aql_schema__WEBPACK_IMPORTED_MODULE_4__["schema"], _aql_schema__WEBPACK_IMPORTED_MODULE_4__["schemaConfig"], table, fields));
} // Data-specific functions. Ideally this would be split up into
// different files
async function getCategories() {
return all(`
SELECT c.* FROM categories c
LEFT JOIN category_groups cg ON c.cat_group = cg.id
WHERE c.tombstone = 0
ORDER BY cg.sort_order, cg.id, c.sort_order, c.id
`);
}
async function getCategoriesGrouped() {
const groups = await all('SELECT * FROM category_groups WHERE tombstone = 0 ORDER BY is_income, sort_order, id');
const rows = await all(`
SELECT * FROM categories WHERE tombstone = 0
ORDER BY sort_order, id
`);
return groups.map(group => {
return _objectSpread(_objectSpread({}, group), {}, {
categories: rows.filter(row => row.cat_group === group.id)
});
});
}
async function insertCategoryGroup(group) {
const lastGroup = await first(`
SELECT sort_order FROM category_groups WHERE tombstone = 0 ORDER BY sort_order DESC, id DESC LIMIT 1
`);
const sort_order = (lastGroup ? lastGroup.sort_order : 0) + _sort__WEBPACK_IMPORTED_MODULE_9__["SORT_INCREMENT"];
group = _objectSpread(_objectSpread({}, _models__WEBPACK_IMPORTED_MODULE_5__["categoryGroupModel"].validate(group)), {}, {
sort_order: sort_order
});
return insertWithUUID('category_groups', group);
}
function updateCategoryGroup(group) {
group = _models__WEBPACK_IMPORTED_MODULE_5__["categoryGroupModel"].validate(group, {
update: true
});
return update('category_groups', group);
}
async function moveCategoryGroup(id, targetId) {
const groups = await all(`SELECT id, sort_order FROM category_groups WHERE tombstone = 0 ORDER BY sort_order, id`);
const _shoveSortOrders = Object(_sort__WEBPACK_IMPORTED_MODULE_9__["shoveSortOrders"])(groups, targetId),
updates = _shoveSortOrders.updates,
sort_order = _shoveSortOrders.sort_order;
for (let info of updates) {
await update('category_groups', info);
}
await update('category_groups', {
id,
sort_order
});
}
async function deleteCategoryGroup(group, transferId) {
const categories = await all('SELECT * FROM categories WHERE cat_group = ?', [group.id]); // Delete all the categories within a group
await Promise.all(categories.map(cat => deleteCategory(cat, transferId)));
await delete_('category_groups', group.id);
}
async function insertCategory(category, {
atEnd
} = {}) {
let sort_order;
let id_;
await Object(_sync__WEBPACK_IMPORTED_MODULE_3__["batchMessages"])(async () => {
if (atEnd) {
const lastCat = await first(`
SELECT sort_order FROM categories WHERE tombstone = 0 ORDER BY sort_order DESC, id DESC LIMIT 1
`);
sort_order = (lastCat ? lastCat.sort_order : 0) + _sort__WEBPACK_IMPORTED_MODULE_9__["SORT_INCREMENT"];
} else {
// Unfortunately since we insert at the beginning, we need to shove
// the sort orders to make sure there's room for it
const categories = await all(`SELECT id, sort_order FROM categories WHERE cat_group = ? AND tombstone = 0 ORDER BY sort_order, id`, [category.cat_group]);
const _shoveSortOrders2 = Object(_sort__WEBPACK_IMPORTED_MODULE_9__["shoveSortOrders"])(categories, categories.length > 0 ? categories[0].id : null),
updates = _shoveSortOrders2.updates,
order = _shoveSortOrders2.sort_order;
for (let info of updates) {
await update('categories', info);
}
sort_order = order;
}
category = _objectSpread(_objectSpread({}, _models__WEBPACK_IMPORTED_MODULE_5__["categoryModel"].validate(category)), {}, {
sort_order: sort_order
});
const id = await insertWithUUID('categories', category); // Create an entry in the mapping table that points it to itself
await insert('category_mapping', {
id,
transferId: id
});
id_ = id;
});
return id_;
}
function updateCategory(category) {
category = _models__WEBPACK_IMPORTED_MODULE_5__["categoryModel"].validate(category, {
update: true
});
return update('categories', category);
}
async function moveCategory(id, groupId, targetId) {
if (!groupId) {
throw new Error('moveCategory: groupId is required');
}
const categories = await all(`SELECT id, sort_order FROM categories WHERE cat_group = ? AND tombstone = 0 ORDER BY sort_order, id`, [groupId]);
const _shoveSortOrders3 = Object(_sort__WEBPACK_IMPORTED_MODULE_9__["shoveSortOrders"])(categories, targetId),
updates = _shoveSortOrders3.updates,
sort_order = _shoveSortOrders3.sort_order;
for (let info of updates) {
await update('categories', info);
}
await update('categories', {
id,
sort_order,
cat_group: groupId
});
}
async function deleteCategory(category, transferId) {
if (transferId) {
// We need to update all the deleted categories that currently
// point to the one we're about to delete so they all are
// "forwarded" to the new transferred category.
const existingTransfers = await all('SELECT * FROM category_mapping WHERE transferId = ?', [category.id]);
for (let mapping of existingTransfers) {
await update('category_mapping', {
id: mapping.id,
transferId
});
} // Finally, map the category we're about to delete to the new one
await update('category_mapping', {
id: category.id,
transferId
});
}
return delete_('categories', category.id);
}
async function getPayee(id) {
return first(`SELECT * FROM payees WHERE id = ?`, [id]);
}
async function insertPayee(payee) {
payee = _models__WEBPACK_IMPORTED_MODULE_5__["payeeModel"].validate(payee);
let id;
await Object(_sync__WEBPACK_IMPORTED_MODULE_3__["batchMessages"])(async () => {
id = await insertWithUUID('payees', payee);
await insert('payee_mapping', {
id,
targetId: id
});
});
return id;
}
async function deletePayee(payee) {
let _await$first = await first('SELECT * FROM payees WHERE id = ?', [payee.id]),
transfer_acct = _await$first.transfer_acct;
if (transfer_acct) {
// You should never be able to delete transfer payees
return;
} // let mappings = await all('SELECT id FROM payee_mapping WHERE targetId = ?', [
// payee.id
// ]);
// await Promise.all(
// mappings.map(m => update('payee_mapping', { id: m.id, targetId: null }))
// );
let rules = await all('SELECT * FROM payee_rules WHERE payee_id = ?', [payee.id]);
await Promise.all(rules.map(rule => deletePayeeRule({
id: rule.id
})));
return delete_('payees', payee.id);
}
async function deleteTransferPayee(payee) {
// This allows deleting transfer payees
return delete_('payees', payee.id);
}
function updatePayee(payee) {
payee = _models__WEBPACK_IMPORTED_MODULE_5__["payeeModel"].validate(payee, {
update: true
});
return update('payees', payee);
}
async function mergePayees(target, ids) {
// Load in payees so we can check some stuff
let payees = Object(_shared_util__WEBPACK_IMPORTED_MODULE_6__["groupById"])(await all('SELECT * FROM payees')); // Filter out any transfer payees
if (payees[target].transfer_acct != null) {
return;
}
ids = ids.filter(id => payees[id].transfer_acct == null);
await Object(_sync__WEBPACK_IMPORTED_MODULE_3__["batchMessages"])(async () => {
await Promise.all(ids.map(async id => {
let mappings = await all('SELECT id FROM payee_mapping WHERE targetId = ?', [id]);
await Promise.all(mappings.map(m => update('payee_mapping', {
id: m.id,
targetId: target
})));
}));
return Promise.all(ids.map(id => Promise.all([update('payee_mapping', {
id,
targetId: target
}), delete_('payees', id)])));
});
}
function getPayees() {
return all(`
SELECT p.*, COALESCE(a.name, p.name) AS name FROM payees p
LEFT JOIN accounts a ON (p.transfer_acct = a.id AND a.tombstone = 0)
WHERE p.tombstone = 0 AND (p.transfer_acct IS NULL OR a.id IS NOT NULL)
ORDER BY p.transfer_acct IS NULL DESC, p.name COLLATE NOCASE
`);
}
async function getOrphanedPayees() {
let rows = await all(`
SELECT p.id FROM payees p
LEFT JOIN payee_mapping pm ON pm.id = p.id
LEFT JOIN v_transactions_internal_alive t ON t.payee = pm.targetId
WHERE p.tombstone = 0 AND p.transfer_acct IS NULL AND t.id IS NULL
`);
return rows.map(row => row.id);
}
async function getPayeeByName(name) {
return first(`SELECT * FROM payees WHERE LOWER(name) = ? AND tombstone = 0`, [name.toLowerCase()]);
}
function insertPayeeRule(rule) {
rule = _models__WEBPACK_IMPORTED_MODULE_5__["payeeRuleModel"].validate(rule);
return insertWithUUID('payee_rules', rule);
}
function deletePayeeRule(rule) {
return delete_('payee_rules', rule.id);
}
function updatePayeeRule(rule) {
rule = _models__WEBPACK_IMPORTED_MODULE_5__["payeeModel"].validate(rule, {
update: true
});
return update('payee_rules', rule);
}
function getPayeeRules(id) {
return all(`SELECT pr.* FROM payee_rules pr
LEFT JOIN payee_mapping pm ON pm.id = pr.payee_id
WHERE pm.targetId = ? AND pr.tombstone = 0`, [id]);
}
function getAccounts() {
return all(`SELECT a.*, b.name as bankName, b.id as bankId FROM accounts a
LEFT JOIN banks b ON a.bank = b.id
WHERE a.tombstone = 0
ORDER BY sort_order, name`);
}
async function insertAccount(account) {
// Default to checking. Makes it a lot easier for tests and is
// generally harmless.
if (account.type === undefined) {
account = _objectSpread(_objectSpread({}, account), {}, {
type: 'checking'
});
}
const accounts = await all('SELECT * FROM accounts WHERE offbudget = ? ORDER BY sort_order, name', [account.offbudget != null ? account.offbudget : 0]); // Don't pass a target in, it will default to appending at the end
let _shoveSortOrders4 = Object(_sort__WEBPACK_IMPORTED_MODULE_9__["shoveSortOrders"])(accounts),
sort_order = _shoveSortOrders4.sort_order;
account = _models__WEBPACK_IMPORTED_MODULE_5__["accountModel"].validate(_objectSpread(_objectSpread({}, account), {}, {
sort_order
}));
return insertWithUUID('accounts', account);
}
function updateAccount(account) {
account = _models__WEBPACK_IMPORTED_MODULE_5__["accountModel"].validate(account, {
update: true
});
return update('accounts', account);
}
function deleteAccount(account) {
return delete_('accounts', account.id);
}
async function moveAccount(id, targetId) {
let account = await first('SELECT * FROM accounts WHERE id = ?', [id]);
let accounts;
if (account.closed) {
accounts = await all(`SELECT id, sort_order FROM accounts WHERE closed = 1 ORDER BY sort_order, name`);
} else {
accounts = await all(`SELECT id, sort_order FROM accounts WHERE tombstone = 0 AND offbudget = ? ORDER BY sort_order, name`, [account.offbudget]);
}
const _shoveSortOrders5 = Object(_sort__WEBPACK_IMPORTED_MODULE_9__["shoveSortOrders"])(accounts, targetId),
updates = _shoveSortOrders5.updates,
sort_order = _shoveSortOrders5.sort_order;
await Object(_sync__WEBPACK_IMPORTED_MODULE_3__["batchMessages"])(() => {
for (let info of updates) {
update('accounts', info);
}
update('accounts', {
id,
sort_order
});
});
}
async function getTransaction(id) {
let rows = await selectWithSchema('transactions', 'SELECT * FROM v_transactions WHERE id = ?', [id]);
return rows[0];
}
function _addFragmentForAccount(accountId, addWhere, options = {}) {
let _options$showClosed = options.showClosed,
showClosed = _options$showClosed === void 0 ? false : _options$showClosed,
_options$showOffbudge = options.showOffbudget,
showOffbudget = _options$showOffbudge === void 0 ? true : _options$showOffbudge;
let fragment = addWhere ? ' WHERE (' : ' AND ';
let params = [];
if (accountId) {
if (accountId === 'offbudget') {
fragment += 'a.closed = 0 AND a.offbudget = 1 ';
} else if (accountId === 'budgeted') {
fragment += 'a.closed = 0 AND a.offbudget = 0 ';
} else if (accountId === 'uncategorized') {
fragment += `
t.category IS NULL AND a.offbudget = 0 AND isParent = 0 AND (
ta.offbudget IS NULL OR ta.offbudget = 1
)
`;
} else {
fragment += 'a.id = ? ';
params.push(accountId);
}
} else {
fragment += showClosed ? '1' : 'a.closed = 0';
if (!showOffbudget) {
fragment += ' AND a.offbudget = 0';
}
}
return {
fragment,
params
};
}
async function getTransactionsByDate(accountId, startDate, endDate, options = {}) {
throw new Error('`getTransactionsByDate` is deprecated');
}
async function getTransactions(accountId, arg2) {
if (arg2 !== undefined) {
throw new Error('`getTransactions` was given a second argument, it now only takes a single argument `accountId`');
}
return selectWithSchema('transactions', 'SELECT * FROM v_transactions WHERE account = ?', [accountId]);
}
function insertTransaction(transaction) {
return insertWithSchema('transactions', transaction);
}
function updateTransaction(transaction) {
return updateWithSchema('transactions', transaction);
}
async function deleteTransaction(transaction) {
return delete_('transactions', transaction.id);
}
/***/ }),
/***/ "./packages/loot-core/src/server/db/mappings.js":
/*!******************************************************!*\
!*** ./packages/loot-core/src/server/db/mappings.js ***!
\******************************************************/
/*! exports provided: loadMappings, getMappings, getMapping */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadMappings", function() { return loadMappings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMappings", function() { return getMappings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMapping", function() { return getMapping; });
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./index */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _sync_index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../sync/index */ "./packages/loot-core/src/server/sync/index.js");
// This file keeps all the mappings in memory so we can access it
// synchronously. This is primarily used in the rules system, but
// there may be other uses in the future. You don't need to worry
// about this generally; if you are querying transactions, ids are
// transparently mapped for you. But if you are building something
// that stores ids and later uses them, you need to remember to map
// the ids.
//
// IMPORTANT: `loadMappings` must be called first before other modules
// that listen for sync changes. This must be the first sync listener
// to run in case other listeners use this mapping table; otherwise
// they might see stale mappings.
let allMappings;
let unlistenSync;
async function loadMappings() {
// The mappings are separated into tables specific to the type of
// data. But you know, we really could keep a global mapping table.
let categories = (await _index__WEBPACK_IMPORTED_MODULE_0__["all"]('SELECT * FROM category_mapping')).map(r => [r.id, r.transferId]);
let payees = (await _index__WEBPACK_IMPORTED_MODULE_0__["all"]('SELECT * FROM payee_mapping')).map(r => [r.id, r.targetId]); // All ids are unique, so we can just keep a global table of mappings
allMappings = new Map(categories.concat(payees));
if (unlistenSync) {
unlistenSync();
}
unlistenSync = Object(_sync_index__WEBPACK_IMPORTED_MODULE_1__["addSyncListener"])(onApplySync);
}
function onApplySync(oldValues, newValues) {
newValues.forEach((items, table) => {
if (table.indexOf('mapping') !== -1) {
let field = table === 'category_mapping' ? 'transferId' : 'targetId';
items.forEach(newValue => {
allMappings.set(newValue.id, newValue[field]);
});
}
});
}
function getMappings() {
return allMappings;
}
function getMapping(id) {
return allMappings.get(id) || null;
}
/***/ }),
/***/ "./packages/loot-core/src/server/db/sort.js":
/*!**************************************************!*\
!*** ./packages/loot-core/src/server/db/sort.js ***!
\**************************************************/
/*! exports provided: SORT_INCREMENT, shoveSortOrders */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SORT_INCREMENT", function() { return SORT_INCREMENT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shoveSortOrders", function() { return shoveSortOrders; });
const SORT_INCREMENT = 16384;
function midpoint(items, to) {
const below = items[to - 1];
const above = items[to];
if (!below) {
return above.sort_order / 2;
} else if (!above) {
return below.sort_order + SORT_INCREMENT;
} else {
return (below.sort_order + above.sort_order) / 2;
}
}
function shoveSortOrders(items, targetId) {
const to = items.findIndex(item => item.id === targetId);
const target = items[to];
const before = items[to - 1];
let updates = []; // If no target is specified, append at the end
if (!targetId || to === -1) {
let order;
if (items.length > 0) {
// Add a new increment to whatever is the latest sort order
order = items[items.length - 1].sort_order + SORT_INCREMENT;
} else {
// If no items exist, the default is to use the first increment
order = SORT_INCREMENT;
}
return {
updates,
sort_order: order
};
} else {
if (target.sort_order - (before ? before.sort_order : 0) <= 2) {
let next = to;
let order = (items[next].sort_order | 0) + SORT_INCREMENT;
while (next < items.length) {
// No need to update it if it's already greater than the current
// order. This can happen because there may already be large
// gaps
if (order <= items[next].sort_order) {
break;
}
updates.push({
id: items[next].id,
sort_order: order
});
next++;
order += SORT_INCREMENT;
}
}
return {
updates,
sort_order: midpoint(items, to)
};
}
}
/***/ }),
/***/ "./packages/loot-core/src/server/db/util.js":
/*!**************************************************!*\
!*** ./packages/loot-core/src/server/db/util.js ***!
\**************************************************/
/*! exports provided: incrFetch, whereIn */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "incrFetch", function() { return incrFetch; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "whereIn", function() { return whereIn; });
async function incrFetch(runQuery, terms, compare, makeQuery, params = []) {
let pageCount = 500;
let results = [];
let fetchedIds = new Set();
for (let i = 0; i < terms.length; i += pageCount) {
let slice = terms.slice(i, i + pageCount).filter(id => !fetchedIds.has(id));
if (slice.length > 0) {
let filter = slice.map(id => compare(id)).join(' OR ');
let query = makeQuery('(' + filter + ')');
let rows = await runQuery(query, params, true);
fetchedIds = new Set([...fetchedIds, ...slice]);
results = results.concat(rows);
}
}
return results;
}
function whereIn(ids, field) {
let ids2 = [...new Set(ids)];
let filter = `${field} IN (` + ids2.map(id => `'${id}'`).join(',') + ')';
return filter;
}
/***/ }),
/***/ "./packages/loot-core/src/server/encryption-internals.js":
/*!***************************************************************!*\
!*** ./packages/loot-core/src/server/encryption-internals.js ***!
\***************************************************************/
/*! exports provided: sha256String, randomBytes, encrypt, decrypt, createKey, importKey */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sha256String", function() { return sha256String; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "randomBytes", function() { return randomBytes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "encrypt", function() { return encrypt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decrypt", function() { return decrypt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createKey", function() { return createKey; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "importKey", function() { return importKey; });
let crypto = __webpack_require__(/*! crypto */ "crypto");
let ENCRYPTION_ALGORITHM = 'aes-256-gcm';
async function sha256String(str) {
return crypto.createHash('sha256').update(str).digest('base64');
}
function randomBytes(n) {
return crypto.randomBytes(n);
}
function encrypt(masterKey, value) {
let masterKeyBuffer = masterKey.getValue().raw; // let iv = createKeyBuffer({ numBytes: 12, secret: masterKeyBuffer });
let iv = crypto.randomBytes(12);
let cipher = crypto.createCipheriv(ENCRYPTION_ALGORITHM, masterKeyBuffer, iv);
let encrypted = cipher.update(value);
encrypted = Buffer.concat([encrypted, cipher.final()]);
let authTag = cipher.getAuthTag();
return {
value: encrypted,
meta: {
keyId: masterKey.getId(),
algorithm: ENCRYPTION_ALGORITHM,
iv: iv.toString('base64'),
authTag: authTag.toString('base64')
}
};
}
function decrypt(masterKey, encrypted, meta) {
let masterKeyBuffer = masterKey.getValue().raw;
let algorithm = meta.algorithm,
iv = meta.iv,
authTag = meta.authTag;
iv = Buffer.from(iv, 'base64');
authTag = Buffer.from(authTag, 'base64');
let decipher = crypto.createDecipheriv(algorithm, masterKeyBuffer, iv);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encrypted);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted;
}
function createKey({
secret,
salt
}) {
let buffer = createKeyBuffer({
secret,
salt
});
return {
raw: buffer,
base64: buffer.toString('base64')
};
}
function importKey(str) {
return {
raw: Buffer.from(str, 'base64'),
base64: str
};
}
/**
* Generates a Buffer of a desired byte length to be used as either an encryption key or an initialization vector.
*
* @private
* @param {Integer} [numBytes = 32] - Optional, number of bytes to fill the Buffer with.
* @param {String} [secret = <random bytes>] - Optional, a secret to use as a basis for the key generation algorithm.
* @returns {Buffer}
*/
function createKeyBuffer({
numBytes,
secret,
salt
}) {
return crypto.pbkdf2Sync(secret || crypto.randomBytes(128).toString('base64'), salt || crypto.randomBytes(32).toString('base64'), 10000, numBytes || 32, 'sha512');
}
/***/ }),
/***/ "./packages/loot-core/src/server/encryption.js":
/*!*****************************************************!*\
!*** ./packages/loot-core/src/server/encryption.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _encryption_internals__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./encryption-internals */ "./packages/loot-core/src/server/encryption-internals.js");
let uuid = __webpack_require__(/*! ../platform/uuid/index.electron.js */ "./packages/loot-core/src/platform/uuid/index.electron.js"); // A map of all possible master encryption keys to use, keyed by
// unique id
let keys = {};
class Key {
constructor({
id,
value
}) {
this.id = id || uuid.v4Sync();
}
async createFromPassword({
password,
salt
}) {
this.value = await _encryption_internals__WEBPACK_IMPORTED_MODULE_0__["createKey"]({
secret: password,
salt
});
}
async createFromBase64(str) {
this.value = await _encryption_internals__WEBPACK_IMPORTED_MODULE_0__["importKey"](str);
}
getId() {
return this.id;
}
getValue() {
return this.value;
}
serialize() {
return {
id: this.id,
base64: this.value.base64
};
}
}
function getKey(keyId) {
if (keyId == null || keys[keyId] == null) {
throw new Error('missing-key');
}
return keys[keyId];
}
function hasKey(keyId) {
return keyId in keys;
}
function encrypt(value, keyId) {
return _encryption_internals__WEBPACK_IMPORTED_MODULE_0__["encrypt"](getKey(keyId), value);
}
function decrypt(encrypted, meta) {
return _encryption_internals__WEBPACK_IMPORTED_MODULE_0__["decrypt"](getKey(meta.keyId), encrypted, meta);
}
function randomBytes(n) {
return _encryption_internals__WEBPACK_IMPORTED_MODULE_0__["randomBytes"](n);
}
async function loadKey(key) {
let keyInstance;
if (!(key instanceof Key)) {
keyInstance = new Key({
id: key.id
});
await keyInstance.createFromBase64(key.base64);
} else {
keyInstance = key;
}
keys[keyInstance.getId()] = keyInstance;
}
function unloadKey(key) {
delete keys[key.getId()];
}
function unloadAllKeys() {
keys = {};
}
async function createKey({
id,
password,
salt
}) {
let key = new Key({
id
});
await key.createFromPassword({
password,
salt
});
return key;
}
/* harmony default export */ __webpack_exports__["default"] = ({
decrypt,
encrypt,
randomBytes,
createKey,
loadKey,
getKey,
hasKey,
unloadKey,
unloadAllKeys
});
/***/ }),
/***/ "./packages/loot-core/src/server/errors.js":
/*!*************************************************!*\
!*** ./packages/loot-core/src/server/errors.js ***!
\*************************************************/
/*! exports provided: PostError, HTTPError, SyncError, TransactionError, RuleError, APIError, FileDownloadError, FileUploadError, isCodeError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PostError", function() { return PostError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HTTPError", function() { return HTTPError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SyncError", function() { return SyncError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransactionError", function() { return TransactionError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RuleError", function() { return RuleError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APIError", function() { return APIError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FileDownloadError", function() { return FileDownloadError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FileUploadError", function() { return FileUploadError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodeError", function() { return isCodeError; });
// TODO: normalize error types
class PostError extends Error {
constructor(reason, meta) {
super('PostError: ' + reason);
this.type = 'PostError';
this.reason = reason;
this.meta = meta;
}
}
class HTTPError extends Error {
constructor(code, body) {
super(`HTTPError: unsuccessful status code (${code}): ${body}`);
this.statusCode = code;
this.responseBody = body;
}
}
class SyncError extends Error {
constructor(reason, meta) {
super('SyncError: ' + reason);
this.reason = reason;
this.meta = meta;
}
}
class TransactionError extends Error {
// eslint-disable-next-line
constructor(message) {
super(message);
}
}
class RuleError extends Error {
constructor(type, message) {
super('RuleError: ' + message);
this.type = type;
}
}
function APIError(msg, meta) {
return {
type: 'APIError',
message: msg,
meta
};
}
function FileDownloadError(reason, meta) {
return {
type: 'FileDownloadError',
reason,
meta
};
}
function FileUploadError(reason, meta) {
return {
type: 'FileUploadError',
reason,
meta
};
}
function isCodeError(err) {
return err instanceof ReferenceError || err instanceof SyntaxError;
}
/***/ }),
/***/ "./packages/loot-core/src/server/main-app.js":
/*!***************************************************!*\
!*** ./packages/loot-core/src/server/main-app.js ***!
\***************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _app__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./app */ "./packages/loot-core/src/server/app.js");
const connection = __webpack_require__(/*! ../platform/server/connection */ "./packages/loot-core/src/platform/server/connection/index.api.js"); // Main app
const app = Object(_app__WEBPACK_IMPORTED_MODULE_0__["createApp"])();
app.events.on('sync', info => {
connection.send('sync-event', info);
});
/* harmony default export */ __webpack_exports__["default"] = (app);
/***/ }),
/***/ "./packages/loot-core/src/server/main.js":
/*!***********************************************!*\
!*** ./packages/loot-core/src/server/main.js ***!
\***********************************************/
/*! exports provided: handlers, initApp, init, lib */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "handlers", function() { return handlers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initApp", function() { return initApp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "init", function() { return init; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lib", function() { return lib; });
/* harmony import */ var _polyfills__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./polyfills */ "./packages/loot-core/src/server/polyfills.js");
/* harmony import */ var _polyfills__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_polyfills__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var date_fns__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! date-fns */ "./node_modules/date-fns/esm/index.js");
/* harmony import */ var _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../platform/server/asyncStorage */ "./packages/loot-core/src/platform/server/asyncStorage/index.electron.js");
/* harmony import */ var _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _platform_exceptions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../platform/exceptions */ "./packages/loot-core/src/platform/exceptions/index.electron.js");
/* harmony import */ var _prefs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./prefs */ "./packages/loot-core/src/server/prefs.js");
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../platform/server/fs */ "./packages/loot-core/src/platform/server/fs/index.electron.js");
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_platform_server_fs__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../platform/server/sqlite */ "./packages/loot-core/src/platform/server/sqlite/index.electron.js");
/* harmony import */ var _platform_server_log__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../platform/server/log */ "./packages/loot-core/src/platform/server/log/index.api.js");
/* harmony import */ var _platform__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./platform */ "./packages/loot-core/src/server/platform.js");
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _sheet__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./sheet */ "./packages/loot-core/src/server/sheet.js");
/* harmony import */ var _undo__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./undo */ "./packages/loot-core/src/server/undo.js");
/* harmony import */ var _update__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./update */ "./packages/loot-core/src/server/update.js");
/* harmony import */ var _accounts_rules__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./accounts/rules */ "./packages/loot-core/src/server/accounts/rules.js");
/* harmony import */ var _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./accounts/transaction-rules */ "./packages/loot-core/src/server/accounts/transaction-rules.js");
/* harmony import */ var _db_mappings__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./db/mappings */ "./packages/loot-core/src/server/db/mappings.js");
/* harmony import */ var _accounts_transactions__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./accounts/transactions */ "./packages/loot-core/src/server/accounts/transactions.js");
/* harmony import */ var _shared_rules__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../shared/rules */ "./packages/loot-core/src/shared/rules.js");
/* harmony import */ var _backups__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./backups */ "./packages/loot-core/src/server/backups.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../shared/util */ "./packages/loot-core/src/shared/util.js");
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _shared_accounts__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../shared/accounts */ "./packages/loot-core/src/shared/accounts.js");
/* harmony import */ var _budget_base__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./budget/base */ "./packages/loot-core/src/server/budget/base.js");
/* harmony import */ var _accounts_sync__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./accounts/sync */ "./packages/loot-core/src/server/accounts/sync.js");
/* harmony import */ var _accounts_link__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./accounts/link */ "./packages/loot-core/src/server/accounts/link.js");
/* harmony import */ var _util_budget_name__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./util/budget-name */ "./packages/loot-core/src/server/util/budget-name.js");
/* harmony import */ var _mutators__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./mutators */ "./packages/loot-core/src/server/mutators.js");
/* harmony import */ var _timestamp__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./timestamp */ "./packages/loot-core/src/server/timestamp.js");
/* harmony import */ var _merkle__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./merkle */ "./packages/loot-core/src/server/merkle.js");
/* harmony import */ var _sync__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./sync */ "./packages/loot-core/src/server/sync/index.js");
/* harmony import */ var _sync_migrate__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./sync/migrate */ "./packages/loot-core/src/server/sync/migrate.js");
/* harmony import */ var _accounts_payees__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./accounts/payees */ "./packages/loot-core/src/server/accounts/payees.js");
/* harmony import */ var _accounts_parse_file__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./accounts/parse-file */ "./packages/loot-core/src/server/accounts/parse-file.js");
/* harmony import */ var _accounts_export_to_csv__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./accounts/export-to-csv */ "./packages/loot-core/src/server/accounts/export-to-csv.js");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./config */ "./packages/loot-core/src/server/config.js");
/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./api */ "./packages/loot-core/src/server/api.js");
/* harmony import */ var _actual_app_api_injected__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! @actual-app/api/injected */ "./packages/api/injected.js");
/* harmony import */ var _actual_app_api_injected__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(_actual_app_api_injected__WEBPACK_IMPORTED_MODULE_36__);
/* harmony import */ var _cloud_storage__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./cloud-storage */ "./packages/loot-core/src/server/cloud-storage.js");
/* harmony import */ var _encryption__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./encryption */ "./packages/loot-core/src/server/encryption.js");
/* harmony import */ var _tracking_events__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./tracking/events */ "./packages/loot-core/src/server/tracking/events.js");
/* harmony import */ var _post__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./post */ "./packages/loot-core/src/server/post.js");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ./errors */ "./packages/loot-core/src/server/errors.js");
/* harmony import */ var _mocks_budget__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ../mocks/budget */ "./packages/loot-core/src/mocks/budget.js");
/* harmony import */ var _aql_schema_run_query__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./aql/schema/run-query */ "./packages/loot-core/src/server/aql/schema/run-query.js");
/* harmony import */ var _shared_query__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ../shared/query */ "./packages/loot-core/src/shared/query.js");
/* harmony import */ var _main_app__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ./main-app */ "./packages/loot-core/src/server/main-app.js");
/* harmony import */ var _schedules_app__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ./schedules/app */ "./packages/loot-core/src/server/schedules/app.js");
/* harmony import */ var _budget_app__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ./budget/app */ "./packages/loot-core/src/server/budget/app.js");
/* harmony import */ var _notes_app__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ./notes/app */ "./packages/loot-core/src/server/notes/app.js");
/* harmony import */ var _tools_app__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! ./tools/app */ "./packages/loot-core/src/server/tools/app.js");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
// Apps
const YNAB4 = __webpack_require__(/*! @actual-app/import-ynab4/importer */ "./packages/import-ynab4/importer.js");
const YNAB5 = __webpack_require__(/*! @actual-app/import-ynab5/importer */ "./packages/import-ynab5/importer.js");
const uuid = __webpack_require__(/*! ../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js");
const connection = __webpack_require__(/*! ../platform/server/connection */ "./packages/loot-core/src/platform/server/connection/index.api.js");
const _require = __webpack_require__(/*! ./spreadsheet/util */ "./packages/loot-core/src/server/spreadsheet/util.js"),
resolveName = _require.resolveName,
unresolveName = _require.unresolveName;
const SyncPb = __webpack_require__(/*! ./sync/proto/sync_pb */ "./packages/loot-core/src/server/sync/proto/sync_pb.js"); // let indexeddb = require('../platform/server/indexeddb');
let VERSION;
let DEMO_BUDGET_ID = '_demo-budget';
let TEST_BUDGET_ID = '_test-budget'; // util
function onSheetChange({
names
}) {
const nodes = names.map(name => {
let node = _sheet__WEBPACK_IMPORTED_MODULE_10__["get"]()._getNode(name);
return {
name: node.name,
value: node.value
};
});
connection.send('cells-changed', nodes);
}
function joinURL(base, ...paths) {
let url = new URL(base);
url.pathname = _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.join(paths);
return url.toString();
} // handlers
let handlers = {};
handlers['undo'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function () {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["undo"])();
});
handlers['redo'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(function () {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["redo"])();
});
handlers['transactions-batch-update'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
added,
deleted,
updated,
learnCategories
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
let result = await Object(_accounts_transactions__WEBPACK_IMPORTED_MODULE_16__["batchUpdateTransactions"])({
added,
updated,
deleted,
learnCategories
}); // Return all data updates to the frontend
return result.updated;
});
});
handlers['transaction-add'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function (transaction) {
await handlers['transactions-batch-update']({
added: [transaction]
});
return {};
});
handlers['transaction-update'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function (transaction) {
await handlers['transactions-batch-update']({
updated: [transaction]
});
return {};
});
handlers['transaction-delete'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function (transaction) {
await handlers['transactions-batch-update']({
deleted: [transaction]
});
return {};
});
handlers['transactions-filter'] = async function ({
term,
accountId,
latestDate,
count,
notPaged,
options = {}
}) {
return _db__WEBPACK_IMPORTED_MODULE_9__["getTransactions"](term, accountId, latestDate, notPaged ? null : count == null ? undefined : count, options);
};
handlers['transactions-parse-file'] = async function ({
filepath,
options
}) {
return Object(_accounts_parse_file__WEBPACK_IMPORTED_MODULE_32__["parseFile"])(filepath, options);
};
handlers['transactions-export'] = async function ({
transactions,
accounts,
categoryGroups,
payees
}) {
return Object(_accounts_export_to_csv__WEBPACK_IMPORTED_MODULE_33__["exportToCSV"])(transactions, accounts, categoryGroups, payees);
};
handlers['transactions-export-query'] = async function ({
query: queryState
}) {
return Object(_accounts_export_to_csv__WEBPACK_IMPORTED_MODULE_33__["exportQueryToCSV"])(new _shared_query__WEBPACK_IMPORTED_MODULE_44__["Query"](queryState));
};
handlers['get-categories'] = async function () {
return {
grouped: await _db__WEBPACK_IMPORTED_MODULE_9__["getCategoriesGrouped"](),
list: await _db__WEBPACK_IMPORTED_MODULE_9__["getCategories"]()
};
};
handlers['get-earliest-transaction'] = async function () {
let _await$aqlQuery = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_43__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_44__["default"])('transactions').options({
splits: 'none'
}).orderBy({
date: 'asc'
}).select('*').limit(1)),
data = _await$aqlQuery.data;
return data[0] || null;
};
handlers['get-budget-bounds'] = async function () {
return _budget_base__WEBPACK_IMPORTED_MODULE_22__["createAllBudgets"]();
};
handlers['rollover-budget-month'] = async function ({
month
}) {
let groups = await _db__WEBPACK_IMPORTED_MODULE_9__["getCategoriesGrouped"]();
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_20__["sheetForMonth"](month);
function value(name) {
let v = _sheet__WEBPACK_IMPORTED_MODULE_10__["getCellValue"](sheetName, name);
return {
value: v === '' ? 0 : v,
name: resolveName(sheetName, name)
};
}
let values = [value('available-funds'), value('last-month-overspent'), value('buffered'), value('total-budgeted'), value('to-budget'), value('from-last-month'), value('total-income'), value('total-spent'), value('total-leftover')];
for (let group of groups) {
if (group.is_income) {
values.push(value('total-income'));
for (let cat of group.categories) {
values.push(value(`sum-amount-${cat.id}`));
}
} else {
values = values.concat([value(`group-budget-${group.id}`), value(`group-sum-amount-${group.id}`), value(`group-leftover-${group.id}`)]);
for (let cat of group.categories) {
values = values.concat([value(`budget-${cat.id}`), value(`sum-amount-${cat.id}`), value(`leftover-${cat.id}`), value(`carryover-${cat.id}`)]);
}
}
}
return values;
};
handlers['report-budget-month'] = async function ({
month
}) {
let groups = await _db__WEBPACK_IMPORTED_MODULE_9__["getCategoriesGrouped"]();
let sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_20__["sheetForMonth"](month);
function value(name) {
let v = _sheet__WEBPACK_IMPORTED_MODULE_10__["getCellValue"](sheetName, name);
return {
value: v === '' ? 0 : v,
name: resolveName(sheetName, name)
};
}
let values = [value('total-budgeted'), value('total-budget-income'), value('total-saved'), value('total-income'), value('total-spent'), value('real-saved'), value('total-leftover')];
for (let group of groups) {
values = values.concat([value(`group-budget-${group.id}`), value(`group-sum-amount-${group.id}`), value(`group-leftover-${group.id}`)]);
for (let cat of group.categories) {
values = values.concat([value(`budget-${cat.id}`), value(`sum-amount-${cat.id}`), value(`leftover-${cat.id}`)]);
if (!group.is_income) {
values.push(value(`carryover-${cat.id}`));
}
}
}
return values;
};
handlers['budget-set-type'] = async function ({
type
}) {
if (type !== 'rollover' && type !== 'report') {
throw new Error('Invalid budget type: ' + type);
} // It's already the same; don't do anything
if (type === _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]().budgetType) {
return;
} // Save prefs
return _prefs__WEBPACK_IMPORTED_MODULE_4__["savePrefs"]({
budgetType: type
});
};
handlers['category-create'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
name,
groupId,
isIncome
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
if (!groupId) {
throw Object(_errors__WEBPACK_IMPORTED_MODULE_41__["APIError"])('Creating a category: groupId is required');
}
return _db__WEBPACK_IMPORTED_MODULE_9__["insertCategory"]({
name,
cat_group: groupId,
is_income: isIncome ? 1 : 0
});
});
});
handlers['category-update'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function (category) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
try {
await _db__WEBPACK_IMPORTED_MODULE_9__["updateCategory"](category);
} catch (e) {
if (e.message.toLowerCase().includes('unique constraint')) {
return {
error: {
type: 'category-exists'
}
};
}
throw e;
}
return {};
});
});
handlers['category-move'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
id,
groupId,
targetId
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
await Object(_sync__WEBPACK_IMPORTED_MODULE_29__["batchMessages"])(async () => {
await _db__WEBPACK_IMPORTED_MODULE_9__["moveCategory"](id, groupId, targetId);
});
return 'ok';
});
});
handlers['category-delete'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
id,
transferId
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
let result = {};
await Object(_sync__WEBPACK_IMPORTED_MODULE_29__["batchMessages"])(async () => {
let row = await _db__WEBPACK_IMPORTED_MODULE_9__["first"]('SELECT is_income FROM categories WHERE id = ?', [id]);
if (!row) {
result = {
error: 'no-categories'
};
return;
}
let transfer = transferId && (await _db__WEBPACK_IMPORTED_MODULE_9__["first"]('SELECT is_income FROM categories WHERE id = ?', [transferId]));
if (!row || transferId && !transfer) {
result = {
error: 'no-categories'
};
return;
} else if (transferId && row.is_income !== transfer.is_income) {
result = {
error: 'category-type'
};
return;
} // Update spreadsheet values if it's an expense category
// TODO: We should do this for income too if it's a reflect budget
if (row.is_income === 0) {
if (transferId) {
await _budget_base__WEBPACK_IMPORTED_MODULE_22__["doTransfer"]([id], transferId);
}
}
await _db__WEBPACK_IMPORTED_MODULE_9__["deleteCategory"]({
id
}, transferId);
});
return result;
});
});
handlers['category-group-create'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
name,
isIncome
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
return _db__WEBPACK_IMPORTED_MODULE_9__["insertCategoryGroup"]({
name,
is_income: isIncome ? 1 : 0
});
});
});
handlers['category-group-update'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function (group) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
return _db__WEBPACK_IMPORTED_MODULE_9__["updateCategoryGroup"](group);
});
});
handlers['category-group-move'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
id,
targetId
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
await Object(_sync__WEBPACK_IMPORTED_MODULE_29__["batchMessages"])(async () => {
await _db__WEBPACK_IMPORTED_MODULE_9__["moveCategoryGroup"](id, targetId);
});
return 'ok';
});
});
handlers['category-group-delete'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
id,
transferId
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
const groupCategories = await _db__WEBPACK_IMPORTED_MODULE_9__["all"]('SELECT id FROM categories WHERE cat_group = ? AND tombstone = 0', [id]);
return Object(_sync__WEBPACK_IMPORTED_MODULE_29__["batchMessages"])(async () => {
if (transferId) {
await _budget_base__WEBPACK_IMPORTED_MODULE_22__["doTransfer"](groupCategories.map(c => c.id), transferId);
}
await _db__WEBPACK_IMPORTED_MODULE_9__["deleteCategoryGroup"]({
id
}, transferId);
});
});
});
handlers['must-category-transfer'] = async function ({
id
}) {
const res = await _db__WEBPACK_IMPORTED_MODULE_9__["runQuery"](`SELECT count(t.id) as count FROM transactions t
LEFT JOIN category_mapping cm ON cm.id = t.category
WHERE cm.transferId = ? AND t.tombstone = 0`, [id], true); // If there are transactions with this category, return early since
// we already know it needs to be tranferred
if (res[0].count !== 0) {
return true;
} // If there are any non-zero budget values, also force the user to
// transfer the category.
return [..._sheet__WEBPACK_IMPORTED_MODULE_10__["get"]().meta().createdMonths].some(month => {
const sheetName = _shared_months__WEBPACK_IMPORTED_MODULE_20__["sheetForMonth"](month);
const value = _sheet__WEBPACK_IMPORTED_MODULE_10__["get"]().getCellValue(sheetName, 'budget-' + id);
return value !== 0;
});
};
handlers['payee-create'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
name
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
return _db__WEBPACK_IMPORTED_MODULE_9__["insertPayee"]({
name
});
});
});
handlers['payees-get'] = async function () {
return _db__WEBPACK_IMPORTED_MODULE_9__["getPayees"]();
};
handlers['payees-get-rule-counts'] = async function () {
let payeeCounts = {};
let allRules = _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["getRules"]();
_accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["iterateIds"](_accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["getRules"](), 'payee', (rule, id) => {
if (payeeCounts[id] == null) {
payeeCounts[id] = 0;
}
payeeCounts[id]++;
});
return payeeCounts;
};
handlers['payees-merge'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
targetId,
mergeIds
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
return _db__WEBPACK_IMPORTED_MODULE_9__["mergePayees"](targetId, mergeIds);
}, {
targetId,
mergeIds
});
});
handlers['payees-batch-change'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
added,
deleted,
updated
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
return Object(_sync__WEBPACK_IMPORTED_MODULE_29__["batchMessages"])(async () => {
if (deleted) {
await Promise.all(deleted.map(p => _db__WEBPACK_IMPORTED_MODULE_9__["deletePayee"](p)));
}
if (added) {
await Promise.all(added.map(p => _db__WEBPACK_IMPORTED_MODULE_9__["insertPayee"](p)));
}
if (updated) {
await Promise.all(updated.map(p => _db__WEBPACK_IMPORTED_MODULE_9__["updatePayee"](p)));
}
});
});
});
handlers['payees-check-orphaned'] = async function ({
ids
}) {
let orphaned = new Set(await _db__WEBPACK_IMPORTED_MODULE_9__["getOrphanedPayees"]());
return ids.filter(id => orphaned.has(id));
};
handlers['payees-get-rules'] = async function ({
id
}) {
return _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["getRulesForPayee"](id).map(rule => rule.serialize());
};
handlers['payees-delete-rule'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
id,
payee_id
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
return await _db__WEBPACK_IMPORTED_MODULE_9__["deletePayeeRule"]({
id
});
}, {
payeeId: payee_id
});
});
handlers['payees-update-rule'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function (rule) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
return await _db__WEBPACK_IMPORTED_MODULE_9__["updatePayeeRule"](rule);
}, {
payeeId: rule.payee_id
});
});
handlers['payees-add-rule'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function (rule) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
let id = await _db__WEBPACK_IMPORTED_MODULE_9__["insertPayeeRule"](rule);
return _objectSpread(_objectSpread({}, rule), {}, {
id
});
}, {
payeeId: rule.payee_id
});
});
function validateRule(rule) {
// Returns an array of errors, the array is the same link as the
// passed-in `array`, or null if there are no errors
function runValidation(array, validate) {
let result = array.map(item => {
try {
validate(item);
} catch (e) {
if (e instanceof _errors__WEBPACK_IMPORTED_MODULE_41__["RuleError"]) {
console.warn('Invalid rule', e);
return e.type;
}
throw e;
}
return null;
});
return result.some(Boolean) ? result : null;
}
let conditionErrors = runValidation(rule.conditions, cond => new _accounts_rules__WEBPACK_IMPORTED_MODULE_13__["Condition"](cond.op, cond.field, cond.value, cond.options, _shared_rules__WEBPACK_IMPORTED_MODULE_17__["FIELD_TYPES"]));
let actionErrors = runValidation(rule.actions, action => new _accounts_rules__WEBPACK_IMPORTED_MODULE_13__["Action"](action.op, action.field, action.value, action.options, _shared_rules__WEBPACK_IMPORTED_MODULE_17__["FIELD_TYPES"]));
if (conditionErrors || actionErrors) {
return {
conditionErrors,
actionErrors
};
}
return null;
}
handlers['rule-validate'] = async function (rule) {
let error = validateRule(rule);
return {
error
};
};
handlers['rule-add'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function (rule) {
let error = validateRule(rule);
if (error) {
return {
error
};
}
let id = await _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["insertRule"](rule);
return {
id
};
});
handlers['rule-update'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function (rule) {
let error = validateRule(rule);
if (error) {
return {
error
};
}
await _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["updateRule"](rule);
return {};
});
handlers['rule-delete'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function (rule) {
return _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["deleteRule"](rule);
});
handlers['rule-delete-all'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function (ids) {
let someDeletionsFailed = false;
await Object(_sync__WEBPACK_IMPORTED_MODULE_29__["batchMessages"])(async () => {
for (let id of ids) {
let res = await _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["deleteRule"]({
id
});
if (res === false) {
someDeletionsFailed = true;
}
}
});
return {
someDeletionsFailed
};
});
handlers['rule-apply-actions'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
transactionIds,
actions
}) {
return _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["applyActions"](transactionIds, actions, handlers);
});
handlers['rule-add-payee-rename'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
fromNames,
to
}) {
return _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["updatePayeeRenameRule"](fromNames, to);
});
handlers['rules-get'] = async function () {
return Object(_accounts_rules__WEBPACK_IMPORTED_MODULE_13__["rankRules"])(_accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["getRules"]()).map(rule => rule.serialize());
};
handlers['rule-get'] = async function ({
id
}) {
let rule = _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["getRules"]().find(rule => rule.id === id);
return rule ? rule.serialize() : null;
};
handlers['rules-run'] = async function ({
transaction
}) {
return _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["runRules"](transaction);
};
handlers['rules-migrate'] = async function () {
await _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["migrateOldRules"]();
};
handlers['make-filters-from-conditions'] = async function ({
conditions
}) {
return _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["conditionsToAQL"](conditions);
};
handlers['getCell'] = async function ({
sheetName,
name
}) {
// Fields is no longer used - hardcode
let fields = ['name', 'value'];
let node = _sheet__WEBPACK_IMPORTED_MODULE_10__["get"]()._getNode(resolveName(sheetName, name));
if (fields) {
let res = {};
fields.forEach(field => {
if (field === 'run') {
res[field] = node._run ? node._run.toString() : null;
} else {
res[field] = node[field];
}
});
return res;
} else {
return node;
}
};
handlers['getCells'] = async function ({
names
}) {
return names.map(name => ({
value: _sheet__WEBPACK_IMPORTED_MODULE_10__["get"]()._getNode(name).value
}));
};
handlers['getCellNamesInSheet'] = async function ({
sheetName
}) {
let names = [];
for (let name of _sheet__WEBPACK_IMPORTED_MODULE_10__["get"]().getNodes().keys()) {
let _unresolveName = unresolveName(name),
nodeSheet = _unresolveName.sheet,
nodeName = _unresolveName.name;
if (nodeSheet === sheetName) {
names.push(nodeName);
}
}
return names;
};
handlers['debugCell'] = async function ({
sheetName,
name
}) {
let node = _sheet__WEBPACK_IMPORTED_MODULE_10__["get"]().getNode(resolveName(sheetName, name));
return _objectSpread(_objectSpread({}, node), {}, {
_run: node._run && node._run.toString()
});
};
handlers['create-query'] = async function ({
sheetName,
name,
query
}) {
// Always run it regardless of cache. We don't know anything has changed
// between the cache value being saved and now
_sheet__WEBPACK_IMPORTED_MODULE_10__["get"]().createQuery(sheetName, name, query);
return 'ok';
};
handlers['query'] = async function (query) {
if (query.table == null) {
throw new Error('query has no table, did you forgot to call `.serialize`?');
}
return Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_43__["runQuery"])(query);
};
handlers['bank-delete'] = async function ({
id
}) {
const accts = await _db__WEBPACK_IMPORTED_MODULE_9__["runQuery"]('SELECT * FROM accounts WHERE bank = ?', [id], true);
await _db__WEBPACK_IMPORTED_MODULE_9__["delete_"]('banks', id);
await Promise.all(accts.map(async acct => {
// TODO: This will not sync across devices because we are bypassing
// the "recorded" functions
await _db__WEBPACK_IMPORTED_MODULE_9__["runQuery"]('DELETE FROM transactions WHERE acct = ?', [acct.id]);
await _db__WEBPACK_IMPORTED_MODULE_9__["delete_"]('accounts', acct.id);
}));
return 'ok';
};
handlers['account-update'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
id,
name
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
await _db__WEBPACK_IMPORTED_MODULE_9__["update"]('accounts', {
id,
name
});
return {};
});
});
handlers['accounts-get'] = async function () {
return _db__WEBPACK_IMPORTED_MODULE_9__["getAccounts"]();
};
handlers['account-properties'] = async function ({
id
}) {
const _await$db$first = await _db__WEBPACK_IMPORTED_MODULE_9__["first"]('SELECT sum(amount) as balance FROM transactions WHERE acct = ? AND isParent = 0 AND tombstone = 0', [id]),
balance = _await$db$first.balance;
const _await$db$first2 = await _db__WEBPACK_IMPORTED_MODULE_9__["first"]('SELECT count(id) as count FROM transactions WHERE acct = ? AND tombstone = 0', [id]),
count = _await$db$first2.count;
return {
balance: balance || 0,
numTransactions: count
};
};
handlers['accounts-link'] = async function ({
institution,
publicToken,
accountId,
upgradingId
}) {
let bankId = await _accounts_link__WEBPACK_IMPORTED_MODULE_24__["handoffPublicToken"](institution, publicToken);
let _await$asyncStorage$m = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.multiGet(['user-id', 'user-key']),
_await$asyncStorage$m2 = _slicedToArray(_await$asyncStorage$m, 2),
_await$asyncStorage$m3 = _slicedToArray(_await$asyncStorage$m2[0], 2),
userId = _await$asyncStorage$m3[1],
_await$asyncStorage$m4 = _slicedToArray(_await$asyncStorage$m2[1], 2),
userKey = _await$asyncStorage$m4[1]; // Get all the available accounts and find the selected one
let accounts = await _accounts_sync__WEBPACK_IMPORTED_MODULE_23__["getAccounts"](userId, userKey, bankId);
let account = accounts.find(acct => acct.account_id === accountId);
await _db__WEBPACK_IMPORTED_MODULE_9__["update"]('accounts', {
id: upgradingId,
account_id: account.account_id,
official_name: account.official_name,
type: Object(_shared_accounts__WEBPACK_IMPORTED_MODULE_21__["fromPlaidAccountType"])(account.type),
balance_current: Object(_shared_util__WEBPACK_IMPORTED_MODULE_19__["amountToInteger"])(account.balances.current),
balance_available: Object(_shared_util__WEBPACK_IMPORTED_MODULE_19__["amountToInteger"])(account.balances.available),
balance_limit: Object(_shared_util__WEBPACK_IMPORTED_MODULE_19__["amountToInteger"])(account.balances.limit),
mask: account.mask,
bank: bankId
});
await _accounts_sync__WEBPACK_IMPORTED_MODULE_23__["syncAccount"](userId, userKey, upgradingId, account.account_id, bankId);
connection.send('sync-event', {
type: 'success',
tables: ['transactions']
});
return 'ok';
};
handlers['accounts-connect'] = async function ({
institution,
publicToken,
accountIds,
offbudgetIds
}) {
let bankId = await _accounts_link__WEBPACK_IMPORTED_MODULE_24__["handoffPublicToken"](institution, publicToken);
let ids = await _accounts_link__WEBPACK_IMPORTED_MODULE_24__["addAccounts"](bankId, accountIds, offbudgetIds);
return ids;
};
handlers['account-create'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
name,
type,
balance,
offBudget,
closed
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
const id = await _db__WEBPACK_IMPORTED_MODULE_9__["insertAccount"]({
name,
type,
offbudget: offBudget ? 1 : 0,
closed: closed ? 1 : 0
});
await _db__WEBPACK_IMPORTED_MODULE_9__["insertPayee"]({
name: '',
transfer_acct: id
});
if (balance != null) {
let payee = await Object(_accounts_payees__WEBPACK_IMPORTED_MODULE_31__["getStartingBalancePayee"])();
await _db__WEBPACK_IMPORTED_MODULE_9__["insertTransaction"]({
account: id,
amount: Object(_shared_util__WEBPACK_IMPORTED_MODULE_19__["amountToInteger"])(balance),
category: offBudget ? null : payee.category,
payee: payee.id,
date: _shared_months__WEBPACK_IMPORTED_MODULE_20__["currentDay"](),
cleared: true,
starting_balance_flag: true
});
}
return id;
});
});
handlers['account-close'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
id,
transferAccountId,
categoryId,
forced
}) {
// Unlink the account if it's linked. This makes sure to remove it
// from Plaid. (This should not be undo-able, as it mutates the
// remote server and the user will have to link the account again)
await handlers['account-unlink']({
id
});
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
let account = await _db__WEBPACK_IMPORTED_MODULE_9__["first"]('SELECT * FROM accounts WHERE id = ? AND tombstone = 0', [id]); // Do nothing if the account doesn't exist or it's already been
// closed
if (!account || account.closed === 1) {
return;
}
const _await$handlers$accou = await handlers['account-properties']({
id
}),
balance = _await$handlers$accou.balance,
numTransactions = _await$handlers$accou.numTransactions; // If there are no transactions, we can simply delete the account
if (numTransactions === 0) {
await _db__WEBPACK_IMPORTED_MODULE_9__["deleteAccount"]({
id
});
} else if (forced) {
let rows = await _db__WEBPACK_IMPORTED_MODULE_9__["runQuery"]('SELECT id, transfer_id FROM v_transactions WHERE account = ?', [id], true);
let _await$db$first3 = await _db__WEBPACK_IMPORTED_MODULE_9__["first"]('SELECT id FROM payees WHERE transfer_acct = ?', [id]),
payeeId = _await$db$first3.id;
await Object(_sync__WEBPACK_IMPORTED_MODULE_29__["batchMessages"])(() => {
// TODO: what this should really do is send a special message that
// automatically marks the tombstone value for all transactions
// within an account... or something? This is problematic
// because another client could easily add new data that
// should be marked as deleted.
rows.forEach(row => {
if (row.transfer_id) {
_db__WEBPACK_IMPORTED_MODULE_9__["updateTransaction"]({
id: row.transfer_id,
payee: null,
transfer_id: null
});
}
_db__WEBPACK_IMPORTED_MODULE_9__["deleteTransaction"]({
id: row.id
});
});
_db__WEBPACK_IMPORTED_MODULE_9__["deleteAccount"]({
id
});
_db__WEBPACK_IMPORTED_MODULE_9__["deleteTransferPayee"]({
id: payeeId
});
});
} else {
if (balance !== 0 && transferAccountId == null) {
throw Object(_errors__WEBPACK_IMPORTED_MODULE_41__["APIError"])('balance is non-zero: transferAccountId is required');
}
await _db__WEBPACK_IMPORTED_MODULE_9__["update"]('accounts', {
id,
closed: 1
}); // If there is a balance we need to transfer it to the specified
// account (and possibly categorize it)
if (balance !== 0) {
let _await$db$first4 = await _db__WEBPACK_IMPORTED_MODULE_9__["first"]('SELECT id FROM payees WHERE transfer_acct = ?', [transferAccountId]),
payeeId = _await$db$first4.id;
await handlers['transaction-add']({
id: uuid.v4Sync(),
payee: payeeId,
amount: -balance,
account: id,
date: _shared_months__WEBPACK_IMPORTED_MODULE_20__["currentDay"](),
notes: 'Closing account',
category: categoryId || null
});
}
}
});
});
handlers['account-reopen'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
id
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
await _db__WEBPACK_IMPORTED_MODULE_9__["update"]('accounts', {
id,
closed: 0
});
});
});
handlers['account-move'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
id,
targetId
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
await _db__WEBPACK_IMPORTED_MODULE_9__["moveAccount"](id, targetId);
});
});
let stopPolling = false;
handlers['poll-web-token'] = async function ({
token
}) {
let _await$asyncStorage$m5 = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.multiGet(['user-id', 'user-key']),
_await$asyncStorage$m6 = _slicedToArray(_await$asyncStorage$m5, 2),
_await$asyncStorage$m7 = _slicedToArray(_await$asyncStorage$m6[0], 2),
userId = _await$asyncStorage$m7[1],
_await$asyncStorage$m8 = _slicedToArray(_await$asyncStorage$m6[1], 2),
key = _await$asyncStorage$m8[1];
let startTime = Date.now();
stopPolling = false;
async function getData(cb) {
if (stopPolling) {
return;
}
if (Date.now() - startTime >= 1000 * 60 * 10) {
cb('timeout');
return;
}
let data = await Object(_post__WEBPACK_IMPORTED_MODULE_40__["post"])(Object(_config__WEBPACK_IMPORTED_MODULE_34__["getConfig"])().PLAID_SERVER + '/get-web-token-contents', {
userId,
key,
token
});
if (data) {
if (data.error) {
cb('unknown');
} else {
cb(null, data);
}
} else {
setTimeout(() => getData(cb), 3000);
}
}
return new Promise(resolve => {
getData((error, data) => {
if (error) {
resolve({
error
});
} else {
resolve({
data
});
}
});
});
};
handlers['poll-web-token-stop'] = async function () {
stopPolling = true;
return 'ok';
};
handlers['accounts-sync'] = async function ({
id
}) {
let _await$asyncStorage$m9 = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.multiGet(['user-id', 'user-key']),
_await$asyncStorage$m10 = _slicedToArray(_await$asyncStorage$m9, 2),
_await$asyncStorage$m11 = _slicedToArray(_await$asyncStorage$m10[0], 2),
userId = _await$asyncStorage$m11[1],
_await$asyncStorage$m12 = _slicedToArray(_await$asyncStorage$m10[1], 2),
userKey = _await$asyncStorage$m12[1];
let accounts = await _db__WEBPACK_IMPORTED_MODULE_9__["runQuery"](`SELECT a.*, b.id as bankId FROM accounts a
LEFT JOIN banks b ON a.bank = b.id
WHERE a.tombstone = 0 AND a.closed = 0`, [], true);
if (id) {
accounts = accounts.filter(acct => acct.id === id);
}
let errors = [];
let newTransactions = [];
let matchedTransactions = [];
let updatedAccounts = [];
let _prefs$getPrefs = _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"](),
groupId = _prefs$getPrefs.groupId;
for (var i = 0; i < accounts.length; i++) {
const acct = accounts[i];
if (acct.bankId) {
try {
const res = await _accounts_sync__WEBPACK_IMPORTED_MODULE_23__["syncAccount"](userId, userKey, acct.id, acct.account_id, acct.bankId);
let added = res.added,
updated = res.updated;
newTransactions = newTransactions.concat(added);
matchedTransactions = matchedTransactions.concat(updated);
if (added.length > 0 || updated.length > 0) {
updatedAccounts = updatedAccounts.concat(acct.id);
}
} catch (err) {
if (err.type === 'BankSyncError') {
errors.push({
type: 'SyncError',
accountId: acct.id,
message: 'Failed syncing account "' + acct.name + '".',
category: err.category,
code: err.code
});
} else if (err instanceof _errors__WEBPACK_IMPORTED_MODULE_41__["PostError"] && err.reason !== 'internal') {
errors.push({
accountId: acct.id,
message: `Account "${acct.name}" is not linked properly. Please link it again`
});
} else {
errors.push({
accountId: acct.id,
message: 'There was an internal error. Please email help@actualbudget.com for support.',
internal: err.stack
});
err.message = 'Failed syncing account: ' + err.message;
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_3__["captureException"])(err);
}
}
}
}
if (updatedAccounts.length > 0) {
connection.send('sync-event', {
type: 'success',
tables: ['transactions']
});
}
return {
errors,
newTransactions,
matchedTransactions,
updatedAccounts
};
};
handlers['transactions-import'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(function ({
accountId,
transactions
}) {
return Object(_undo__WEBPACK_IMPORTED_MODULE_11__["withUndo"])(async () => {
if (typeof accountId !== 'string') {
throw Object(_errors__WEBPACK_IMPORTED_MODULE_41__["APIError"])('transactions-import: accountId must be an id');
}
try {
return await _accounts_sync__WEBPACK_IMPORTED_MODULE_23__["reconcileTransactions"](accountId, transactions);
} catch (err) {
if (err instanceof _errors__WEBPACK_IMPORTED_MODULE_41__["TransactionError"]) {
return {
errors: [{
message: err.message
}],
added: [],
updated: []
};
}
throw err;
}
});
});
handlers['account-unlink'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function ({
id
}) {
let _await$db$first5 = await _db__WEBPACK_IMPORTED_MODULE_9__["first"]('SELECT bank FROM accounts WHERE id = ?', [id]),
bankId = _await$db$first5.bank;
if (!bankId) {
return 'ok';
}
await _db__WEBPACK_IMPORTED_MODULE_9__["updateAccount"]({
id,
account_id: null,
bank: null,
balance_current: null,
balance_available: null,
balance_limit: null
});
let _await$db$first6 = await _db__WEBPACK_IMPORTED_MODULE_9__["first"]('SELECT COUNT(*) as count FROM accounts WHERE bank = ?', [bankId]),
count = _await$db$first6.count;
if (count === 0) {
// No more accounts are associated with this bank. We can remove
// it from Plaid.
let _await$asyncStorage$m13 = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.multiGet(['user-id', 'user-key']),
_await$asyncStorage$m14 = _slicedToArray(_await$asyncStorage$m13, 2),
_await$asyncStorage$m15 = _slicedToArray(_await$asyncStorage$m14[0], 2),
userId = _await$asyncStorage$m15[1],
_await$asyncStorage$m16 = _slicedToArray(_await$asyncStorage$m14[1], 2),
key = _await$asyncStorage$m16[1];
await Object(_post__WEBPACK_IMPORTED_MODULE_40__["post"])(Object(_config__WEBPACK_IMPORTED_MODULE_34__["getConfig"])().PLAID_SERVER + '/remove-access-token', {
userId,
key,
item_id: bankId
});
}
return 'ok';
});
handlers['make-plaid-public-token'] = async function ({
bankId
}) {
let _await$asyncStorage$m17 = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.multiGet(['user-id', 'user-key']),
_await$asyncStorage$m18 = _slicedToArray(_await$asyncStorage$m17, 2),
_await$asyncStorage$m19 = _slicedToArray(_await$asyncStorage$m18[0], 2),
userId = _await$asyncStorage$m19[1],
_await$asyncStorage$m20 = _slicedToArray(_await$asyncStorage$m18[1], 2),
userKey = _await$asyncStorage$m20[1];
let data = await Object(_post__WEBPACK_IMPORTED_MODULE_40__["post"])(Object(_config__WEBPACK_IMPORTED_MODULE_34__["getConfig"])().PLAID_SERVER + '/make-public-token', {
userId: userId,
key: userKey,
item_id: '' + bankId
});
if (data.error_code) {
return {
error: '',
code: data.error_code,
type: data.error_type
};
}
return {
linkToken: data.link_token
};
};
handlers['save-global-prefs'] = async function (prefs) {
if ('maxMonths' in prefs) {
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('max-months', '' + prefs.maxMonths);
}
if ('trackUsage' in prefs) {
_tracking_events__WEBPACK_IMPORTED_MODULE_39__["toggle"](prefs.trackUsage);
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('track-usage', '' + prefs.trackUsage);
}
if ('autoUpdate' in prefs) {
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('auto-update', '' + prefs.autoUpdate);
process.send({
type: 'shouldAutoUpdate',
flag: prefs.autoUpdate
});
}
if ('documentDir' in prefs) {
if (await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.exists(prefs.documentDir)) {
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('document-dir', prefs.documentDir);
}
}
if ('floatingSidebar' in prefs) {
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('floating-sidebar', '' + prefs.floatingSidebar);
}
return 'ok';
};
handlers['load-global-prefs'] = async function () {
let _await$asyncStorage$m21 = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.multiGet(['floating-sidebar', 'seen-tutorial', 'max-months', 'track-usage', 'auto-update', 'document-dir', 'encrypt-key']),
_await$asyncStorage$m22 = _slicedToArray(_await$asyncStorage$m21, 7),
_await$asyncStorage$m23 = _slicedToArray(_await$asyncStorage$m22[0], 2),
floatingSidebar = _await$asyncStorage$m23[1],
_await$asyncStorage$m24 = _slicedToArray(_await$asyncStorage$m22[1], 2),
seenTutorial = _await$asyncStorage$m24[1],
_await$asyncStorage$m25 = _slicedToArray(_await$asyncStorage$m22[2], 2),
maxMonths = _await$asyncStorage$m25[1],
_await$asyncStorage$m26 = _slicedToArray(_await$asyncStorage$m22[3], 2),
trackUsage = _await$asyncStorage$m26[1],
_await$asyncStorage$m27 = _slicedToArray(_await$asyncStorage$m22[4], 2),
autoUpdate = _await$asyncStorage$m27[1],
_await$asyncStorage$m28 = _slicedToArray(_await$asyncStorage$m22[5], 2),
documentDir = _await$asyncStorage$m28[1],
_await$asyncStorage$m29 = _slicedToArray(_await$asyncStorage$m22[6], 2),
encryptKey = _await$asyncStorage$m29[1];
return {
floatingSidebar: floatingSidebar === 'true' ? true : false,
seenTutorial: seenTutorial === 'true' ? true : false,
maxMonths: Object(_shared_util__WEBPACK_IMPORTED_MODULE_19__["stringToInteger"])(maxMonths || ''),
// Default to true
trackUsage: trackUsage == null || trackUsage === 'true' ? true : false,
autoUpdate: autoUpdate == null || autoUpdate === 'true' ? true : false,
documentDir: documentDir || getDefaultDocumentDir(),
keyId: encryptKey && JSON.parse(encryptKey).id
};
};
handlers['save-prefs'] = async function (prefsToSet) {
let _prefs$getPrefs2 = _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"](),
cloudFileId = _prefs$getPrefs2.cloudFileId; // Need to sync the budget name on the server as well
if (prefsToSet.budgetName && cloudFileId) {
let userToken = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.getItem('user-token');
await Object(_post__WEBPACK_IMPORTED_MODULE_40__["post"])(Object(_config__WEBPACK_IMPORTED_MODULE_34__["getConfig"])().SYNC_SERVER + '/update-user-filename', {
token: userToken,
fileId: cloudFileId,
name: prefsToSet.budgetName
});
}
await _prefs__WEBPACK_IMPORTED_MODULE_4__["savePrefs"](prefsToSet);
return 'ok';
};
handlers['load-prefs'] = async function () {
return _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]();
};
handlers['sync-reset'] = async function () {
return await Object(_sync__WEBPACK_IMPORTED_MODULE_29__["resetSync"])();
};
handlers['sync-repair'] = async function () {
await Object(_sync__WEBPACK_IMPORTED_MODULE_29__["repairSync"])();
}; // A user can only enable/change their key with the file loaded. This
// will change in the future: during onboarding the user should be
// able to enable encryption. (Imagine if they are importing data from
// another source, they should be able to encrypt first)
handlers['key-make'] = async function ({
password
}) {
if (!_prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]()) {
throw new Error('user-set-key must be called with file loaded');
}
let cloudFileId = _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]().cloudFileId;
let salt = _encryption__WEBPACK_IMPORTED_MODULE_38__["default"].randomBytes(32).toString('base64');
let id = uuid.v4Sync();
let key = await _encryption__WEBPACK_IMPORTED_MODULE_38__["default"].createKey({
id,
password,
salt
}); // Load the key
await _encryption__WEBPACK_IMPORTED_MODULE_38__["default"].loadKey(key); // Make some test data to use if the key is valid or not
let testContent = await Object(_sync__WEBPACK_IMPORTED_MODULE_29__["makeTestMessage"])(key.getId()); // Changing your key necessitates a sync reset as well. This will
// clear all existing encrypted data from the server so you won't
// have a mix of data encrypted with different keys.
return await Object(_sync__WEBPACK_IMPORTED_MODULE_29__["resetSync"])({
key,
salt,
testContent: JSON.stringify(_objectSpread(_objectSpread({}, testContent), {}, {
value: testContent.value.toString('base64')
}))
});
}; // This can be called both while a file is already loaded or not. This
// will see if a key is valid and if so save it off.
handlers['key-test'] = async function ({
fileId,
password
}) {
let userToken = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.getItem('user-token');
if (fileId == null) {
fileId = _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]().cloudFileId;
}
let res;
try {
res = await Object(_post__WEBPACK_IMPORTED_MODULE_40__["post"])(Object(_config__WEBPACK_IMPORTED_MODULE_34__["getConfig"])().SYNC_SERVER + '/user-get-key', {
token: userToken,
fileId
});
} catch (e) {
console.log(e);
return {
error: {
reason: 'network'
}
};
}
let _res = res,
id = _res.id,
salt = _res.salt,
test = _res.test;
if (test == null) {
return {
error: {
reason: 'old-key-style'
}
};
}
test = JSON.parse(test);
let key = await _encryption__WEBPACK_IMPORTED_MODULE_38__["default"].createKey({
id,
password,
salt
});
_encryption__WEBPACK_IMPORTED_MODULE_38__["default"].loadKey(key);
try {
await _encryption__WEBPACK_IMPORTED_MODULE_38__["default"].decrypt(Buffer.from(test.value, 'base64'), test.meta);
} catch (e) {
console.log(e); // Unload the key, it's invalid
_encryption__WEBPACK_IMPORTED_MODULE_38__["default"].unloadKey(key);
return {
error: {
reason: 'decrypt-failure'
}
};
} // Persist key in async storage
let keys = JSON.parse((await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.getItem(`encrypt-keys`)) || '{}');
keys[fileId] = key.serialize();
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('encrypt-keys', JSON.stringify(keys)); // Save the key id in prefs if the are loaded. If they aren't, we
// are testing a key to download a file and when the file is
// actually downloaded it will update the prefs with the latest key id
if (_prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]()) {
await _prefs__WEBPACK_IMPORTED_MODULE_4__["savePrefs"]({
encryptKeyId: key.getId()
});
}
return {};
};
handlers['should-pitch-subscribe'] = async function () {
let seenSubscribe = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.getItem('seenSubscribe');
return seenSubscribe !== 'true';
};
handlers['has-pitched-subscribe'] = async function () {
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('seenSubscribe', 'true');
return 'ok';
};
handlers['subscribe-set-user'] = async function ({
token
}) {
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('user-token', token);
};
handlers['subscribe-get-user'] = async function () {
let userToken = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.getItem('user-token');
if (userToken) {
try {
let res = await Object(_post__WEBPACK_IMPORTED_MODULE_40__["post"])(Object(_config__WEBPACK_IMPORTED_MODULE_34__["getConfig"])().SIGNUP_SERVER + '/account', {
token: userToken
});
return {
offline: false
};
} catch (e) {
// The server responded successfully, but the user isn't found.
// Could be a server problem, but most likely in development we
// are switching between staging/prod
if (e.reason === 'unauthorized') {
return null;
} // Worse case, return the user id so the frontend knows the user
// has been logged in.
return {
offline: true
};
}
}
return null;
};
handlers['subscribe-sign-in'] = async function ({
password
}) {
let res = await Object(_post__WEBPACK_IMPORTED_MODULE_40__["post"])(Object(_config__WEBPACK_IMPORTED_MODULE_34__["getConfig"])().SIGNUP_SERVER + '/login', {
password
});
if (res.token) {
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('user-token', res.token);
return {};
}
return {
error: 'invalid-password'
};
};
handlers['subscribe-sign-out'] = async function () {
_encryption__WEBPACK_IMPORTED_MODULE_38__["default"].unloadAllKeys();
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.multiRemove(['user-token', 'encrypt-keys', 'lastBudget', 'readOnly']);
return 'ok';
};
handlers['sync'] = async function () {
return Object(_sync__WEBPACK_IMPORTED_MODULE_29__["fullSync"])();
};
handlers['get-version'] = async function () {
return {
version: VERSION
};
};
handlers['get-budgets'] = async function () {
const paths = await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.listDir(_platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.getDocumentDir());
const budgets = (await Promise.all(paths.map(async name => {
const prefsPath = _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.join(_platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.getDocumentDir(), name, 'metadata.json');
if (await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.exists(prefsPath)) {
let prefs;
try {
prefs = JSON.parse(await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.readFile(prefsPath));
} catch (e) {
console.log('Error parsing metadata:', e.stack);
return;
} // We treat the directory name as the canonical id so that if
// the user moves it around/renames/etc, nothing breaks. The
// id is stored in prefs just for convenience (and the prefs
// will always update to the latest given id)
if (name !== DEMO_BUDGET_ID) {
return {
id: name,
cloudFileId: prefs.cloudFileId,
groupId: prefs.groupId,
name: prefs.budgetName || '(no name)'
};
}
}
return null;
}))).filter(x => x);
return budgets;
};
handlers['get-ynab4-files'] = async function () {
return YNAB4.findBudgets();
};
handlers['get-remote-files'] = async function () {
return _cloud_storage__WEBPACK_IMPORTED_MODULE_37__["listRemoteFiles"]();
};
handlers['reset-budget-cache'] = Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["mutator"])(async function () {
// Recomputing everything will update the cache
await _sheet__WEBPACK_IMPORTED_MODULE_10__["loadUserBudgets"](_db__WEBPACK_IMPORTED_MODULE_9__);
_sheet__WEBPACK_IMPORTED_MODULE_10__["get"]().recomputeAll();
await _sheet__WEBPACK_IMPORTED_MODULE_10__["waitOnSpreadsheet"]();
});
handlers['upload-budget'] = async function ({
id
} = {}) {
if (id) {
if (_prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]()) {
throw new Error('upload-budget: id given but prefs already loaded');
}
await _prefs__WEBPACK_IMPORTED_MODULE_4__["loadPrefs"](id);
}
try {
await _cloud_storage__WEBPACK_IMPORTED_MODULE_37__["upload"]();
} catch (e) {
console.log(e);
if (e.type === 'FileUploadError') {
return {
error: e
};
}
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_3__["captureException"])(e);
return {
error: {
reason: 'internal'
}
};
} finally {
if (id) {
_prefs__WEBPACK_IMPORTED_MODULE_4__["unloadPrefs"]();
}
}
return {};
};
handlers['download-budget'] = async function ({
fileId,
replace
}) {
let result;
try {
result = await _cloud_storage__WEBPACK_IMPORTED_MODULE_37__["download"](fileId, replace);
} catch (e) {
if (e.type === 'FileDownloadError') {
if (e.reason === 'file-exists' && e.meta.id) {
await _prefs__WEBPACK_IMPORTED_MODULE_4__["loadPrefs"](e.meta.id);
let name = _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]().budgetName;
_prefs__WEBPACK_IMPORTED_MODULE_4__["unloadPrefs"]();
e.meta = _objectSpread(_objectSpread({}, e.meta), {}, {
name
});
}
return {
error: e
};
} else {
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_3__["captureException"])(e);
return {
error: {
reason: 'internal'
}
};
}
}
let id = result.id; // Load the budget and do a full sync
result = await loadBudget(result.id, VERSION, {
showUpdate: true
});
if (result.error) {
return {
error: {
reason: result.error
}
};
}
Object(_sync__WEBPACK_IMPORTED_MODULE_29__["setSyncingMode"])('enabled');
await Object(_sync__WEBPACK_IMPORTED_MODULE_29__["initialFullSync"])();
await handlers['close-budget']();
return {
id
};
};
handlers['load-budget'] = async function ({
id
}) {
let currentPrefs = _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]();
if (currentPrefs) {
if (currentPrefs.id === id) {
// If it's already loaded, do nothing
return {};
} else {
// Otherwise, close the currently loaded budget
await handlers['close-budget']();
}
}
let res = await loadBudget(id, VERSION, {
showUpdate: true
});
async function trackSizes() {
let getFileSize = async name => {
let dbFile = _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.join(_platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.getBudgetDir(id), name);
try {
return await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.size(dbFile);
} catch (err) {
return null;
}
};
try {
let dbSize = await getFileSize('db.sqlite');
let cacheSize = await getFileSize('cache.sqlite');
_tracking_events__WEBPACK_IMPORTED_MODULE_39__["track"]('app:load-budget', {
size: dbSize,
cacheSize
});
} catch (err) {
console.warn(err);
}
}
trackSizes();
return res;
};
handlers['create-demo-budget'] = async function () {
// Make sure the read only flag isn't leftover (normally it's
// reset when signing in, but you don't have to sign in for the
// demo budget)
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('readOnly', '');
return handlers['create-budget']({
budgetName: 'Demo Budget',
testMode: true,
testBudgetId: DEMO_BUDGET_ID
});
};
handlers['close-budget'] = async function () {
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_3__["captureBreadcrumb"])({
message: 'Closing budget'
}); // The spreadsheet may be running, wait for it to complete
await _sheet__WEBPACK_IMPORTED_MODULE_10__["waitOnSpreadsheet"]();
_sheet__WEBPACK_IMPORTED_MODULE_10__["unloadSpreadsheet"]();
Object(_sync__WEBPACK_IMPORTED_MODULE_29__["clearFullSyncTimeout"])();
await _main_app__WEBPACK_IMPORTED_MODULE_45__["default"].stopServices();
await _db__WEBPACK_IMPORTED_MODULE_9__["closeDatabase"]();
try {
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('lastBudget', '');
} catch (e) {// This might fail if we are shutting down after failing to load a
// budget. We want to unload whatever has already been loaded but
// be resilient to anything failing
}
_prefs__WEBPACK_IMPORTED_MODULE_4__["unloadPrefs"]();
Object(_backups__WEBPACK_IMPORTED_MODULE_18__["stopBackupService"])();
return 'ok';
};
handlers['delete-budget'] = async function ({
id,
cloudFileId
}) {
// If it's a cloud file, you can delete it from the server by
// passing its cloud id
if (cloudFileId && !process.env.IS_BETA) {
await _cloud_storage__WEBPACK_IMPORTED_MODULE_37__["removeFile"](cloudFileId).catch(err => {});
} // If a local file exists, you can delete it by passing its local id
if (id) {
let budgetDir = _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.getBudgetDir(id);
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.removeDirRecursively(budgetDir);
}
return 'ok';
};
handlers['create-budget'] = async function ({
budgetName,
avoidUpload,
testMode,
testBudgetId
} = {}) {
let id;
if (testMode) {
budgetName = budgetName || 'Test Budget';
id = testBudgetId || TEST_BUDGET_ID;
if (await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.exists(_platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.getBudgetDir(id))) {
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.removeDirRecursively(_platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.getBudgetDir(id));
}
} else {
// Generate budget name if not given
if (!budgetName) {
// Unfortunately we need to load all of the existing files first
// so we can detect conflicting names.
let files = await handlers['get-budgets']();
budgetName = await Object(_util_budget_name__WEBPACK_IMPORTED_MODULE_25__["uniqueFileName"])(files);
}
id = await Object(_util_budget_name__WEBPACK_IMPORTED_MODULE_25__["idFromFileName"])(budgetName);
}
let budgetDir = _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.getBudgetDir(id);
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.mkdir(budgetDir); // Create the initial database
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.copyFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.bundledDatabasePath, _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.join(budgetDir, 'db.sqlite')); // Create the initial prefs file
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.writeFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.join(budgetDir, 'metadata.json'), JSON.stringify(_prefs__WEBPACK_IMPORTED_MODULE_4__["getDefaultPrefs"](id, budgetName))); // Load it in
let _await$loadBudget = await loadBudget(id, VERSION),
error = _await$loadBudget.error;
if (error) {
console.log('Error creating budget: ' + error);
return {
error
};
}
if (!avoidUpload && !testMode) {
try {
await _cloud_storage__WEBPACK_IMPORTED_MODULE_37__["upload"]();
} catch (e) {// Ignore any errors uploading. If they are offline they should
// still be able to create files.
}
}
if (testMode) {
await Object(_mocks_budget__WEBPACK_IMPORTED_MODULE_42__["createTestBudget"])(handlers);
}
return {};
};
handlers['set-tutorial-seen'] = async function () {
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('seen-tutorial', 'true');
return 'ok';
};
handlers['import-budget'] = async function ({
filepath,
type
}) {
try {
if (!(await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.exists(filepath))) {
throw new Error(`File not found at the provided path: ${filepath}`);
}
let buffer = Buffer.from(await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.readFile(filepath, 'binary'));
switch (type) {
case 'ynab4':
try {
await YNAB4.importBuffer(filepath, buffer);
} catch (e) {
let msg = e.message.toLowerCase();
if (msg.includes('not a ynab4') || msg.includes('could not find file')) {
return {
error: 'not-ynab4'
};
}
}
break;
case 'ynab5':
let data;
try {
data = JSON.parse(buffer.toString());
} catch (e) {
return {
error: 'parse-error'
};
}
try {
await YNAB5.importYNAB5(data);
} catch (e) {
return {
error: 'not-ynab5'
};
}
break;
default:
}
} catch (err) {
err.message = 'Error importing budget: ' + err.message;
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_3__["captureException"])(err);
return {
error: 'internal-error'
};
}
return {};
};
handlers['export-budget'] = async function () {
return await _cloud_storage__WEBPACK_IMPORTED_MODULE_37__["exportBuffer"]();
};
async function loadBudget(id, appVersion, {
showUpdate
} = {}) {
let dir;
try {
dir = _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.getBudgetDir(id);
} catch (e) {
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_3__["captureException"])(new Error('`getBudgetDir` failed in `loadBudget`: ' + e.message));
return {
error: 'budget-not-found'
};
}
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_3__["captureBreadcrumb"])({
message: 'Loading budget ' + dir
});
if (!(await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.exists(dir))) {
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_3__["captureException"])(new Error('budget directory does not exist'));
return {
error: 'budget-not-found'
};
}
try {
await _prefs__WEBPACK_IMPORTED_MODULE_4__["loadPrefs"](id);
await _db__WEBPACK_IMPORTED_MODULE_9__["openDatabase"](id);
} catch (e) {
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_3__["captureBreadcrumb"])({
message: 'Error loading budget ' + id
});
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_3__["captureException"])(e);
await handlers['close-budget']();
return {
error: 'opening-budget'
};
} // Older versions didn't tag the file with the current user, so do
// so now
if (!_prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]().userId) {
let _await$asyncStorage$m30 = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.multiGet(['user-token']),
_await$asyncStorage$m31 = _slicedToArray(_await$asyncStorage$m30, 1),
_await$asyncStorage$m32 = _slicedToArray(_await$asyncStorage$m31[0], 2),
userId = _await$asyncStorage$m32[1];
_prefs__WEBPACK_IMPORTED_MODULE_4__["savePrefs"]({
userId
});
}
let _prefs$getPrefs3 = _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"](),
budgetVersion = _prefs$getPrefs3.budgetVersion,
budgetId = _prefs$getPrefs3.budgetId;
try {
await Object(_update__WEBPACK_IMPORTED_MODULE_12__["updateVersion"])(budgetVersion, showUpdate);
} catch (e) {
console.warn('Error updating', e);
let result;
if (e.message.includes('out-of-sync-migrations')) {
result = {
error: 'out-of-sync-migrations'
};
} else if (e.message.includes('out-of-sync-data')) {
result = {
error: 'out-of-sync-data'
};
} else {
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_3__["captureException"])(e);
_platform_server_log__WEBPACK_IMPORTED_MODULE_7__["default"].info('Error updating budget ' + id, e);
console.log('Error updating budget', e);
result = {
error: 'loading-budget'
};
}
await handlers['close-budget']();
return result;
}
await _db__WEBPACK_IMPORTED_MODULE_9__["loadClock"]();
if (_prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]().resetClock) {
// If we need to generate a fresh clock, we need to generate a new
// client id. This happens when the database is transferred to a
// new device.
//
// TODO: The client id should be stored elsewhere. It shouldn't
// work this way, but it's fine for now.
_timestamp__WEBPACK_IMPORTED_MODULE_27__["getClock"]().timestamp.setNode(_timestamp__WEBPACK_IMPORTED_MODULE_27__["makeClientId"]());
await _db__WEBPACK_IMPORTED_MODULE_9__["runQuery"]('INSERT OR REPLACE INTO messages_clock (id, clock) VALUES (1, ?)', [_timestamp__WEBPACK_IMPORTED_MODULE_27__["serializeClock"](_timestamp__WEBPACK_IMPORTED_MODULE_27__["getClock"]())]);
await _prefs__WEBPACK_IMPORTED_MODULE_4__["savePrefs"]({
resetClock: false
});
}
if (!_platform__WEBPACK_IMPORTED_MODULE_8__["default"].isWeb && !_platform__WEBPACK_IMPORTED_MODULE_8__["default"].isMobile && !global.__TESTING__) {
Object(_backups__WEBPACK_IMPORTED_MODULE_18__["startBackupService"])(id);
}
try {
await _sheet__WEBPACK_IMPORTED_MODULE_10__["loadSpreadsheet"](_db__WEBPACK_IMPORTED_MODULE_9__, onSheetChange);
} catch (e) {
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_3__["captureException"])(e);
await handlers['close-budget']();
return {
error: 'opening-budget'
};
} // This is a bit leaky, but we need to set the initial budget type
_sheet__WEBPACK_IMPORTED_MODULE_10__["get"]().meta().budgetType = _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]().budgetType;
await _budget_base__WEBPACK_IMPORTED_MODULE_22__["createAllBudgets"](); // Load all the in-memory state
await _db_mappings__WEBPACK_IMPORTED_MODULE_15__["loadMappings"]();
await _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_14__["loadRules"]();
await _sync_migrate__WEBPACK_IMPORTED_MODULE_30__["listen"]();
await _main_app__WEBPACK_IMPORTED_MODULE_45__["default"].startServices();
Object(_undo__WEBPACK_IMPORTED_MODULE_11__["clearUndo"])(); // Ensure that syncing is enabled
if (!global.__TESTING__) {
if (process.env.IS_BETA || id === DEMO_BUDGET_ID) {
Object(_sync__WEBPACK_IMPORTED_MODULE_29__["setSyncingMode"])('disabled');
} else if (id === TEST_BUDGET_ID) {
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('lastBudget', id);
} else {
Object(_sync__WEBPACK_IMPORTED_MODULE_29__["setSyncingMode"])('enabled');
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.setItem('lastBudget', id); // Only upload periodically on desktop
if (!_platform__WEBPACK_IMPORTED_MODULE_8__["default"].isMobile) {
await _cloud_storage__WEBPACK_IMPORTED_MODULE_37__["possiblyUpload"]();
}
}
}
_main_app__WEBPACK_IMPORTED_MODULE_45__["default"].events.emit('load-budget', {
id
});
return {};
}
handlers['get-upgrade-notifications'] = async function () {
let _prefs$getPrefs4 = _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"](),
id = _prefs$getPrefs4.id;
if (id === TEST_BUDGET_ID || id === DEMO_BUDGET_ID) {
return [];
}
let types = ['schedules', 'repair-splits'];
let unseen = [];
for (let type of types) {
let key = `notifications.${type}`;
if (_prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]()[key] == null) {
unseen.push(type);
}
}
return unseen;
};
handlers['seen-upgrade-notification'] = async function ({
type
}) {
let key = `notifications.${type}`;
_prefs__WEBPACK_IMPORTED_MODULE_4__["savePrefs"]({
[key]: true
});
};
handlers['upload-file-web'] = async function ({
filename,
contents
}) {
if (!_platform__WEBPACK_IMPORTED_MODULE_8__["default"].isWeb) {
return null;
}
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.writeFile('/uploads/' + filename, contents);
return 'ok';
};
handlers['backups-get'] = async function ({
id
}) {
return Object(_backups__WEBPACK_IMPORTED_MODULE_18__["getAvailableBackups"])(id);
};
handlers['backup-load'] = async function ({
id,
backupId
}) {
await Object(_backups__WEBPACK_IMPORTED_MODULE_18__["loadBackup"])(id, backupId);
};
handlers['backup-make'] = async function ({
id
}) {
await Object(_backups__WEBPACK_IMPORTED_MODULE_18__["makeBackup"])(id);
};
handlers['get-last-opened-backup'] = async function () {
const id = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.getItem('lastBudget');
if (id && id !== '') {
const budgetDir = _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.getBudgetDir(id); // We never want to give back a budget that does not exist on the
// filesystem anymore, so first check that it exists
if (await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.exists(budgetDir)) {
return id;
}
}
return null;
};
handlers['app-focused'] = async function () {
if (_prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]() && _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]().id) {
// First we sync
Object(_sync__WEBPACK_IMPORTED_MODULE_29__["fullSync"])();
}
};
handlers['track'] = async function ({
name,
props
}) {
_tracking_events__WEBPACK_IMPORTED_MODULE_39__["track"](name, props);
};
handlers = Object(_api__WEBPACK_IMPORTED_MODULE_35__["default"])(handlers);
_actual_app_api_injected__WEBPACK_IMPORTED_MODULE_36___default.a.send = (name, args) => Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["runHandler"])(_main_app__WEBPACK_IMPORTED_MODULE_45__["default"].handlers[name], args); // A hack for now until we clean up everything
_main_app__WEBPACK_IMPORTED_MODULE_45__["default"].handlers = handlers;
_main_app__WEBPACK_IMPORTED_MODULE_45__["default"].combine(_schedules_app__WEBPACK_IMPORTED_MODULE_46__["default"], _budget_app__WEBPACK_IMPORTED_MODULE_47__["default"], _notes_app__WEBPACK_IMPORTED_MODULE_48__["default"], _tools_app__WEBPACK_IMPORTED_MODULE_49__["default"]);
function getDefaultDocumentDir() {
if (_platform__WEBPACK_IMPORTED_MODULE_8__["default"].isMobile) {
// On mobile, unfortunately we need to be backwards compatible
// with the old folder structure which does not store files inside
// of an `Actual` directory. In the future, if we really care, we
// can migrate them, but for now just return the documents dir
return process.env.ACTUAL_DOCUMENT_DIR;
}
return _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.join(process.env.ACTUAL_DOCUMENT_DIR, 'Actual');
}
async function setupDocumentsDir() {
async function ensureExists(dir) {
// Make sure the document folder exists
if (!(await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.exists(dir))) {
await _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.mkdir(dir);
}
}
let documentDir = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.getItem('document-dir'); // Test the existing documents directory to make sure it's a valid
// path that exists, and if it errors fallback to the default one
if (documentDir) {
try {
await ensureExists(documentDir);
} catch (e) {
documentDir = null;
}
}
if (!documentDir) {
documentDir = getDefaultDocumentDir();
}
await ensureExists(documentDir);
_platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a._setDocumentDir(documentDir);
}
async function initApp(version, isDev, socketName) {
VERSION = version;
await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_6__["init"]();
await Promise.all([_platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.init(), _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.init()]);
await _tracking_events__WEBPACK_IMPORTED_MODULE_39__["init"]();
await setupDocumentsDir();
let keysStr = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.getItem('encrypt-keys');
if (keysStr) {
try {
let keys = JSON.parse(keysStr); // Load all the keys
await Promise.all(Object.keys(keys).map(fileId => {
return _encryption__WEBPACK_IMPORTED_MODULE_38__["default"].loadKey(keys[fileId]);
}));
} catch (e) {
console.log('Error loading key', e);
throw new Error('load-key-error');
}
}
if (isDev) {
const lastBudget = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.getItem('lastBudget'); // if (lastBudget) {
// loadBudget(lastBudget, VERSION);
// }
// setConfig({
// SYNC_SERVER: 'https://sync-staging.actualbudget.com/sync',
// SIGNUP_SERVER: 'https://sync-staging.actualbudget.com/account',
// PLAID_SERVER: 'https://sync-staging.actualbudget.com/plaid'
// });
Object(_config__WEBPACK_IMPORTED_MODULE_34__["setConfig"])({
SYNC_SERVER: 'http://localhost:5006/sync',
SIGNUP_SERVER: 'http://localhost:5006/account',
PLAID_SERVER: 'http://localhost:5006/plaid'
});
}
connection.init(socketName, _main_app__WEBPACK_IMPORTED_MODULE_45__["default"].handlers);
_tracking_events__WEBPACK_IMPORTED_MODULE_39__["track"]('app:init', {
platform: _platform__WEBPACK_IMPORTED_MODULE_8__["default"].isMobile ? 'mobile' : _platform__WEBPACK_IMPORTED_MODULE_8__["default"].isWeb ? 'web' : 'desktop'
});
if (!isDev && !_platform__WEBPACK_IMPORTED_MODULE_8__["default"].isMobile && !_platform__WEBPACK_IMPORTED_MODULE_8__["default"].isWeb) {
let autoUpdate = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.getItem('auto-update');
process.send({
type: 'shouldAutoUpdate',
flag: autoUpdate == null || autoUpdate === 'true'
});
}
if (isDev || process.env.IS_BETA) {
global.$send = (name, args) => Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["runHandler"])(_main_app__WEBPACK_IMPORTED_MODULE_45__["default"].handlers[name], args);
global.$query = _aql_schema_run_query__WEBPACK_IMPORTED_MODULE_43__["runQuery"];
global.$q = _shared_query__WEBPACK_IMPORTED_MODULE_44__["default"];
global.$db = _db__WEBPACK_IMPORTED_MODULE_9__;
global.$setSyncingMode = _sync__WEBPACK_IMPORTED_MODULE_29__["setSyncingMode"];
}
}
async function init({
budgetId,
config
}) {
// Get from build
// eslint-disable-next-line
VERSION = "0.0.147";
let dataDir, serverURL;
if (config) {
dataDir = config.dataDir;
serverURL = config.serverURL;
} else {
dataDir = process.env.ACTUAL_DATA_DIR;
serverURL = process.env.ACTUAL_SERVER_URL;
}
await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_6__["init"]();
await Promise.all([_platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.init({
persist: false
}), _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.init()]);
_platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a._setDocumentDir(dataDir || process.cwd());
if (serverURL) {
Object(_config__WEBPACK_IMPORTED_MODULE_34__["setConfig"])({
SYNC_SERVER: joinURL(serverURL, '/sync'),
SIGNUP_SERVER: joinURL(serverURL, '/account'),
PLAID_SERVER: joinURL(serverURL, '/plaid')
});
} else {
// This turns off all server URLs. In this mode we don't want any
// access to the server, we are doing things locally
Object(_config__WEBPACK_IMPORTED_MODULE_34__["setConfig"])(null);
_main_app__WEBPACK_IMPORTED_MODULE_45__["default"].events.on('load-budget', () => {
Object(_sync__WEBPACK_IMPORTED_MODULE_29__["setSyncingMode"])('offline');
});
}
if (budgetId) {
await Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["runHandler"])(handlers['load-budget'], {
id: budgetId
});
}
return lib;
} // Export a few things required for the platform
const lib = {
getDataDir: _platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.getDataDir,
sendMessage: (msg, args) => connection.send(msg, args),
send: async (name, args) => {
let res = await Object(_mutators__WEBPACK_IMPORTED_MODULE_26__["runHandler"])(_main_app__WEBPACK_IMPORTED_MODULE_45__["default"].handlers[name], args);
return res;
},
on: (name, func) => _main_app__WEBPACK_IMPORTED_MODULE_45__["default"].events.on(name, func),
syncAndReceiveMessages: _sync__WEBPACK_IMPORTED_MODULE_29__["syncAndReceiveMessages"],
q: _shared_query__WEBPACK_IMPORTED_MODULE_44__["default"],
db: _db__WEBPACK_IMPORTED_MODULE_9__,
// Expose CRDT mechanisms so server can use them
merkle: _merkle__WEBPACK_IMPORTED_MODULE_28__,
timestamp: _timestamp__WEBPACK_IMPORTED_MODULE_27__,
SyncProtoBuf: SyncPb
};
if ( true && _platform__WEBPACK_IMPORTED_MODULE_8__["default"].isWeb) {
// Support reloading the backend
self.addEventListener('message', async e => {
if (e.data.type === '__actual:shutdown') {
await _sheet__WEBPACK_IMPORTED_MODULE_10__["waitOnSpreadsheet"]();
await _main_app__WEBPACK_IMPORTED_MODULE_45__["default"].stopServices();
await _db__WEBPACK_IMPORTED_MODULE_9__["closeDatabase"]();
_platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_2___default.a.shutdown();
_platform_server_fs__WEBPACK_IMPORTED_MODULE_5___default.a.shutdown();
setTimeout(() => {
// Give everything else some time to process shutdown events
self.close();
}, 100);
}
});
}
/***/ }),
/***/ "./packages/loot-core/src/server/merkle.js":
/*!*************************************************!*\
!*** ./packages/loot-core/src/server/merkle.js ***!
\*************************************************/
/*! exports provided: getKeys, keyToTimestamp, insert, build, diff, prune, debug */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getKeys", function() { return getKeys; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "keyToTimestamp", function() { return keyToTimestamp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "insert", function() { return insert; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "build", function() { return build; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "diff", function() { return diff; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prune", function() { return prune; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "debug", function() { return debug; });
// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
function getKeys(trie) {
return Object.keys(trie).filter(x => x !== 'hash');
}
function keyToTimestamp(key) {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
let fullkey = key + '0'.repeat(16 - key.length); // Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
function insert(trie, timestamp) {
let hash = timestamp.hash();
let key = Number(timestamp.millis() / 1000 / 60 | 0).toString(3);
trie = Object.assign({}, trie, {
hash: trie.hash ^ hash
});
return insertKey(trie, key, hash);
}
function insertKey(trie, key, hash) {
if (key.length === 0) {
return trie;
}
const c = key[0];
const n = trie[c] || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: n.hash ^ hash
})
});
}
function build(timestamps) {
let trie = {};
for (let timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
function diff(trie1, trie2) {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = ''; // This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
let keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
let keys = [...keyset.values()];
keys.sort();
let diffkey = null; // Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
if (!node1[key] || !node2[key]) {
break;
}
let next1 = node1[key];
let next2 = node2[key];
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || {};
node2 = node2[diffkey] || {};
}
}
function prune(trie, n = 2) {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
let keys = getKeys(trie);
keys.sort();
let next = {
hash: trie.hash
};
keys = keys.slice(-n).map(k => next[k] = prune(trie[k], n));
return next;
}
function debug(trie, k = '', indent = 0) {
const str = ' '.repeat(indent) + (k !== '' ? `k: ${k} ` : '') + `hash: ${trie.hash || '(empty)'}\n`;
return str + getKeys(trie).map(key => {
return debug(trie[key], key, indent + 2);
}).join('');
}
/***/ }),
/***/ "./packages/loot-core/src/server/migrate/migrations.js":
/*!*************************************************************!*\
!*** ./packages/loot-core/src/server/migrate/migrations.js ***!
\*************************************************************/
/*! exports provided: withMigrationsDir, getMigrationsDir, getUpMigration, getAppliedMigrations, getMigrationList, getPending, applyMigration, migrate */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withMigrationsDir", function() { return withMigrationsDir; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMigrationsDir", function() { return getMigrationsDir; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getUpMigration", function() { return getUpMigration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAppliedMigrations", function() { return getAppliedMigrations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMigrationList", function() { return getMigrationList; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPending", function() { return getPending; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyMigration", function() { return applyMigration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "migrate", function() { return migrate; });
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../platform/server/fs */ "./packages/loot-core/src/platform/server/fs/index.electron.js");
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../platform/server/sqlite */ "./packages/loot-core/src/platform/server/sqlite/index.electron.js");
/* harmony import */ var _migrations_1632571489012_remove_cache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../migrations/1632571489012_remove_cache.js */ "./packages/loot-core/migrations/1632571489012_remove_cache.js");
// We have to bundle in JS migrations manually to avoid having to `eval`
// them which doesn't play well with CSP. There isn't great, and eventually
// we can remove this migration.
const uuid = __webpack_require__(/*! ../../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js");
let MIGRATIONS_DIR = _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.migrationsPath;
let javascriptMigrations = {
1632571489012: _migrations_1632571489012_remove_cache_js__WEBPACK_IMPORTED_MODULE_2__["default"]
};
async function withMigrationsDir(dir, func) {
let oldDir = MIGRATIONS_DIR;
MIGRATIONS_DIR = dir;
await func();
MIGRATIONS_DIR = oldDir;
}
function getMigrationsDir() {
return MIGRATIONS_DIR;
}
function getMigrationId(name) {
return parseInt(name.match(/^(\d)+/)[0]);
}
function getUpMigration(id, names) {
for (let m of names) {
if (getMigrationId(m) === id) {
return m;
}
}
}
async function getAppliedMigrations(db) {
const rows = await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["runQuery"](db, 'SELECT * FROM __migrations__ ORDER BY id ASC', [], true);
return rows.map(row => row.id);
}
async function getMigrationList(migrationsDir) {
const files = await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.listDir(migrationsDir);
return files.filter(name => name.match(/(\.sql|\.js)$/)).sort((m1, m2) => {
const id1 = getMigrationId(m1);
const id2 = getMigrationId(m2);
if (id1 < id2) {
return -1;
} else if (id1 > id2) {
return 1;
}
return 0;
});
}
function getPending(appliedIds, all) {
return all.filter(name => {
const id = getMigrationId(name);
return appliedIds.indexOf(id) === -1;
});
}
async function applyJavaScript(db, id) {
const dbInterface = {
runQuery: (query, params, fetchAll) => _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["runQuery"](db, query, params, fetchAll),
execQuery: query => _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["execQuery"](db, query),
transaction: func => _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["transaction"](db, func)
};
if (javascriptMigrations[id] == null) {
throw new Error('Could not find JS migration code to run for ' + id);
}
let run = javascriptMigrations[id];
return run(dbInterface, () => uuid.v4Sync());
}
async function applySql(db, sql) {
try {
await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["execQuery"](db, sql);
} catch (e) {
console.log('Error applying sql:', sql);
throw e;
}
}
async function applyMigration(db, name, migrationsDir) {
const code = await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.readFile(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.join(migrationsDir, name));
if (name.match(/\.js$/)) {
await applyJavaScript(db, getMigrationId(name));
} else {
await applySql(db, code);
}
await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_1__["runQuery"](db, 'INSERT INTO __migrations__ (id) VALUES (?)', [getMigrationId(name)]);
}
function checkDatabaseValidity(appliedIds, available) {
for (let i = 0; i < appliedIds.length; i++) {
if (i >= available.length || appliedIds[i] !== getMigrationId(available[i])) {
throw new Error('out-of-sync-migrations');
}
}
}
async function migrate(db) {
let appliedIds = await getAppliedMigrations(db);
let available = await getMigrationList(MIGRATIONS_DIR);
checkDatabaseValidity(appliedIds, available);
const pending = getPending(appliedIds, available);
for (let migration of pending) {
await applyMigration(db, migration, MIGRATIONS_DIR);
}
return pending;
}
/***/ }),
/***/ "./packages/loot-core/src/server/models.js":
/*!*************************************************!*\
!*** ./packages/loot-core/src/server/models.js ***!
\*************************************************/
/*! exports provided: requiredFields, toDateRepr, fromDateRepr, accountModel, categoryModel, categoryGroupModel, payeeModel, payeeRuleModel, transactionModel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "requiredFields", function() { return requiredFields; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toDateRepr", function() { return toDateRepr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromDateRepr", function() { return fromDateRepr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "accountModel", function() { return accountModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "categoryModel", function() { return categoryModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "categoryGroupModel", function() { return categoryGroupModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "payeeModel", function() { return payeeModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "payeeRuleModel", function() { return payeeRuleModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transactionModel", function() { return transactionModel; });
const _excluded = ["sort_order"],
_excluded2 = ["sort_order"];
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function requiredFields(name, row, fields, update) {
fields.forEach(field => {
if (update) {
if (row.hasOwnProperty(field) && row[field] == null) {
throw new Error(`${name} is missing field ${field}`);
}
} else {
if (!row.hasOwnProperty(field) || row[field] == null) {
throw new Error(`${name} is missing field ${field}`);
}
}
});
}
function toDateRepr(str) {
if (typeof str !== 'string') {
throw new Error('toDateRepr not passed a string: ' + str);
}
return parseInt(str.replace(/-/g, ''));
}
function fromDateRepr(number) {
if (typeof number !== 'number') {
throw new Error('fromDateRepr not passed a number: ' + number);
}
const dateString = number.toString();
return dateString.slice(0, 4) + '-' + dateString.slice(4, 6) + '-' + dateString.slice(6);
}
const accountModel = {
validateAccountType(account) {
const type = account.type;
if (type !== 'checking' && type !== 'savings' && type !== 'investment' && type !== 'credit' && type !== 'mortgage' && type !== 'debt' && type !== 'other') {
throw new Error('Invalid account type: ' + type);
}
},
validate(account, {
update
} = {}) {
if (!update || account.type != null) {
accountModel.validateAccountType(account);
}
requiredFields('account', account, update ? ['name', 'type', 'offbudget', 'closed'] : ['name', 'type'], update);
return account;
}
};
const categoryModel = {
validate(category, {
update
} = {}) {
requiredFields('category', category, update ? ['name', 'is_income', 'cat_group'] : ['name', 'cat_group'], update);
let sort_order = category.sort_order,
rest = _objectWithoutProperties(category, _excluded);
return rest;
}
};
const categoryGroupModel = {
validate(categoryGroup, {
update
} = {}) {
requiredFields('categoryGroup', categoryGroup, update ? ['name', 'is_income'] : ['name'], update);
let sort_order = categoryGroup.sort_order,
rest = _objectWithoutProperties(categoryGroup, _excluded2);
return rest;
}
};
const payeeModel = {
validate(payee, {
update
} = {}) {
requiredFields('payee', payee, ['name'], update);
return payee;
}
};
const payeeRuleModel = {
validateType(rule) {
const type = rule.type;
if (type !== 'equals' && type !== 'contains') {
throw new Error('Invalid rule type: ' + type);
}
},
validate(rule, {
update
} = {}) {
if (!update || 'type' in rule) {
payeeRuleModel.validateType(rule);
}
requiredFields('payee_rules', rule, ['payee_id', 'type'], update);
return rule;
}
};
const transactionModel = {
validate(trans, {
update
} = {}) {
requiredFields('transaction', trans, ['date', 'acct'], update);
if ('date' in trans) {
// Make sure it's the right format, and also do a sanity check.
// Really old dates can mess up the system and can happen by
// accident
if (trans.date.match(/^\d{4}-\d{2}-\d{2}$/) == null || trans.date < '2000-01-01') {
throw new Error('Invalid transaction date: ' + trans.date);
}
}
return trans;
},
toJS(row) {
// Check a non-important field that typically wouldn't be passed in
// manually, and use it as a smoke test to see if this is a
// fully-formed transaction or not.
if (!('location' in row)) {
throw new Error('A full transaction is required to be passed to `toJS`. Instead got: ' + JSON.stringify(row));
}
let trans = _objectSpread({}, row);
trans.error = row.error ? JSON.parse(row.error) : null;
trans.isParent = row.isParent === 1 ? true : false;
trans.isChild = row.isChild === 1 ? true : false;
trans.starting_balance_flag = row.starting_balance_flag === 1 ? true : false;
trans.cleared = row.cleared === 1 ? true : false;
trans.pending = row.pending === 1 ? true : false;
trans.date = trans.date && fromDateRepr(trans.date);
return trans;
},
fromJS(trans) {
let row = _objectSpread({}, trans);
if ('error' in row) {
row.error = trans.error ? JSON.stringify(trans.error) : null;
}
if ('isParent' in row) {
row.isParent = trans.isParent ? 1 : 0;
}
if ('isChild' in row) {
row.isChild = trans.isChild ? 1 : 0;
}
if ('cleared' in row) {
row.cleared = trans.cleared ? 1 : 0;
}
if ('pending' in row) {
row.pending = trans.pending ? 1 : 0;
}
if ('starting_balance_flag' in row) {
row.starting_balance_flag = trans.starting_balance_flag ? 1 : 0;
}
if ('date' in row) {
row.date = toDateRepr(trans.date);
}
return row;
}
};
/***/ }),
/***/ "./packages/loot-core/src/server/mutators.js":
/*!***************************************************!*\
!*** ./packages/loot-core/src/server/mutators.js ***!
\***************************************************/
/*! exports provided: mutator, isMutating, runHandler, enableGlobalMutations, disableGlobalMutations, runMutator, withMutatorContext, getMutatorContext */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mutator", function() { return mutator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isMutating", function() { return isMutating; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runHandler", function() { return runHandler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableGlobalMutations", function() { return enableGlobalMutations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "disableGlobalMutations", function() { return disableGlobalMutations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runMutator", function() { return runMutator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withMutatorContext", function() { return withMutatorContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMutatorContext", function() { return getMutatorContext; });
/* harmony import */ var _shared_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../shared/async */ "./packages/loot-core/src/shared/async.js");
/* harmony import */ var _platform_exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../platform/exceptions */ "./packages/loot-core/src/platform/exceptions/index.electron.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
let runningMethods = new Set();
let currentContext = null;
let mutatingMethods = new WeakMap();
let globalMutationsEnabled = false;
let _latestHandlerNames = [];
function mutator(handler) {
mutatingMethods.set(handler, true);
return handler;
}
function isMutating(handler) {
return mutatingMethods.has(handler);
}
async function flushRunningMethods() {
// Give the client some time to invoke new requests
await wait(200);
while (runningMethods.size > 0) {
// Wait for all of them
await Promise.all([...runningMethods.values()]); // We give clients more time to make other requests. This lets them continue
// to do an async workflow
await wait(100);
}
}
function wait(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
async function runHandler(handler, args, {
undoTag,
name
} = {}) {
// For debug reasons, track the latest handlers that have been
// called
_latestHandlerNames.push(name);
if (_latestHandlerNames.length > 5) {
_latestHandlerNames = _latestHandlerNames.slice(-5);
}
if (mutatingMethods.has(handler)) {
return runMutator(() => handler(args), {
undoTag
});
} // When closing a file, it clears out all global state for the file. That
// means any async workflows currently executed would be cut off. We handle
// this by letting all async workflows finish executing before closing the
// file
if (name === 'close-budget') {
await flushRunningMethods();
}
let promise = handler(args);
runningMethods.add(promise);
promise.then(() => {
runningMethods.delete(promise);
});
return promise;
} // These are useful for tests. Only use them in tests.
function enableGlobalMutations() {
if (global.__TESTING__) {
globalMutationsEnabled = true;
}
}
function disableGlobalMutations() {
if (global.__TESTING__) {
globalMutationsEnabled = false;
}
}
const runMutator = Object(_shared_async__WEBPACK_IMPORTED_MODULE_0__["sequential"])(async (func, initialContext = {}) => {
currentContext = initialContext;
return func().finally(() => {
currentContext = null;
});
});
function withMutatorContext(context, func) {
if (currentContext == null && !globalMutationsEnabled) {
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_1__["captureBreadcrumb"])('Recent methods: ' + _latestHandlerNames.join(', '));
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_1__["captureException"])(new Error('withMutatorContext: mutator not running')); // See comment below. This is not an error right now, but it will
// be in the future.
return func();
}
let prevContext = currentContext;
currentContext = _objectSpread(_objectSpread({}, currentContext), context);
return func().finally(() => {
currentContext = prevContext;
});
}
function getMutatorContext() {
if (currentContext == null) {
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_1__["captureBreadcrumb"])({
category: 'server',
message: 'Recent methods: ' + _latestHandlerNames.join(', ')
}); // captureException(new Error('getMutatorContext: mutator not running'));
// For now, this is a non-fatal error. It will be in the future,
// but this is relatively non-critical (undo just won't work) so
// return an empty context. When we have more confidence that
// everything is running inside a mutator, throw an error.
return {};
}
if (currentContext == null && globalMutationsEnabled) {
return {};
}
return currentContext;
}
/***/ }),
/***/ "./packages/loot-core/src/server/notes/app.js":
/*!****************************************************!*\
!*** ./packages/loot-core/src/server/notes/app.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _app__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../app */ "./packages/loot-core/src/server/app.js");
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
let app = Object(_app__WEBPACK_IMPORTED_MODULE_0__["createApp"])();
app.method('notes-save', async ({
id,
note
}) => {
await _db__WEBPACK_IMPORTED_MODULE_1__["update"]('notes', {
id,
note
});
});
/* harmony default export */ __webpack_exports__["default"] = (app);
/***/ }),
/***/ "./packages/loot-core/src/server/perf.js":
/*!***********************************************!*\
!*** ./packages/loot-core/src/server/perf.js ***!
\***********************************************/
/*! exports provided: reset, record, increment, start, stop */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reset", function() { return reset; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "record", function() { return record; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "increment", function() { return increment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "start", function() { return start; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stop", function() { return stop; });
let enabled = false;
let entries = {};
let counters = {};
function reset() {
entries = {};
counters = {};
}
function record(name) {
const start = Date.now();
return () => unrecord(name, start);
}
function unrecord(name, start) {
const end = Date.now();
if (enabled) {
if (entries[name] == null) {
entries[name] = [];
}
entries[name].push(end - start);
}
}
function increment(name) {
if (enabled) {
if (counters[name] == null) {
counters[name] = 0;
}
counters[name]++;
}
}
function start() {
enabled = true;
}
function stop() {
enabled = false;
console.log('~~ PERFORMANCE REPORT ~~');
for (let name in entries) {
const records = entries[name];
const total = records.reduce((total, n) => total + n / 1000, 0);
const avg = total / records.length;
console.log(`[${name}] count: ${records.length} total: ${total}s avg: ${avg}`);
}
for (let name in counters) {
console.log(`[${name}] ${counters[name]}`);
}
console.log('~~ END REPORT ~~');
reset();
}
/***/ }),
/***/ "./packages/loot-core/src/server/platform.js":
/*!***************************************************!*\
!*** ./packages/loot-core/src/server/platform.js ***!
\***************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
isMobile: false,
isWeb: false,
isDesktop: true
});
/***/ }),
/***/ "./packages/loot-core/src/server/polyfills.js":
/*!****************************************************!*\
!*** ./packages/loot-core/src/server/polyfills.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
// By default, no polyfills are installed
/***/ }),
/***/ "./packages/loot-core/src/server/post.js":
/*!***********************************************!*\
!*** ./packages/loot-core/src/server/post.js ***!
\***********************************************/
/*! exports provided: post, postBinary, get */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "post", function() { return post; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "postBinary", function() { return postBinary; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "get", function() { return get; });
/* harmony import */ var _platform__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./platform */ "./packages/loot-core/src/server/platform.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const _require = __webpack_require__(/*! ./errors */ "./packages/loot-core/src/server/errors.js"),
PostError = _require.PostError,
HTTPError = _require.HTTPError;
const _require2 = __webpack_require__(/*! ../platform/server/fetch */ "./packages/loot-core/src/platform/server/fetch/index.electron.js"),
fetch = _require2.fetch;
function throwIfNot200(res, text) {
if (res.status !== 200) {
if (res.status === 500) {
throw new PostError(res.status === 500 ? 'internal' : text);
}
let contentType = res.headers.get('Content-Type');
if (contentType.toLowerCase().indexOf('application/json') !== -1) {
let json = JSON.parse(text);
throw new PostError(json.reason);
}
throw new PostError(text);
}
}
async function post(url, data) {
let text;
let res;
let s = new Error().stack;
try {
res = await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
});
text = await res.text();
} catch (err) {
throw new PostError('network-failure');
}
throwIfNot200(res, text);
try {
res = JSON.parse(text);
} catch (err) {
// Something seriously went wrong. TODO handle errors
throw new PostError('parse-json', {
meta: text
});
}
if (res.status !== 'ok') {
console.log('API call failed: ' + url + '\nData: ' + JSON.stringify(data, null, 2) + '\nResponse: ' + JSON.stringify(res, null, 2));
throw new PostError(res.description || res.reason || 'unknown');
}
return res.data;
}
async function postBinary(url, data, headers) {
let res;
try {
res = await fetch(url, {
method: 'POST',
body: _platform__WEBPACK_IMPORTED_MODULE_0__["default"].isWeb ? data : Buffer.from(data),
headers: _objectSpread({
'Content-Length': data.length,
'Content-Type': 'application/actual-sync'
}, headers)
});
} catch (err) {
throw new PostError('network-failure');
}
let buffer;
if (res.arrayBuffer) {
buffer = Buffer.from(await res.arrayBuffer());
} else {
buffer = await res.buffer();
}
throwIfNot200(res, buffer.toString());
return buffer;
}
function get(url) {
return fetch(url).then(res => res.text());
}
/***/ }),
/***/ "./packages/loot-core/src/server/prefs.js":
/*!************************************************!*\
!*** ./packages/loot-core/src/server/prefs.js ***!
\************************************************/
/*! exports provided: loadPrefs, savePrefs, unloadPrefs, getPrefs, getDefaultPrefs, readPrefs */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadPrefs", function() { return loadPrefs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "savePrefs", function() { return savePrefs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unloadPrefs", function() { return unloadPrefs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPrefs", function() { return getPrefs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDefaultPrefs", function() { return getDefaultPrefs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readPrefs", function() { return readPrefs; });
/* harmony import */ var _sync__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sync */ "./packages/loot-core/src/server/sync/index.js");
/* harmony import */ var _timestamp__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./timestamp */ "./packages/loot-core/src/server/timestamp.js");
const fs = __webpack_require__(/*! ../platform/server/fs */ "./packages/loot-core/src/platform/server/fs/index.electron.js");
let prefs = null;
async function loadPrefs(id) {
if (global.__TESTING__ && !id) {
prefs = {
dummyTestPrefs: true
};
return prefs;
}
const fullpath = fs.join(fs.getBudgetDir(id), 'metadata.json');
try {
prefs = JSON.parse(await fs.readFile(fullpath));
} catch (e) {
// If the user messed something up, be flexible and allow them to
// still load the budget database. Default the budget name to the
// id.
prefs = {
id,
budgetName: id
};
} // No matter what is in `id` field, force it to be the current id.
// This makes it resilient to users moving around folders, etc
prefs.id = id;
return prefs;
}
async function savePrefs(prefsToSet, {
avoidSync = false
} = {}) {
Object.assign(prefs, prefsToSet);
if (!avoidSync) {
// Sync whitelisted prefs
let messages = Object.keys(prefsToSet).map(key => {
if (key === 'budgetType' || key === 'budgetName') {
return {
dataset: 'prefs',
row: key,
column: 'value',
value: prefsToSet[key],
timestamp: _timestamp__WEBPACK_IMPORTED_MODULE_1__["default"].send()
};
}
return null;
}).filter(x => x);
if (messages.length > 0) {
await Object(_sync__WEBPACK_IMPORTED_MODULE_0__["sendMessages"])(messages);
}
}
if (!prefs.dummyTestPrefs) {
let prefsPath = fs.join(fs.getBudgetDir(prefs.id), 'metadata.json');
await fs.writeFile(prefsPath, JSON.stringify(prefs));
}
}
function unloadPrefs() {
prefs = null;
}
function getPrefs() {
return prefs;
}
function getDefaultPrefs(id, budgetName) {
// Add any notifications in here that new users shouldn't see.
// Without them, a popup will show to explain a new feature.
return {
id,
budgetName,
'notifications.schedules': true,
'notifications.repair-splits': true
};
}
async function readPrefs(id) {
const fullpath = fs.join(fs.getBudgetDir(id), 'metadata.json');
try {
return JSON.parse(await fs.readFile(fullpath));
} catch (e) {
return null;
}
}
/***/ }),
/***/ "./packages/loot-core/src/server/schedules/app.js":
/*!********************************************************!*\
!*** ./packages/loot-core/src/server/schedules/app.js ***!
\********************************************************/
/*! exports provided: updateConditions, getNextDate, getRuleForSchedule, fixRuleForSchedule, setNextDate, createSchedule, updateSchedule, deleteSchedule, skipNextDate, getPossibleTransactions, discoverSchedules, getUpcomingDates, advanceSchedulesService, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateConditions", function() { return updateConditions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNextDate", function() { return getNextDate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRuleForSchedule", function() { return getRuleForSchedule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fixRuleForSchedule", function() { return fixRuleForSchedule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setNextDate", function() { return setNextDate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createSchedule", function() { return createSchedule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateSchedule", function() { return updateSchedule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteSchedule", function() { return deleteSchedule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "skipNextDate", function() { return skipNextDate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPossibleTransactions", function() { return getPossibleTransactions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "discoverSchedules", function() { return discoverSchedules; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getUpcomingDates", function() { return getUpcomingDates; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "advanceSchedulesService", function() { return advanceSchedulesService; });
/* harmony import */ var deep_equal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! deep-equal */ "./node_modules/deep-equal/index.js");
/* harmony import */ var deep_equal__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(deep_equal__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var date_fns__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! date-fns */ "./node_modules/date-fns/esm/index.js");
/* harmony import */ var _app__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../app */ "./packages/loot-core/src/server/app.js");
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _prefs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../prefs */ "./packages/loot-core/src/server/prefs.js");
/* harmony import */ var _models__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../models */ "./packages/loot-core/src/server/models.js");
/* harmony import */ var _aql_schema_run_query__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../aql/schema/run-query */ "./packages/loot-core/src/server/aql/schema/run-query.js");
/* harmony import */ var _aql_compiler__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../aql/compiler */ "./packages/loot-core/src/server/aql/compiler.js");
/* harmony import */ var _aql_schema__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../aql/schema */ "./packages/loot-core/src/server/aql/schema/index.js");
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _shared_query__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../shared/query */ "./packages/loot-core/src/shared/query.js");
/* harmony import */ var _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../accounts/transaction-rules */ "./packages/loot-core/src/server/accounts/transaction-rules.js");
/* harmony import */ var _accounts_rules__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../accounts/rules */ "./packages/loot-core/src/server/accounts/rules.js");
/* harmony import */ var _shared_schedules__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../shared/schedules */ "./packages/loot-core/src/shared/schedules.js");
/* harmony import */ var _mutators__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../mutators */ "./packages/loot-core/src/server/mutators.js");
/* harmony import */ var _undo__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../undo */ "./packages/loot-core/src/server/undo.js");
/* harmony import */ var _util_rschedule__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../util/rschedule */ "./packages/loot-core/src/server/util/rschedule.js");
/* harmony import */ var _sync__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../sync */ "./packages/loot-core/src/server/sync/index.js");
/* harmony import */ var _platform_exceptions__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../platform/exceptions */ "./packages/loot-core/src/platform/exceptions/index.electron.js");
/* harmony import */ var _accounts_sync__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../accounts/sync */ "./packages/loot-core/src/server/accounts/sync.js");
/* harmony import */ var _find_schedules__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./find-schedules */ "./packages/loot-core/src/server/schedules/find-schedules.js");
const _excluded = ["type"];
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const connection = __webpack_require__(/*! ../../platform/server/connection */ "./packages/loot-core/src/platform/server/connection/index.api.js");
const uuid = __webpack_require__(/*! ../../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js"); // Utilities
function zip(arr1, arr2) {
let result = [];
for (let i = 0; i < arr1.length; i++) {
result.push([arr1[i], arr2[i]]);
}
return result;
}
function updateConditions(conditions, newConditions) {
let scheduleConds = Object(_shared_schedules__WEBPACK_IMPORTED_MODULE_13__["extractScheduleConds"])(conditions);
let newScheduleConds = Object(_shared_schedules__WEBPACK_IMPORTED_MODULE_13__["extractScheduleConds"])(newConditions);
let replacements = zip(Object.values(scheduleConds), Object.values(newScheduleConds));
let updated = conditions.map(cond => {
let r = replacements.find(r => cond === r[0]);
return r && r[1] ? r[1] : cond;
});
let added = replacements.filter(x => x[0] == null && x[1] != null).map(x => x[1]);
return updated.concat(added);
}
function getNextDate(dateCond, start = new Date()) {
start = date_fns__WEBPACK_IMPORTED_MODULE_1__["startOfDay"](start);
let cond = new _accounts_rules__WEBPACK_IMPORTED_MODULE_12__["Condition"](dateCond.op, 'date', dateCond.value, null, new Map(Object.entries({
date: 'date'
})));
let value = cond.getValue();
if (value.type === 'date') {
return value.date;
} else if (value.type === 'recur') {
let dates = value.schedule.occurrences({
start,
take: 1
}).toArray();
if (dates.length > 0) {
let date = dates[0].date;
return Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["dayFromDate"])(date);
}
}
return null;
}
async function getRuleForSchedule(id) {
if (id == null) {
throw new Error('Schedule not attached to a rule');
}
let _await$aqlQuery = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_6__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_10__["default"])('schedules').filter({
id
}).calculate('rule')),
ruleId = _await$aqlQuery.data;
return Object(_accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_11__["getRules"])().find(rule => rule.id === ruleId);
}
async function fixRuleForSchedule(id) {
let _await$aqlQuery2 = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_6__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_10__["default"])('schedules').filter({
id
}).calculate('rule')),
ruleId = _await$aqlQuery2.data;
if (ruleId) {
// Take the bad rule out of the system so it never causes problems
// in the future
await _db__WEBPACK_IMPORTED_MODULE_3__["delete_"]('rules', ruleId);
}
let newId = await Object(_accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_11__["insertRule"])({
stage: null,
conditions: [{
op: 'isapprox',
field: 'date',
value: Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["currentDay"])()
}, {
op: 'isapprox',
field: 'amount',
value: 0
}],
actions: [{
op: 'link-schedule',
value: id
}]
});
await _db__WEBPACK_IMPORTED_MODULE_3__["updateWithSchema"]('schedules', {
id,
rule: newId
});
return Object(_accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_11__["getRules"])().find(rule => rule.id === newId);
}
async function setNextDate({
id,
start,
conditions,
reset
}) {
if (conditions == null) {
let rule = await getRuleForSchedule(id);
if (rule == null) {
throw new Error('No rule found for schedule');
}
conditions = rule.serialize().conditions;
}
let _extractScheduleConds = Object(_shared_schedules__WEBPACK_IMPORTED_MODULE_13__["extractScheduleConds"])(conditions),
dateCond = _extractScheduleConds.date;
let _await$aqlQuery3 = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_6__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_10__["default"])('schedules').filter({
id
}).calculate('next_date')),
nextDate = _await$aqlQuery3.data; // Only do this if a date condition exists
if (dateCond) {
let newNextDate = getNextDate(dateCond, start ? start(nextDate) : new Date());
if (newNextDate !== nextDate) {
// Our `update` functon requires the id of the item and we don't
// have it, so we need to query it
let nd = await _db__WEBPACK_IMPORTED_MODULE_3__["first"]('SELECT id, base_next_date_ts FROM schedules_next_date WHERE schedule_id = ?', [id]);
await _db__WEBPACK_IMPORTED_MODULE_3__["update"]('schedules_next_date', reset ? {
id: nd.id,
base_next_date: Object(_models__WEBPACK_IMPORTED_MODULE_5__["toDateRepr"])(newNextDate),
base_next_date_ts: Date.now()
} : {
id: nd.id,
local_next_date: Object(_models__WEBPACK_IMPORTED_MODULE_5__["toDateRepr"])(newNextDate),
local_next_date_ts: nd.base_next_date_ts
});
}
}
} // Methods
async function createSchedule({
schedule,
conditions = []
} = {}) {
let scheduleId = schedule && schedule.id || uuid.v4Sync();
let _extractScheduleConds2 = Object(_shared_schedules__WEBPACK_IMPORTED_MODULE_13__["extractScheduleConds"])(conditions),
dateCond = _extractScheduleConds2.date;
if (dateCond == null) {
throw new Error('A date condition is required to create a schedule');
}
if (dateCond.value == null) {
throw new Error('Date is required');
}
let nextDate = getNextDate(dateCond);
let nextDateRepr = nextDate ? Object(_models__WEBPACK_IMPORTED_MODULE_5__["toDateRepr"])(nextDate) : null; // Create the rule here based on the info
let ruleId;
ruleId = await Object(_accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_11__["insertRule"])({
stage: null,
conditions,
actions: [{
op: 'link-schedule',
value: scheduleId
}]
});
let now = Date.now();
let nextDateId = await _db__WEBPACK_IMPORTED_MODULE_3__["insertWithUUID"]('schedules_next_date', {
schedule_id: scheduleId,
local_next_date: nextDateRepr,
local_next_date_ts: now,
base_next_date: nextDateRepr,
base_next_date_ts: now
});
let id = await _db__WEBPACK_IMPORTED_MODULE_3__["insertWithSchema"]('schedules', _objectSpread(_objectSpread({}, schedule), {}, {
id: scheduleId,
rule: ruleId
}));
return scheduleId;
} // TODO: don't allow deleting rules that link schedules
async function updateSchedule({
schedule,
conditions,
resetNextDate
}) {
if (schedule.rule) {
throw new Error('You cannot change the rule of a schedule');
} // We need the rule if there are conditions
let rule; // This must be outside the `batchMessages` call because we change
// and then read data
if (conditions) {
let _extractScheduleConds3 = Object(_shared_schedules__WEBPACK_IMPORTED_MODULE_13__["extractScheduleConds"])(conditions),
dateCond = _extractScheduleConds3.date;
if (dateCond && dateCond.value == null) {
throw new Error('Date is required');
} // We need to get the full rule to merge in the updated
// conditions
rule = await getRuleForSchedule(schedule.id);
if (rule == null) {
// In the edge case that a rule gets corrupted (either by a bug in
// the system or user messing with their data), don't crash. We
// generate a new rule because schedules have to have a rule
// attached to them.
rule = await fixRuleForSchedule(schedule.id);
}
}
await Object(_sync__WEBPACK_IMPORTED_MODULE_17__["batchMessages"])(async () => {
if (conditions) {
let oldConditions = rule.serialize().conditions;
let newConditions = updateConditions(oldConditions, conditions);
await Object(_accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_11__["updateRule"])({
id: rule.id,
conditions: newConditions
}); // Annoyingly, sometimes it has `type` and sometimes it doesn't
let stripType = _ref => {
let type = _ref.type,
fields = _objectWithoutProperties(_ref, _excluded);
return fields;
}; // Update `next_date` if the user forced it, or if the account
// or date changed. We check account because we don't update
// schedules automatically for closed account, and the user
// might switch accounts from a closed one
if (resetNextDate || !deep_equal__WEBPACK_IMPORTED_MODULE_0___default()(oldConditions.find(c => c.field === 'account'), oldConditions.find(c => c.field === 'account')) || !deep_equal__WEBPACK_IMPORTED_MODULE_0___default()(stripType(oldConditions.find(c => c.field === 'date')), stripType(newConditions.find(c => c.field === 'date')))) {
await setNextDate({
id: schedule.id,
conditions: newConditions,
reset: true
});
}
} else if (resetNextDate) {
await setNextDate({
id: schedule.id,
reset: true
});
}
await _db__WEBPACK_IMPORTED_MODULE_3__["updateWithSchema"]('schedules', schedule);
});
}
async function deleteSchedule({
id
}) {
let _await$aqlQuery4 = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_6__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_10__["default"])('schedules').filter({
id
}).calculate('rule')),
ruleId = _await$aqlQuery4.data;
await Object(_sync__WEBPACK_IMPORTED_MODULE_17__["batchMessages"])(async () => {
await _db__WEBPACK_IMPORTED_MODULE_3__["delete_"]('rules', ruleId);
await _db__WEBPACK_IMPORTED_MODULE_3__["delete_"]('schedules', id);
});
}
async function skipNextDate({
id
}) {
return setNextDate({
id,
start: nextDate => {
return date_fns__WEBPACK_IMPORTED_MODULE_1__["addDays"](Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["parseDate"])(nextDate), 1);
}
});
} // `schedule` here might not be a saved schedule, so it might not have
// an id
function getPossibleTransactions({
schedule
}) {}
function discoverSchedules() {
return Object(_find_schedules__WEBPACK_IMPORTED_MODULE_20__["findSchedules"])();
}
async function getUpcomingDates({
config,
count
}) {
let rules = Object(_shared_schedules__WEBPACK_IMPORTED_MODULE_13__["recurConfigToRSchedule"])(config);
try {
let schedule = new _util_rschedule__WEBPACK_IMPORTED_MODULE_16__["Schedule"]({
rrules: rules
});
return schedule.occurrences({
start: date_fns__WEBPACK_IMPORTED_MODULE_1__["startOfDay"](new Date()),
take: count
}).toArray().map(date => Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["dayFromDate"])(date.date));
} catch (err) {
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_18__["captureBreadcrumb"])(config);
throw err;
}
} // Services
function onRuleUpdate(rule) {
let _ref2 = rule instanceof _accounts_rules__WEBPACK_IMPORTED_MODULE_12__["Rule"] ? rule.serialize() : _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_11__["ruleModel"].toJS(rule),
actions = _ref2.actions,
conditions = _ref2.conditions;
if (actions && actions.find(a => a.op === 'link-schedule')) {
let scheduleId = actions.find(a => a.op === 'link-schedule').value;
if (scheduleId) {
let conds = Object(_shared_schedules__WEBPACK_IMPORTED_MODULE_13__["extractScheduleConds"])(conditions);
let payeeIdx = conditions.findIndex(c => c === conds.payee);
let accountIdx = conditions.findIndex(c => c === conds.account);
let amountIdx = conditions.findIndex(c => c === conds.amount);
let dateIdx = conditions.findIndex(c => c === conds.date);
_db__WEBPACK_IMPORTED_MODULE_3__["runQuery"]('INSERT OR REPLACE INTO schedules_json_paths (schedule_id, payee, account, amount, date) VALUES (?, ?, ?, ?, ?)', [scheduleId, payeeIdx === -1 ? null : `$[${payeeIdx}]`, accountIdx === -1 ? null : `$[${accountIdx}]`, amountIdx === -1 ? null : `$[${amountIdx}]`, dateIdx === -1 ? null : `$[${dateIdx}]`]);
}
}
}
function trackJSONPaths() {
// Populate the table
_db__WEBPACK_IMPORTED_MODULE_3__["transaction"](() => {
Object(_accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_11__["getRules"])().forEach(rule => {
onRuleUpdate(rule);
});
});
return Object(_sync__WEBPACK_IMPORTED_MODULE_17__["addSyncListener"])(onApplySync);
}
function onApplySync(oldValues, newValues) {
let found = false;
newValues.forEach((items, table) => {
if (table === 'rules') {
found = true;
items.forEach(newValue => {
onRuleUpdate(newValue);
});
}
});
} // This is the service that move schedules forward automatically and
// posts transactions
async function postTransactionForSchedule({
id
}) {
let _await$aqlQuery5 = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_6__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_10__["default"])('schedules').filter({
id
}).select('*')),
data = _await$aqlQuery5.data;
let schedule = data[0];
if (schedule == null || schedule._account == null) {
return;
}
let transaction = {
payee: schedule._payee,
account: schedule._account,
amount: Object(_shared_schedules__WEBPACK_IMPORTED_MODULE_13__["getScheduledAmount"])(schedule._amount),
date: schedule.next_date,
schedule: schedule.id,
cleared: false
};
if (transaction.account) {
await Object(_accounts_sync__WEBPACK_IMPORTED_MODULE_19__["addTransactions"])(transaction.account, [transaction]);
}
} // TODO: make this sequential
async function advanceSchedulesService(syncSuccess) {
// Move all paid schedules
let _await$aqlQuery6 = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_6__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_10__["default"])('schedules').filter({
completed: false,
'_account.closed': false
}).select('*')),
schedules = _await$aqlQuery6.data;
let _await$aqlQuery7 = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_6__["runQuery"])(Object(_shared_schedules__WEBPACK_IMPORTED_MODULE_13__["getHasTransactionsQuery"])(schedules)),
hasTransData = _await$aqlQuery7.data;
let hasTrans = new Set(hasTransData.filter(Boolean).map(row => row.schedule));
let failedToPost = [];
let didPost = false;
for (let schedule of schedules) {
let status = Object(_shared_schedules__WEBPACK_IMPORTED_MODULE_13__["getStatus"])(schedule.next_date, schedule.completed, hasTrans.has(schedule.id));
if (status === 'paid') {
if (schedule._date) {
// Move forward recurring schedules
if (schedule._date.frequency) {
try {
await setNextDate({
id: schedule.id
});
} catch (err) {// This might error if the rule is corrupted and it can't
// find the rule
}
} else {
if (schedule._date < Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["currentDay"])()) {
// Complete any single schedules
await updateSchedule({
schedule: {
id: schedule.id,
completed: true
}
});
}
}
}
} else if ((status === 'due' || status === 'missed') && schedule.posts_transaction && schedule._account) {
// Automatically create a transaction for due schedules
if (syncSuccess) {
await postTransactionForSchedule({
id: schedule.id
});
didPost = true;
} else {
failedToPost.push(schedule._payee);
}
}
}
if (failedToPost.length > 0) {
connection.send('schedules-offline', {
payees: failedToPost
});
} else if (didPost) {
// This forces a full refresh of transactions because it
// simulates them coming in from a full sync. This not a
// great API right now, but I think generally the approach
// is sane to treat them as external sync events.
connection.send('sync-event', {
type: 'success',
tables: ['transactions'],
syncDisabled: 'false'
});
}
} // Expose functions to the client
let app = Object(_app__WEBPACK_IMPORTED_MODULE_2__["createApp"])();
app.method('schedule/create', Object(_mutators__WEBPACK_IMPORTED_MODULE_14__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_15__["undoable"])(createSchedule)));
app.method('schedule/update', Object(_mutators__WEBPACK_IMPORTED_MODULE_14__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_15__["undoable"])(updateSchedule)));
app.method('schedule/delete', Object(_mutators__WEBPACK_IMPORTED_MODULE_14__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_15__["undoable"])(deleteSchedule)));
app.method('schedule/skip-next-date', Object(_mutators__WEBPACK_IMPORTED_MODULE_14__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_15__["undoable"])(skipNextDate)));
app.method('schedule/post-transaction', Object(_mutators__WEBPACK_IMPORTED_MODULE_14__["mutator"])(Object(_undo__WEBPACK_IMPORTED_MODULE_15__["undoable"])(postTransactionForSchedule)));
app.method('schedule/force-run-service', Object(_mutators__WEBPACK_IMPORTED_MODULE_14__["mutator"])(() => advanceSchedulesService(true)));
app.method('schedule/get-possible-transactions', getPossibleTransactions);
app.method('schedule/discover', discoverSchedules);
app.method('schedule/get-upcoming-dates', getUpcomingDates);
app.service(trackJSONPaths);
app.events.on('sync', ({
type,
subtype
}) => {
let completeEvent = type === 'success' || type === 'error' || type === 'unauthorized';
if (completeEvent && _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"]()) {
let _prefs$getPrefs = _prefs__WEBPACK_IMPORTED_MODULE_4__["getPrefs"](),
lastScheduleRun = _prefs$getPrefs.lastScheduleRun;
if (lastScheduleRun !== Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["currentDay"])()) {
Object(_mutators__WEBPACK_IMPORTED_MODULE_14__["runMutator"])(() => advanceSchedulesService(type === 'success'));
_prefs__WEBPACK_IMPORTED_MODULE_4__["savePrefs"]({
lastScheduleRun: Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["currentDay"])()
});
}
}
});
/* harmony default export */ __webpack_exports__["default"] = (app);
/***/ }),
/***/ "./packages/loot-core/src/server/schedules/find-schedules.js":
/*!*******************************************************************!*\
!*** ./packages/loot-core/src/server/schedules/find-schedules.js ***!
\*******************************************************************/
/*! exports provided: matchSchedules, findSchedules */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "matchSchedules", function() { return matchSchedules; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findSchedules", function() { return findSchedules; });
/* harmony import */ var date_fns__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! date-fns */ "./node_modules/date-fns/esm/index.js");
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _util_rschedule__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/rschedule */ "./packages/loot-core/src/server/util/rschedule.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/util */ "./packages/loot-core/src/shared/util.js");
/* harmony import */ var _models__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../models */ "./packages/loot-core/src/server/models.js");
/* harmony import */ var _aql_schema_run_query__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../aql/schema/run-query */ "./packages/loot-core/src/server/aql/schema/run-query.js");
/* harmony import */ var _shared_query__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../shared/query */ "./packages/loot-core/src/shared/query.js");
/* harmony import */ var _shared_rules__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../shared/rules */ "./packages/loot-core/src/shared/rules.js");
/* harmony import */ var _shared_schedules__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../shared/schedules */ "./packages/loot-core/src/shared/schedules.js");
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../accounts/transaction-rules */ "./packages/loot-core/src/server/accounts/transaction-rules.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const uuid = __webpack_require__(/*! ../../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js");
function takeDates(config) {
let schedule = new _util_rschedule__WEBPACK_IMPORTED_MODULE_2__["Schedule"]({
rrules: Object(_shared_schedules__WEBPACK_IMPORTED_MODULE_8__["recurConfigToRSchedule"])(config)
});
return schedule.occurrences({
take: 3
}).toArray().map(d => d.date);
}
async function getTransactions(date, account) {
let _await$aqlQuery = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_5__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_6__["default"])('transactions').filter({
account,
schedule: null,
// Don't match transfers
'payee.transfer_acct': null,
$and: [{
date: {
$gte: date_fns__WEBPACK_IMPORTED_MODULE_0__["subDays"](date, 2)
}
}, {
date: {
$lte: date_fns__WEBPACK_IMPORTED_MODULE_0__["addDays"](date, 2)
}
}]
}).select('*').options({
splits: 'none'
})),
data = _await$aqlQuery.data;
return data;
}
function getRank(day1, day2) {
let dayDiff = Math.abs(date_fns__WEBPACK_IMPORTED_MODULE_0__["differenceInDays"](Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["parseDate"])(day1), Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["parseDate"])(day2))); // The amount of days off determines the rank: exact same day
// is highest rank 1, 1 day off is .5, etc. This will find the
// best start date that matches all the dates the closest
return 1 / (dayDiff + 1);
}
function matchSchedules(allOccurs, config, partialMatchRank = 0.5) {
allOccurs = [...allOccurs].reverse();
let baseOccur = allOccurs[0];
let occurs = allOccurs.slice(1);
let schedules = [];
for (let trans of baseOccur.transactions) {
let threshold = Object(_shared_rules__WEBPACK_IMPORTED_MODULE_7__["getApproxNumberThreshold"])(trans.amount);
let payee = trans.payee;
let account = trans.account;
let found = occurs.map(occur => {
let matched = occur.transactions.find(t => t.amount >= trans.amount - threshold && t.amount <= trans.amount + threshold);
matched = matched && matched.payee === payee ? matched : null;
if (matched) {
return {
trans: matched,
rank: getRank(occur.date, matched.date)
};
}
return null;
});
if (found.indexOf(null) !== -1) {
continue;
}
let rank = found.reduce((total, match) => total + match.rank, getRank(baseOccur.date, trans.date));
let exactAmount = found.reduce((exact, match) => exact && match.trans.amount === trans.amount, true);
schedules.push({
rank,
amount: trans.amount,
account: trans.account,
payee: trans.payee,
date: config,
// Exact dates rank as 1, so all of them matches exactly it
// would equal the number of `allOccurs`
exactDate: rank === allOccurs.length,
exactAmount
});
}
return schedules;
}
async function schedulesForPattern(baseStart, numDays, baseConfig, accountId, partialMatchRank) {
let schedules = [];
let i = 0;
for (let i = 0; i < numDays; i++) {
let start = date_fns__WEBPACK_IMPORTED_MODULE_0__["addDays"](baseStart, i);
let config;
if (typeof baseConfig === 'function') {
config = baseConfig(start);
if (config === false) {
// Skip this one
continue;
}
} else {
config = _objectSpread(_objectSpread({}, baseConfig), {}, {
start
});
} // Our recur config expects a day string, not a native date format
config.start = Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["dayFromDate"])(config.start);
let data = [];
let dates = takeDates(config);
for (let date of dates) {
data.push({
date: Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["dayFromDate"])(date),
transactions: await getTransactions(date, accountId)
});
}
schedules = schedules.concat(matchSchedules(data, config, partialMatchRank));
}
return schedules;
}
async function weekly(startDate, accountId) {
return schedulesForPattern(date_fns__WEBPACK_IMPORTED_MODULE_0__["subWeeks"](Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["parseDate"])(startDate), 4), 7 * 2, {
frequency: 'weekly'
}, accountId);
}
async function every2weeks(startDate, accountId) {
return schedulesForPattern( // 6 weeks would cover 3 instances, but we also scan an addition
// week back
date_fns__WEBPACK_IMPORTED_MODULE_0__["subWeeks"](Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["parseDate"])(startDate), 7), 7 * 2, {
frequency: 'weekly',
interval: 2
}, accountId);
}
async function monthly(startDate, accountId) {
return schedulesForPattern(date_fns__WEBPACK_IMPORTED_MODULE_0__["subMonths"](Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["parseDate"])(startDate), 4), 31 * 2, start => {
// 28 is the max number of days that all months are guaranteed
// to have. We don't want to go any higher than that because
// we'll end up skipping months that don't have that day.
// The use cases of end of month days will be covered with the
// `monthlyLastDay` pattern;
if (date_fns__WEBPACK_IMPORTED_MODULE_0__["getDate"](start) > 28) {
return false;
}
return {
start,
frequency: 'monthly'
};
}, accountId);
}
async function monthlyLastDay(startDate, accountId) {
// We do two separate calls because this pattern doesn't fit into
// how `schedulesForPattern` works
let s1 = await schedulesForPattern(date_fns__WEBPACK_IMPORTED_MODULE_0__["subMonths"](Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["parseDate"])(startDate), 3), 1, {
frequency: 'monthly',
patterns: [{
type: 'day',
value: -1
}]
}, accountId, // Last day patterns should win over day-specific ones that just
// happen to match
0.75);
let s2 = await schedulesForPattern(date_fns__WEBPACK_IMPORTED_MODULE_0__["subMonths"](Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["parseDate"])(startDate), 4), 1, {
frequency: 'monthly',
patterns: [{
type: 'day',
value: -1
}]
}, accountId, 0.75);
return s1.concat(s2);
}
async function monthly1stor3rd(startDate, accountId) {
return schedulesForPattern(date_fns__WEBPACK_IMPORTED_MODULE_0__["subWeeks"](Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["parseDate"])(startDate), 8), 14, start => {
let day = date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](new Date(), 'iiii');
let dayValue = day.slice(0, 2).toUpperCase();
return {
start,
frequency: 'monthly',
patterns: [{
type: dayValue,
value: 1
}, {
type: dayValue,
value: 3
}]
};
}, accountId);
}
async function monthly2ndor4th(startDate, accountId) {
return schedulesForPattern(date_fns__WEBPACK_IMPORTED_MODULE_0__["subMonths"](Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["parseDate"])(startDate), 8), 14, start => {
let day = date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](new Date(), 'iiii');
let dayValue = day.slice(0, 2).toUpperCase();
return {
start,
frequency: 'monthly',
patterns: [{
type: dayValue,
value: 2
}, {
type: dayValue,
value: 4
}]
};
}, accountId);
}
async function findStartDate(schedule) {
let conditions = schedule._conditions;
let dateCond = conditions.find(c => c.field === 'date');
let currentConfig = dateCond.value;
while (1) {
let prevConfig = currentConfig;
currentConfig = _objectSpread({}, prevConfig);
switch (currentConfig.frequency) {
case 'weekly':
currentConfig.start = Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["dayFromDate"])(date_fns__WEBPACK_IMPORTED_MODULE_0__["subWeeks"](Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["parseDate"])(currentConfig.start), currentConfig.interval || 1));
break;
case 'monthly':
currentConfig.start = Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["dayFromDate"])(date_fns__WEBPACK_IMPORTED_MODULE_0__["subMonths"](Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["parseDate"])(currentConfig.start), currentConfig.interval || 1));
break;
case 'yearly':
currentConfig.start = Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["dayFromDate"])(date_fns__WEBPACK_IMPORTED_MODULE_0__["subYears"](Object(_shared_months__WEBPACK_IMPORTED_MODULE_9__["parseDate"])(currentConfig.start), currentConfig.interval || 1));
break;
default:
throw new Error('findStartDate: invalid frequency');
}
let newConditions = conditions.map(c => c.field === 'date' ? _objectSpread(_objectSpread({}, c), {}, {
value: currentConfig
}) : c);
let _conditionsToAQL = Object(_accounts_transaction_rules__WEBPACK_IMPORTED_MODULE_10__["conditionsToAQL"])(newConditions, {
recurDateBounds: 1
}),
filters = _conditionsToAQL.filters,
errors = _conditionsToAQL.errors;
if (errors.length > 0) {
// Somehow we generated an invalid config. Abort the whole
// process and don't change the date at all
currentConfig = null;
break;
}
let _await$aqlQuery2 = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_5__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_6__["default"])('transactions').filter({
$and: filters
}).select('*')),
data = _await$aqlQuery2.data;
if (data.length === 0) {
// No data, revert back to the last valid value and stop
currentConfig = prevConfig;
break;
}
}
if (currentConfig) {
return _objectSpread(_objectSpread({}, schedule), {}, {
date: currentConfig,
_conditions: conditions.map(c => c.field === 'date' ? _objectSpread(_objectSpread({}, c), {}, {
value: currentConfig
}) : c)
});
}
return schedule;
}
async function findSchedules() {
// Patterns to look for:
// * Weekly
// * Every two weeks
// * Monthly on day X
// * Monthly on every 1st or 3rd day
// * Monthly on every 2nd or 4th day
//
// Search for them approx (+- 2 days) but track which transactions
// and find the best one...
let _await$aqlQuery3 = await Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_5__["runQuery"])(Object(_shared_query__WEBPACK_IMPORTED_MODULE_6__["default"])('accounts').filter({
closed: false
}).select('*')),
accounts = _await$aqlQuery3.data;
let allSchedules = [];
for (let account of accounts) {
// Find latest transaction-ish to start with
let latestTrans = await _db__WEBPACK_IMPORTED_MODULE_1__["first"]('SELECT * FROM v_transactions WHERE account = ? AND parent_id IS NULL ORDER BY date DESC LIMIT 1', [account.id]);
if (latestTrans) {
let latestDate = Object(_models__WEBPACK_IMPORTED_MODULE_4__["fromDateRepr"])(latestTrans.date);
allSchedules = allSchedules.concat(await weekly(latestDate, account.id), await every2weeks(latestDate, account.id), await monthly(latestDate, account.id), await monthlyLastDay(latestDate, account.id), await monthly1stor3rd(latestDate, account.id), await monthly2ndor4th(latestDate, account.id));
}
}
let schedules = [...Object(_shared_util__WEBPACK_IMPORTED_MODULE_3__["groupBy"])(allSchedules, 'payee').entries()].map(([payeeId, schedules]) => {
schedules.sort((s1, s2) => s2.rank - s1.rank);
let winner = schedules[0]; // Convert to schedule and return it
return {
id: uuid.v4Sync(),
account: winner.account,
payee: winner.payee,
date: winner.date,
amount: winner.amount,
_conditions: [{
op: 'is',
field: 'account',
value: winner.account
}, {
op: 'is',
field: 'payee',
value: winner.payee
}, {
op: winner.exactDate ? 'is' : 'isapprox',
field: 'date',
value: winner.date
}, {
op: winner.exactAmount ? 'is' : 'isapprox',
field: 'amount',
value: winner.amount
}]
};
});
let finalized = [];
for (let schedule of schedules) {
finalized.push(await findStartDate(schedule));
}
return finalized;
}
/***/ }),
/***/ "./packages/loot-core/src/server/sheet.js":
/*!************************************************!*\
!*** ./packages/loot-core/src/server/sheet.js ***!
\************************************************/
/*! exports provided: get, loadSpreadsheet, unloadSpreadsheet, reloadSpreadsheet, loadUserBudgets, getCell, getCellValue, startTransaction, endTransaction, waitOnSpreadsheet */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "get", function() { return get; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadSpreadsheet", function() { return loadSpreadsheet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unloadSpreadsheet", function() { return unloadSpreadsheet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reloadSpreadsheet", function() { return reloadSpreadsheet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadUserBudgets", function() { return loadUserBudgets; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCell", function() { return getCell; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCellValue", function() { return getCellValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startTransaction", function() { return startTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "endTransaction", function() { return endTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "waitOnSpreadsheet", function() { return waitOnSpreadsheet; });
/* harmony import */ var _spreadsheet_spreadsheet__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./spreadsheet/spreadsheet */ "./packages/loot-core/src/server/spreadsheet/spreadsheet.js");
/* harmony import */ var _prefs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./prefs */ "./packages/loot-core/src/server/prefs.js");
/* harmony import */ var _platform_exceptions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../platform/exceptions */ "./packages/loot-core/src/platform/exceptions/index.electron.js");
/* harmony import */ var _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../platform/server/sqlite */ "./packages/loot-core/src/platform/server/sqlite/index.electron.js");
/* harmony import */ var _shared_months__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../shared/months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _platform__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./platform */ "./packages/loot-core/src/server/platform.js");
const _require = __webpack_require__(/*! ./spreadsheet/util */ "./packages/loot-core/src/server/spreadsheet/util.js"),
resolveName = _require.resolveName;
let globalSheet, globalOnChange;
let globalCacheDb;
function get() {
return globalSheet;
}
async function updateSpreadsheetCache(rawDb, names) {
await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_3__["transaction"](rawDb, () => {
names.forEach(name => {
const node = globalSheet._getNode(name); // Don't cache query nodes yet
if (node.sql == null) {
_platform_server_sqlite__WEBPACK_IMPORTED_MODULE_3__["runQuery"](rawDb, 'INSERT OR REPLACE INTO kvcache (key, value) VALUES (?, ?)', [name, JSON.stringify(node.value)]);
}
});
});
}
function setCacheStatus(mainDb, cacheDb, {
clean
}) {
if (clean) {
// Generate random number and stick in both places
let num = Math.random() * 10000000;
_platform_server_sqlite__WEBPACK_IMPORTED_MODULE_3__["runQuery"](cacheDb, 'INSERT OR REPLACE INTO kvcache_key (id, key) VALUES (1, ?)', [num]);
if (mainDb) {
_platform_server_sqlite__WEBPACK_IMPORTED_MODULE_3__["runQuery"](mainDb, 'INSERT OR REPLACE INTO kvcache_key (id, key) VALUES (1, ?)', [num]);
}
} else {
_platform_server_sqlite__WEBPACK_IMPORTED_MODULE_3__["runQuery"](cacheDb, 'DELETE FROM kvcache_key');
}
}
function isCacheDirty(mainDb, cacheDb) {
let rows = _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_3__["runQuery"](cacheDb, 'SELECT key FROM kvcache_key WHERE id = 1', [], true);
let num = rows.length === 0 ? null : rows[0].key;
if (num == null) {
return true;
}
if (mainDb) {
let rows = _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_3__["runQuery"](mainDb, 'SELECT key FROM kvcache_key WHERE id = 1', [], true);
if (rows.length === 0 || rows[0].key !== num) {
return true;
}
} // Always also check if there is anything in `kvcache`. We ask for one item;
// if we didn't get back anything it's empty so there is no cache
rows = _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_3__["runQuery"](cacheDb, 'SELECT * FROM kvcache LIMIT 1', [], true);
return rows.length === 0;
}
async function loadSpreadsheet(db, onSheetChange) {
let cacheEnabled = !global.__TESTING__;
let mainDb = db.getDatabase();
let cacheDb;
if (_platform__WEBPACK_IMPORTED_MODULE_5__["default"].isDesktop && cacheEnabled) {
// Desktop apps use a separate database for the cache. This is because it is
// much more likely to directly work with files on desktop, and this makes
// it a lot clearer what the true filesize of the main db is (and avoid
// copying the cache data around).
let cachePath = db.getDatabasePath().replace(/db\.sqlite$/, 'cache.sqlite');
globalCacheDb = cacheDb = _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_3__["openDatabase"](cachePath);
_platform_server_sqlite__WEBPACK_IMPORTED_MODULE_3__["execQuery"](cacheDb, `
CREATE TABLE IF NOT EXISTS kvcache (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE IF NOT EXISTS kvcache_key (id INTEGER PRIMARY KEY, key REAL)
`);
} else {
// All other platforms use the same database for cache
cacheDb = mainDb;
}
let sheet;
if (cacheEnabled) {
sheet = new _spreadsheet_spreadsheet__WEBPACK_IMPORTED_MODULE_0__["default"](updateSpreadsheetCache.bind(null, cacheDb), setCacheStatus.bind(null, mainDb, cacheDb));
} else {
sheet = new _spreadsheet_spreadsheet__WEBPACK_IMPORTED_MODULE_0__["default"]();
}
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_2__["captureBreadcrumb"])({
message: 'loading spreaadsheet',
category: 'server'
});
globalSheet = sheet;
globalOnChange = onSheetChange;
if (onSheetChange) {
sheet.addEventListener('change', onSheetChange);
}
if (cacheEnabled && !isCacheDirty(mainDb, cacheDb)) {
let cachedRows = await _platform_server_sqlite__WEBPACK_IMPORTED_MODULE_3__["runQuery"](cacheDb, 'SELECT * FROM kvcache', [], true);
console.log(`Loaded spreadsheet from cache (${cachedRows.length} items)`);
for (let row of cachedRows) {
let parsed = JSON.parse(row.value);
sheet.load(row.key, parsed);
}
} else {
console.log('Loading fresh spreadsheet');
await loadUserBudgets(db);
}
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_2__["captureBreadcrumb"])({
message: 'loaded spreaadsheet',
category: 'server'
});
return sheet;
}
function unloadSpreadsheet() {
if (globalSheet) {
// TODO: Should wait for the sheet to finish
globalSheet.unload();
globalSheet = null;
}
if (globalCacheDb) {
_platform_server_sqlite__WEBPACK_IMPORTED_MODULE_3__["closeDatabase"](globalCacheDb);
globalCacheDb = null;
}
}
async function reloadSpreadsheet(db) {
if (globalSheet) {
unloadSpreadsheet();
return loadSpreadsheet(db, globalOnChange);
}
}
async function loadUserBudgets(db) {
let sheet = globalSheet; // TODO: Clear out the cache here so make sure future loads of the app
// don't load any extra values that aren't set here
let _ref = _prefs__WEBPACK_IMPORTED_MODULE_1__["getPrefs"]() || {},
budgetType = _ref.budgetType;
let table = budgetType === 'report' ? 'reflect_budgets' : 'zero_budgets';
let budgets = await db.all(`
SELECT * FROM ${table} b
LEFT JOIN categories c ON c.id = b.category
WHERE c.tombstone = 0
`);
sheet.startTransaction(); // Load all the budget amounts and carryover values
for (let budget of budgets) {
if (budget.month && budget.category) {
let sheetName = `budget${budget.month}`;
sheet.set(`${sheetName}!budget-${budget.category}`, budget.amount);
sheet.set(`${sheetName}!carryover-${budget.category}`, budget.carryover === 1 ? true : false);
}
} // For zero-based budgets, load the buffered amounts
if (budgetType !== 'report') {
let budgetMonths = await db.all('SELECT * FROM zero_budget_months');
for (let budgetMonth of budgetMonths) {
let sheetName = Object(_shared_months__WEBPACK_IMPORTED_MODULE_4__["sheetForMonth"])(budgetMonth.id);
sheet.set(`${sheetName}!buffered`, budgetMonth.buffered);
}
}
sheet.endTransaction();
}
function getCell(sheet, name) {
return globalSheet._getNode(resolveName(sheet, name));
}
function getCellValue(sheet, name) {
return globalSheet.getValue(resolveName(sheet, name));
}
function startTransaction() {
if (globalSheet) {
globalSheet.startTransaction();
}
}
function endTransaction() {
if (globalSheet) {
globalSheet.endTransaction();
}
}
function waitOnSpreadsheet() {
return new Promise(resolve => {
if (globalSheet) {
globalSheet.onFinish(resolve);
} else {
resolve();
}
});
}
/***/ }),
/***/ "./packages/loot-core/src/server/spreadsheet/globals.js":
/*!**************************************************************!*\
!*** ./packages/loot-core/src/server/spreadsheet/globals.js ***!
\**************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function first(arr) {
return arr[0];
}
function firstValue(arr) {
const keys = Object.keys(arr[0]);
return arr[0][keys[0]];
}
function number(v) {
if (typeof v === 'number') {
return v;
} else if (typeof v === 'string') {
const parsed = parseFloat(v);
if (isNaN(parsed)) {
return 0;
}
return parsed;
}
return 0;
}
function min(x, y) {
return Math.min(x, y);
}
function max(x, y) {
return Math.max(x, y);
}
module.exports = {
first,
firstValue,
number,
min,
max
};
/***/ }),
/***/ "./packages/loot-core/src/server/spreadsheet/graph-data-structure.js":
/*!***************************************************************************!*\
!*** ./packages/loot-core/src/server/spreadsheet/graph-data-structure.js ***!
\***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function Graph(serialized) {
var graph = {
addNode,
removeNode,
adjacent,
adjacentIncoming,
addEdge,
removeEdge,
removeIncomingEdges,
topologicalSort,
generateDOT,
getEdges
};
var edges = new Map();
var incomingEdges = new Map();
function getEdges() {
return {
edges,
incomingEdges
};
}
function addNode(node) {
edges.set(node, adjacent(node));
incomingEdges.set(node, adjacentIncoming(node));
return graph;
}
function removeIncomingEdges(node) {
const incoming = adjacentIncoming(node);
incomingEdges.set(node, new Set());
let iter = incoming.values();
let cur = iter.next();
while (!cur.done) {
removeEdge(cur.value, node);
cur = iter.next();
}
}
function removeNode(node) {
removeIncomingEdges(node);
edges.delete(node);
incomingEdges.delete(node);
}
function adjacent(node) {
return edges.get(node) || new Set();
}
function adjacentIncoming(node) {
return incomingEdges.get(node) || new Set();
} // Adds an edge from node u to node v.
// Implicitly adds the nodes if they were not already added.
function addEdge(node1, node2) {
addNode(node1);
addNode(node2);
adjacent(node1).add(node2);
adjacentIncoming(node2).add(node1);
return graph;
} // Removes the edge from node u to node v.
// Does not remove the nodes.
// Does nothing if the edge does not exist.
function removeEdge(node1, node2) {
if (edges.has(node1)) {
adjacent(node1).delete(node2);
}
if (incomingEdges.has(node2)) {
adjacentIncoming(node2).delete(node1);
}
return graph;
}
function topologicalSortUntil(name, visited, sorted) {
visited.add(name);
let iter = adjacent(name).values();
let cur = iter.next();
while (!cur.done) {
if (!visited.has(cur.value)) {
topologicalSortUntil(cur.value, visited, sorted);
}
cur = iter.next();
}
sorted.unshift(name);
}
function topologicalSort(sourceNodes) {
const visited = new Set();
const sorted = [];
sourceNodes.forEach(name => {
if (!visited.has(name)) {
topologicalSortUntil(name, visited, sorted);
}
});
return sorted;
}
function generateDOT() {
let edgeStrings = [];
edges.forEach(function (adj, edge) {
if (adj.length !== 0) {
edgeStrings.push(`${edge} -> {${adj.join(',')}}`);
}
});
return `
digraph G {
${edgeStrings.join('\n').replace(/!/g, '_')}
}
`;
}
return graph;
}
module.exports = Graph;
/***/ }),
/***/ "./packages/loot-core/src/server/spreadsheet/spreadsheet.js":
/*!******************************************************************!*\
!*** ./packages/loot-core/src/server/spreadsheet/spreadsheet.js ***!
\******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Spreadsheet; });
/* harmony import */ var mitt__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! mitt */ "./packages/loot-core/node_modules/mitt/dist/mitt.es.js");
/* harmony import */ var _aql_schema__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../aql/schema */ "./packages/loot-core/src/server/aql/schema/index.js");
/* harmony import */ var _aql_compiler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../aql/compiler */ "./packages/loot-core/src/server/aql/compiler.js");
/* harmony import */ var _aql_schema_run_query__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../aql/schema/run-query */ "./packages/loot-core/src/server/aql/schema/run-query.js");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
const Graph = __webpack_require__(/*! ./graph-data-structure */ "./packages/loot-core/src/server/spreadsheet/graph-data-structure.js");
const _require = __webpack_require__(/*! ./util */ "./packages/loot-core/src/server/spreadsheet/util.js"),
unresolveName = _require.unresolveName,
resolveName = _require.resolveName;
class Spreadsheet {
constructor(saveCache, setCacheStatus) {
this.graph = new Graph();
this.nodes = new Map();
this.transactionDepth = 0;
this.saveCache = saveCache;
this.setCacheStatus = setCacheStatus;
this.dirtyCells = [];
this.computeQueue = [];
this.events = Object(mitt__WEBPACK_IMPORTED_MODULE_0__["default"])();
this._meta = {
createdMonths: new Set()
};
}
meta() {
return this._meta;
}
setMeta(meta) {
this._meta = meta;
} // Spreadsheet interface
_getNode(name) {
const _unresolveName = unresolveName(name),
sheet = _unresolveName.sheet;
if (!this.nodes.has(name)) {
this.nodes.set(name, {
name,
expr: null,
value: null,
sheet: sheet
});
}
return this.nodes.get(name);
}
getNode(name) {
return this._getNode(name);
}
hasCell(name) {
return this.nodes.has(name);
}
add(name, expr, value) {
this.set(name, expr);
}
getNodes() {
return this.nodes;
}
serialize() {
return {
graph: this.graph.getEdges(),
nodes: [...this.nodes.entries()]
};
}
transaction(func) {
this.startTransaction();
try {
func();
} catch (e) {
console.log(e);
}
return this.endTransaction();
}
startTransaction() {
this.transactionDepth++;
}
endTransaction() {
this.transactionDepth--;
if (this.transactionDepth === 0) {
const cells = this.dirtyCells;
this.dirtyCells = [];
this.queueComputation(this.graph.topologicalSort(cells));
}
return [];
}
queueComputation(cellNames) {
// TODO: Formally write out the different cases when the existing
// queue is not empty. There should be cases where we can easily
// optimize this by skipping computations if we know they are
// going to be computed again. The hard thing is to ensure that
// the order of computations stays correct
this.computeQueue = this.computeQueue.concat(cellNames); // Begin running on the next tick so we guarantee that it doesn't finish
// within the same tick. Since some computations are async, this makes it
// consistent (otherwise it would only sometimes finish sync)
Promise.resolve().then(() => {
if (!this.running) {
this.runComputations();
}
});
}
runComputations(idx = 0) {
this.running = true;
while (idx < this.computeQueue.length) {
let name = this.computeQueue[idx];
let node;
let result;
try {
node = this.getNode(name);
if (node._run) {
let args = node._dependencies.map(dep => {
return this.getNode(dep).value;
});
result = node._run(...args);
if (result instanceof Promise) {
console.warn('dynamic cell returned a promise! this is discouraged because errors are not handled properly');
}
} else if (node.sql) {
result = Object(_aql_schema_run_query__WEBPACK_IMPORTED_MODULE_3__["runCompiledQuery"])(node.query, node.sql.sqlPieces, node.sql.state);
} else {
idx++;
continue;
}
} catch (e) {
console.log('Error while evaluating ' + name + ':', e); // If an error happens, bail on the rest of the computations
this.running = false;
this.computeQueue = [];
return;
}
if (result instanceof Promise) {
// When the cell is finished computing, finish computing the
// rest
result.then(value => {
node.value = value;
this.runComputations(idx + 1);
}, err => {
// TODO: use captureException here
console.warn(`Failed running ${node.name}!`, err);
this.runComputations(idx + 1);
});
return;
} else {
node.value = result;
}
idx++;
} // If everything computed in one loop (no async operations) notify
// the user and empty the queue
if (idx === this.computeQueue.length) {
this.events.emit('change', {
names: this.computeQueue
}); // Cache the updated cells
if (this.saveCache) {
this.saveCache(this.computeQueue);
}
this.markCacheSafe();
this.running = false;
this.computeQueue = [];
}
}
markCacheSafe() {
if (!this.cacheBarrier) {
if (this.setCacheStatus) {
this.setCacheStatus({
clean: true
});
}
}
}
markCacheDirty() {
if (this.setCacheStatus) {
this.setCacheStatus({
clean: false
});
}
}
startCacheBarrier() {
this.cacheBarrier = true;
this.markCacheDirty();
}
endCacheBarrier() {
this.cacheBarrier = false;
let pendingChange = this.running || this.computeQueue.length > 0;
if (!pendingChange) {
this.markCacheSafe();
}
}
addEventListener(name, func) {
this.events.on(name, func);
return () => this.events.off(name, func);
}
onFinish(func) {
if (this.transactionDepth !== 0) {
throw new Error('onFinish called while inside a spreadsheet transaction. This is not allowed as it will lead to race conditions');
}
if (!this.running && this.computeQueue.length === 0) {
func([]); // The remove function does nothing
return () => {};
}
let remove = this.addEventListener('change', (...args) => {
remove();
return func(...args);
});
return remove;
}
unload() {
this.events.all.clear();
}
getValue(name) {
return this.getNode(name).value;
}
getExpr(name) {
return this.getNode(name).expr;
}
getCellValue(sheet, name) {
return this.getNode(resolveName(sheet, name)).value;
}
getCellExpr(sheet, name) {
return this.getNode(resolveName(sheet, name)).expr;
}
getCellValueLoose(sheetName, cellName) {
let name = resolveName(sheetName, cellName);
if (this.nodes.has(name)) {
return this.getNode(name).value;
}
return null;
}
bootup(onReady) {
this.onFinish(() => {
onReady();
});
}
load(name, value) {
const node = this._getNode(name);
node.expr = value;
node.value = value;
}
create(name, value) {
return this.transaction(() => {
const node = this._getNode(name);
node.expr = value;
node.value = value;
this._markDirty(name);
});
}
set(name, value) {
this.create(name, value);
}
recompute(name) {
this.transaction(() => {
this.dirtyCells.push(name);
});
}
recomputeAll() {
// Recompute everything!
this.transaction(() => {
this.dirtyCells = [...this.nodes.keys()];
});
}
createQuery(sheetName, cellName, query) {
let name = resolveName(sheetName, cellName);
let node = this._getNode(name);
if (node.query !== query) {
node.query = query;
let _compileQuery = Object(_aql_compiler__WEBPACK_IMPORTED_MODULE_2__["compileQuery"])(node.query, _aql_schema__WEBPACK_IMPORTED_MODULE_1__["schema"], _aql_schema__WEBPACK_IMPORTED_MODULE_1__["schemaConfig"]),
sqlPieces = _compileQuery.sqlPieces,
state = _compileQuery.state;
node.sql = {
sqlPieces,
state
};
this.transaction(() => {
this._markDirty(name);
});
}
}
createStatic(sheetName, cellName, initialValue) {
let name = resolveName(sheetName, cellName);
let exists = this.nodes.has(name);
if (!exists) {
this.create(name, initialValue);
}
}
createDynamic(sheetName, cellName, {
dependencies = [],
run,
initialValue,
refresh
}) {
let name = resolveName(sheetName, cellName);
let node = this._getNode(name);
if (node.dynamic) {
// If it already exists, do nothing
return;
}
node.dynamic = true;
node._run = run;
dependencies = dependencies.map(dep => {
let resolved;
if (!unresolveName(dep).sheet) {
resolved = resolveName(sheetName, dep);
} else {
resolved = dep;
}
return resolved;
});
node._dependencies = dependencies; // TODO: diff these
this.graph.removeIncomingEdges(name);
dependencies.forEach(dep => {
this.graph.addEdge(dep, name);
});
if (node.value == null || refresh) {
this.transaction(() => {
node.value = initialValue;
this._markDirty(name);
});
}
}
clearSheet(sheetName) {
for (let _ref of this.nodes.entries()) {
var _ref2 = _slicedToArray(_ref, 2);
let name = _ref2[0];
let node = _ref2[1];
if (node.sheet === sheetName) {
this.nodes.delete(name);
}
}
}
voidCell(sheetName, name, voidValue = null) {
let node = this.getNode(resolveName(sheetName, name));
node._run = null;
node.dynamic = false;
node.value = voidValue;
}
deleteCell(sheetName, name) {
this.voidCell(sheetName, name);
this.nodes.delete(resolveName(sheetName, name));
}
addDependencies(sheetName, cellName, deps) {
let name = resolveName(sheetName, cellName);
deps = deps.map(dep => {
if (!unresolveName(dep).sheet) {
return resolveName(sheetName, dep);
}
return dep;
});
let node = this.getNode(name);
let newDeps = deps.filter(dep => (node._dependencies || []).indexOf(dep) === -1);
if (newDeps.length > 0) {
node._dependencies = (node._dependencies || []).concat(newDeps);
newDeps.forEach(dep => {
this.graph.addEdge(dep, name);
});
this.recompute(name);
}
}
removeDependencies(sheetName, cellName, deps) {
let name = resolveName(sheetName, cellName);
deps = deps.map(dep => {
if (!unresolveName(dep).sheet) {
return resolveName(sheetName, dep);
}
return dep;
});
let node = this.getNode(name);
node._dependencies = (node._dependencies || []).filter(dep => deps.indexOf(dep) === -1);
deps.forEach(dep => {
this.graph.removeEdge(dep, name);
});
this.recompute(name);
}
_markDirty(name) {
this.dirtyCells.push(name);
}
triggerDatabaseChanges(oldValues, newValues) {
let tables = new Set([...oldValues.keys(), ...newValues.keys()]);
this.startTransaction(); // TODO: Create an index of deps so we don't have to iterate
// across all nodes
this.nodes.forEach(node => {
if (node.sql && node.sql.state.dependencies.some(dep => tables.has(dep))) {
this._markDirty(node.name);
}
});
this.endTransaction();
}
}
/***/ }),
/***/ "./packages/loot-core/src/server/spreadsheet/util.js":
/*!***********************************************************!*\
!*** ./packages/loot-core/src/server/spreadsheet/util.js ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function unresolveName(name) {
let idx = name.indexOf('!');
if (idx !== -1) {
return {
sheet: name.slice(0, idx),
name: name.slice(idx + 1)
};
}
return {
sheet: null,
name
};
}
function resolveName(sheet, name) {
return sheet + '!' + name;
}
function resolveNamesAsObjects(sheets) {
const cells = {};
Object.keys(sheets).forEach(sheetName => {
const sheet = sheets[sheetName];
Object.keys(sheet).forEach(name => {
const expr = sheet[name];
cells[resolveName(sheetName, name)] = expr;
});
});
return cells;
}
function resolveNamesAsArrays(sheets) {
const cells = [];
Object.keys(sheets).forEach(sheetName => {
const sheet = sheets[sheetName];
sheet.forEach(name => {
const expr = sheet[name];
cells.push(resolveName(sheetName, name));
});
});
return cells;
}
module.exports = {
unresolveName,
resolveName,
resolveNamesAsObjects,
resolveNamesAsArrays
};
/***/ }),
/***/ "./packages/loot-core/src/server/sync/encoder.js":
/*!*******************************************************!*\
!*** ./packages/loot-core/src/server/sync/encoder.js ***!
\*******************************************************/
/*! exports provided: encode, decode */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "encode", function() { return encode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decode", function() { return decode; });
/* harmony import */ var _encryption__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../encryption */ "./packages/loot-core/src/server/encryption.js");
/* harmony import */ var _prefs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../prefs */ "./packages/loot-core/src/server/prefs.js");
let _require = __webpack_require__(/*! ../errors */ "./packages/loot-core/src/server/errors.js"),
SyncError = _require.SyncError;
let SyncPb = __webpack_require__(/*! ./proto/sync_pb */ "./packages/loot-core/src/server/sync/proto/sync_pb.js");
function coerceBuffer(value) {
// The web encryption APIs give us back raw Uint8Array... but our
// encryption code assumes we can work with it as a buffer. This is
// a leaky abstraction and ideally the our abstraction over the web
// encryption APIs should do this.
if (!Buffer.isBuffer(value)) {
return Buffer.from(value);
}
return value;
}
async function encode(groupId, fileId, since, messages) {
let _prefs$getPrefs = _prefs__WEBPACK_IMPORTED_MODULE_1__["getPrefs"](),
encryptKeyId = _prefs$getPrefs.encryptKeyId;
let requestPb = new SyncPb.SyncRequest();
for (let i = 0; i < messages.length; i++) {
let msg = messages[i];
let envelopePb = new SyncPb.MessageEnvelope();
envelopePb.setTimestamp(msg.timestamp);
let messagePb = new SyncPb.Message();
messagePb.setDataset(msg.dataset);
messagePb.setRow(msg.row);
messagePb.setColumn(msg.column);
messagePb.setValue(msg.value);
let binaryMsg = messagePb.serializeBinary();
if (encryptKeyId) {
let encrypted = new SyncPb.EncryptedData();
let result;
try {
result = await _encryption__WEBPACK_IMPORTED_MODULE_0__["default"].encrypt(binaryMsg, encryptKeyId);
} catch (e) {
throw new SyncError('encrypt-failure', {
isMissingKey: e.message === 'missing-key'
});
}
encrypted.setData(result.value);
encrypted.setIv(Buffer.from(result.meta.iv, 'base64'));
encrypted.setAuthtag(Buffer.from(result.meta.authTag, 'base64'));
envelopePb.setContent(encrypted.serializeBinary());
envelopePb.setIsencrypted(true);
} else {
envelopePb.setContent(binaryMsg);
}
requestPb.addMessages(envelopePb);
}
requestPb.setGroupid(groupId);
requestPb.setFileid(fileId);
requestPb.setKeyid(encryptKeyId);
requestPb.setSince(since);
return requestPb.serializeBinary();
}
async function decode(data) {
let _prefs$getPrefs2 = _prefs__WEBPACK_IMPORTED_MODULE_1__["getPrefs"](),
encryptKeyId = _prefs$getPrefs2.encryptKeyId;
let responsePb = SyncPb.SyncResponse.deserializeBinary(data);
let merkle = JSON.parse(responsePb.getMerkle());
let list = responsePb.getMessagesList();
let messages = [];
for (let i = 0; i < list.length; i++) {
let envelopePb = list[i];
let timestamp = envelopePb.getTimestamp();
let encrypted = envelopePb.getIsencrypted();
let msg;
if (encrypted) {
let binary = SyncPb.EncryptedData.deserializeBinary(envelopePb.getContent());
let decrypted;
try {
decrypted = await _encryption__WEBPACK_IMPORTED_MODULE_0__["default"].decrypt(coerceBuffer(binary.getData()), {
keyId: encryptKeyId,
algorithm: 'aes-256-gcm',
iv: coerceBuffer(binary.getIv()),
authTag: coerceBuffer(binary.getAuthtag())
});
} catch (e) {
console.log(e);
throw new SyncError('decrypt-failure', {
isMissingKey: e.message === 'missing-key'
});
}
msg = SyncPb.Message.deserializeBinary(decrypted);
} else {
msg = SyncPb.Message.deserializeBinary(envelopePb.getContent());
}
messages.push({
timestamp: timestamp,
dataset: msg.getDataset(),
row: msg.getRow(),
column: msg.getColumn(),
value: msg.getValue()
});
}
return {
messages,
merkle
};
}
/***/ }),
/***/ "./packages/loot-core/src/server/sync/index.js":
/*!*****************************************************!*\
!*** ./packages/loot-core/src/server/sync/index.js ***!
\*****************************************************/
/*! exports provided: setSyncingMode, checkSyncingMode, makeTestMessage, resetSync, repairSync, serializeValue, deserializeValue, addSyncListener, applyMessages, receiveMessages, batchMessages, sendMessages, getMessagesSince, syncAndReceiveMessages, clearFullSyncTimeout, scheduleFullSync, initialFullSync, fullSync */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setSyncingMode", function() { return setSyncingMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkSyncingMode", function() { return checkSyncingMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "serializeValue", function() { return serializeValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deserializeValue", function() { return deserializeValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addSyncListener", function() { return addSyncListener; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyMessages", function() { return applyMessages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "receiveMessages", function() { return receiveMessages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchMessages", function() { return batchMessages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendMessages", function() { return sendMessages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMessagesSince", function() { return getMessagesSince; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "syncAndReceiveMessages", function() { return syncAndReceiveMessages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearFullSyncTimeout", function() { return clearFullSyncTimeout; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scheduleFullSync", function() { return scheduleFullSync; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialFullSync", function() { return initialFullSync; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fullSync", function() { return fullSync; });
/* harmony import */ var _shared_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../shared/async */ "./packages/loot-core/src/shared/async.js");
/* harmony import */ var _perf__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../perf */ "./packages/loot-core/src/server/perf.js");
/* harmony import */ var _prefs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../prefs */ "./packages/loot-core/src/server/prefs.js");
/* harmony import */ var _main_app__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../main-app */ "./packages/loot-core/src/server/main-app.js");
/* harmony import */ var _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../platform/server/asyncStorage */ "./packages/loot-core/src/platform/server/asyncStorage/index.electron.js");
/* harmony import */ var _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _platform_exceptions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../platform/exceptions */ "./packages/loot-core/src/platform/exceptions/index.electron.js");
/* harmony import */ var _platform_server_log__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../platform/server/log */ "./packages/loot-core/src/platform/server/log/index.api.js");
/* harmony import */ var _post__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../post */ "./packages/loot-core/src/server/post.js");
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _sheet__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../sheet */ "./packages/loot-core/src/server/sheet.js");
/* harmony import */ var _budget_base__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../budget/base */ "./packages/loot-core/src/server/budget/base.js");
/* harmony import */ var _undo__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../undo */ "./packages/loot-core/src/server/undo.js");
/* harmony import */ var _mutators__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../mutators */ "./packages/loot-core/src/server/mutators.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../shared/util */ "./packages/loot-core/src/shared/util.js");
/* harmony import */ var _timestamp__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../timestamp */ "./packages/loot-core/src/server/timestamp.js");
/* harmony import */ var _merkle__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../merkle */ "./packages/loot-core/src/server/merkle.js");
/* harmony import */ var _encoder__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./encoder */ "./packages/loot-core/src/server/sync/encoder.js");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../config */ "./packages/loot-core/src/server/config.js");
/* harmony import */ var _repair__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./repair */ "./packages/loot-core/src/server/sync/repair.js");
/* harmony import */ var _make_test_message__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./make-test-message */ "./packages/loot-core/src/server/sync/make-test-message.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "makeTestMessage", function() { return _make_test_message__WEBPACK_IMPORTED_MODULE_19__["default"]; });
/* harmony import */ var _reset__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./reset */ "./packages/loot-core/src/server/sync/reset.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "resetSync", function() { return _reset__WEBPACK_IMPORTED_MODULE_20__["default"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "repairSync", function() { return _repair__WEBPACK_IMPORTED_MODULE_18__["default"]; });
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const _require = __webpack_require__(/*! ../errors */ "./packages/loot-core/src/server/errors.js"),
PostError = _require.PostError,
SyncError = _require.SyncError;
const connection = __webpack_require__(/*! ../../platform/server/connection */ "./packages/loot-core/src/platform/server/connection/index.api.js");
let FULL_SYNC_DELAY = 1000;
let SYNCING_MODE = 'enabled';
function setSyncingMode(mode) {
let prevMode = SYNCING_MODE;
switch (mode) {
case 'enabled':
SYNCING_MODE = 'enabled';
break;
case 'offline':
SYNCING_MODE = 'offline';
break;
case 'disabled':
SYNCING_MODE = 'disabled';
break;
case 'import':
SYNCING_MODE = 'import';
break;
default:
throw new Error('setSyncingMode: invalid mode: ' + mode);
}
return prevMode;
}
function checkSyncingMode(mode) {
switch (mode) {
case 'enabled':
return SYNCING_MODE === 'enabled' || SYNCING_MODE === 'offline';
case 'disabled':
return SYNCING_MODE === 'disabled' || SYNCING_MODE === 'import';
case 'offline':
return SYNCING_MODE === 'offline';
case 'import':
return SYNCING_MODE === 'import';
default:
throw new Error('checkSyncingMode: invalid mode: ' + mode);
}
}
function apply(msg, prev) {
let dataset = msg.dataset,
row = msg.row,
column = msg.column,
value = msg.value;
if (dataset === 'prefs') {// Do nothing, it doesn't exist in the db
} else {
try {
let query;
if (prev) {
query = {
sql: _db__WEBPACK_IMPORTED_MODULE_8__["cache"](`UPDATE ${dataset} SET ${column} = ? WHERE id = ?`),
params: [value, row]
};
} else {
query = {
sql: _db__WEBPACK_IMPORTED_MODULE_8__["cache"](`INSERT INTO ${dataset} (id, ${column}) VALUES (?, ?)`),
params: [row, value]
};
}
_db__WEBPACK_IMPORTED_MODULE_8__["runQuery"](query.sql, query.params);
} catch (e) {
//console.log(e);
throw new SyncError('invalid-schema');
}
}
}
async function fetchAll(table, ids) {
let results = []; // TODO: convert to `whereIn`
for (let i = 0; i < ids.length; i += 500) {
let partIds = ids.slice(i, i + 500);
let sql;
let column = `${table}.id`; // We have to provide *mapped* data so the spreadsheet works. The functions
// which trigger budget changes based on data changes assumes data has been
// mapped. The only mapped data that the budget is concerned about is
// categories. This is kind of annoying, but we manually map it here
if (table === 'transactions') {
sql = `
SELECT t.*, c.transferId AS category
FROM transactions t
LEFT JOIN category_mapping c ON c.id = t.category
`;
column = 't.id';
} else {
sql = `SELECT * FROM ${table}`;
}
sql += ` WHERE `;
sql += partIds.map(id => `${column} = ?`).join(' OR ');
try {
let rows = await _db__WEBPACK_IMPORTED_MODULE_8__["runQuery"](sql, partIds, true);
results = results.concat(rows);
} catch (e) {
throw new SyncError('invalid-schema');
}
}
return results;
}
function serializeValue(value) {
if (value === null) {
return '0:';
} else if (typeof value === 'number') {
return 'N:' + value;
} else if (typeof value === 'string') {
return 'S:' + value;
}
throw new Error('Unserializable value type: ' + JSON.stringify(value));
}
function deserializeValue(value) {
const type = value[0];
switch (type) {
case '0':
return null;
case 'N':
return parseFloat(value.slice(2));
case 'S':
return value.slice(2);
default:
}
throw new Error('Invalid type key for value: ' + value);
}
let _syncListeners = [];
function addSyncListener(func) {
_syncListeners.push(func);
return () => {
_syncListeners = _syncListeners.filter(f => f !== func);
};
}
async function compareMessages(messages) {
let newMessages = [];
for (let i = 0; i < messages.length; i++) {
let message = messages[i];
let dataset = message.dataset,
row = message.row,
column = message.column,
timestamp = message.timestamp;
let timestampStr = timestamp.toString();
let res = _db__WEBPACK_IMPORTED_MODULE_8__["runQuery"](_db__WEBPACK_IMPORTED_MODULE_8__["cache"]('SELECT timestamp FROM messages_crdt WHERE dataset = ? AND row = ? AND column = ? AND timestamp >= ?'), [dataset, row, column, timestampStr], true); // Returned message is any one that is "later" than this message,
// meaning if the result exists this message is an old one
if (res.length === 0) {
newMessages.push(message);
} else if (res[0].timestamp !== timestampStr) {
newMessages.push(_objectSpread(_objectSpread({}, message), {}, {
old: true
}));
}
}
return newMessages;
} // This is the fast path `apply` function when in "import" mode.
// There's no need to run through the whole sync system when
// importing, but **there is a caveat**: because we don't run sync
// listeners importers should not rely on any functions that use any
// projected state (like rules). We can't fire those because they
// depend on having both old and new data which we don't quere here
function applyMessagesForImport(messages) {
_db__WEBPACK_IMPORTED_MODULE_8__["transaction"](() => {
for (let i = 0; i < messages.length; i++) {
let msg = messages[i];
let dataset = msg.dataset,
row = msg.row,
column = msg.column,
timestamp = msg.timestamp,
value = msg.value;
if (!msg.old) {
try {
apply(msg);
} catch (e) {
apply(msg, true);
}
if (dataset === 'prefs') {
throw new Error('Cannot set prefs while importing');
}
}
}
});
}
const applyMessages = Object(_shared_async__WEBPACK_IMPORTED_MODULE_0__["sequential"])(async messages => {
if (checkSyncingMode('import')) {
return applyMessagesForImport(messages);
} else if (checkSyncingMode('enabled')) {
// Compare the messages with the existing crdt. This filters out
// already applied messages and determines if a message is old or
// not. An "old" message doesn't need to be applied, but it still
// needs to be put into the merkle trie to maintain the hash.
messages = await compareMessages(messages);
}
messages = [...messages].sort((m1, m2) => {
let t1 = m1.timestamp ? m1.timestamp.toString() : '';
let t2 = m2.timestamp ? m2.timestamp.toString() : '';
if (t1 < t2) {
return -1;
} else if (t1 > t2) {
return 1;
}
return 0;
});
let idsPerTable = {};
messages.forEach(msg => {
if (msg.dataset === 'prefs') {
return;
}
if (idsPerTable[msg.dataset] == null) {
idsPerTable[msg.dataset] = [];
}
idsPerTable[msg.dataset].push(msg.row);
});
async function fetchData() {
let data = new Map();
for (let table of Object.keys(idsPerTable)) {
const rows = await fetchAll(table, idsPerTable[table]);
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
Object(_shared_util__WEBPACK_IMPORTED_MODULE_13__["setIn"])(data, [table, row.id], row);
}
}
return data;
}
let prefsToSet = {};
let oldData = await fetchData();
_undo__WEBPACK_IMPORTED_MODULE_11__["appendMessages"](messages, oldData); // It's important to not mutate the clock while processing the
// messages. We only want to mutate it if the transaction succeeds.
// The merkle variable will be updated while applying the messages and
// we'll apply it afterwards.
let clock;
let currentMerkle;
if (checkSyncingMode('enabled')) {
clock = Object(_timestamp__WEBPACK_IMPORTED_MODULE_14__["getClock"])();
currentMerkle = clock.merkle;
}
if (_sheet__WEBPACK_IMPORTED_MODULE_9__["get"]()) {
_sheet__WEBPACK_IMPORTED_MODULE_9__["get"]().startCacheBarrier();
} // Now that we have all of the data, go through and apply the
// messages carefully. This transaction is **crucial**: it
// guarantees that everything is atomically committed to the
// database, and if any part of it fails everything aborts and
// nothing is changed. This is critical to maintain consistency. We
// also avoid any side effects to in-memory objects, and apply them
// after this succeeds.
_db__WEBPACK_IMPORTED_MODULE_8__["transaction"](() => {
let added = new Set();
for (let i = 0; i < messages.length; i++) {
let msg = messages[i];
let dataset = msg.dataset,
row = msg.row,
column = msg.column,
timestamp = msg.timestamp,
value = msg.value;
if (!msg.old) {
apply(msg, Object(_shared_util__WEBPACK_IMPORTED_MODULE_13__["getIn"])(oldData, [dataset, row]) || added.has(dataset + row));
if (dataset === 'prefs') {
prefsToSet[row] = value;
} else {
// Keep track of which items have been added it in this sync
// so it knows whether they already exist in the db or not. We
// ignore any changes to the spreadsheet.
added.add(dataset + row);
}
}
if (checkSyncingMode('enabled')) {
_db__WEBPACK_IMPORTED_MODULE_8__["runQuery"](_db__WEBPACK_IMPORTED_MODULE_8__["cache"](`INSERT INTO messages_crdt (timestamp, dataset, row, column, value)
VALUES (?, ?, ?, ?, ?)`), [timestamp.toString(), dataset, row, column, serializeValue(value)]);
currentMerkle = _merkle__WEBPACK_IMPORTED_MODULE_15__["insert"](currentMerkle, msg.timestamp);
}
}
if (checkSyncingMode('enabled')) {
currentMerkle = _merkle__WEBPACK_IMPORTED_MODULE_15__["prune"](currentMerkle); // Save the clock in the db first (queries might throw
// exceptions)
_db__WEBPACK_IMPORTED_MODULE_8__["runQuery"](_db__WEBPACK_IMPORTED_MODULE_8__["cache"]('INSERT OR REPLACE INTO messages_clock (id, clock) VALUES (1, ?)'), [Object(_timestamp__WEBPACK_IMPORTED_MODULE_14__["serializeClock"])(_objectSpread(_objectSpread({}, clock), {}, {
merkle: currentMerkle
}))]);
}
});
if (checkSyncingMode('enabled')) {
// The transaction succeeded, so we can update in-memory objects
// now. Update the in-memory clock.
clock.merkle = currentMerkle;
} // Save any synced prefs
if (Object.keys(prefsToSet).length > 0) {
_prefs__WEBPACK_IMPORTED_MODULE_2__["savePrefs"](prefsToSet, {
avoidSync: true
});
if (prefsToSet.budgetType) {
Object(_budget_base__WEBPACK_IMPORTED_MODULE_10__["setType"])(prefsToSet.budgetType);
}
connection.send('prefs-updated');
}
let newData = await fetchData(); // In testing, sometimes the spreadsheet isn't loaded, and that's ok
if (_sheet__WEBPACK_IMPORTED_MODULE_9__["get"]()) {
// Need to clean up these APIs and make them consistent
_sheet__WEBPACK_IMPORTED_MODULE_9__["startTransaction"]();
Object(_budget_base__WEBPACK_IMPORTED_MODULE_10__["triggerBudgetChanges"])(oldData, newData);
_sheet__WEBPACK_IMPORTED_MODULE_9__["get"]().triggerDatabaseChanges(oldData, newData);
_sheet__WEBPACK_IMPORTED_MODULE_9__["endTransaction"](); // Allow the cache to be used in the future. At this point it's guaranteed
// to be up-to-date because we are done mutating any other data
_sheet__WEBPACK_IMPORTED_MODULE_9__["get"]().endCacheBarrier();
}
_syncListeners.forEach(func => func(oldData, newData));
let tables = getTablesFromMessages(messages.filter(msg => !msg.old));
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'applied',
tables,
data: newData,
prevData: oldData
});
return messages;
});
function receiveMessages(messages) {
messages.forEach(msg => {
_timestamp__WEBPACK_IMPORTED_MODULE_14__["default"].recv(msg.timestamp);
});
return Object(_mutators__WEBPACK_IMPORTED_MODULE_12__["runMutator"])(() => applyMessages(messages));
}
async function _sendMessages(messages) {
try {
await applyMessages(messages);
} catch (e) {
if (e instanceof SyncError) {
if (e.reason === 'invalid-schema') {
// We know this message came from a local modification, and it
// couldn't apply, which doesn't make any sense. Must be a bug
// in the code. Send a specific error type for it for a custom
// message.
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'error',
subtype: 'apply-failure'
});
} else {
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'error'
});
}
}
throw e;
}
await scheduleFullSync();
}
let IS_BATCHING = false;
let _BATCHED = [];
async function batchMessages(func) {
if (IS_BATCHING) {
await func();
return;
}
IS_BATCHING = true;
let batched = [];
try {
await func(); // TODO: if it fails, it shouldn't apply them?
} finally {
IS_BATCHING = false;
batched = _BATCHED;
_BATCHED = [];
}
if (batched.length > 0) {
await _sendMessages(batched);
}
}
async function sendMessages(messages) {
if (IS_BATCHING) {
_BATCHED = _BATCHED.concat(messages);
} else {
return _sendMessages(messages);
}
}
function getMessagesSince(since) {
return _db__WEBPACK_IMPORTED_MODULE_8__["runQuery"]('SELECT timestamp, dataset, row, column, value FROM messages_crdt WHERE timestamp > ?', [since], true);
}
async function syncAndReceiveMessages(messages, since) {
let localMessages = await getMessagesSince(since);
await receiveMessages(messages.map(msg => _objectSpread(_objectSpread({}, msg), {}, {
value: deserializeValue(msg.value),
timestamp: _timestamp__WEBPACK_IMPORTED_MODULE_14__["default"].parse(msg.timestamp)
})));
return localMessages;
}
function clearFullSyncTimeout() {
if (syncTimeout) {
clearTimeout(syncTimeout);
syncTimeout = null;
}
}
let syncTimeout = null;
function scheduleFullSync() {
clearFullSyncTimeout();
if (checkSyncingMode('enabled') && !checkSyncingMode('offline')) {
if (global.__TESTING__) {
return fullSync().then(res => {
if (res.error) {
throw res.error;
}
return res;
});
} else {
syncTimeout = setTimeout(fullSync, FULL_SYNC_DELAY);
}
}
}
function getTablesFromMessages(messages) {
return messages.reduce((acc, message) => {
let dataset = message.dataset === 'schedules_next_date' ? 'schedules' : message.dataset;
if (!acc.includes(dataset)) {
acc.push(dataset);
}
return acc;
}, []);
} // This is different than `fullSync` because it waits for the
// spreadsheet to finish any processing. This is useful if we want to
// perform a full sync and wait for everything to finish, usually if
// you're doing an initial sync before working with a file.
async function initialFullSync() {
let result = await fullSync();
if (!result.error) {
// Make sure to wait for anything in the spreadsheet to process
await _sheet__WEBPACK_IMPORTED_MODULE_9__["waitOnSpreadsheet"]();
}
}
const fullSync = Object(_shared_async__WEBPACK_IMPORTED_MODULE_0__["once"])(async function () {
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'start'
});
let messages;
try {
messages = await _fullSync(null, 0, null);
} catch (e) {
console.log(e);
if (e instanceof SyncError) {
if (e.reason === 'out-of-sync') {
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_5__["captureException"])(e);
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'error',
subtype: 'out-of-sync'
});
} else if (e.reason === 'invalid-schema') {
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'error',
subtype: 'invalid-schema'
});
} else if (e.reason === 'decrypt-failure' || e.reason === 'encrypt-failure') {
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'error',
subtype: e.reason,
meta: e.meta
});
} else if (e.reason === 'beta-version') {
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'error',
subtype: e.reason
});
} else {
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'error'
});
}
} else if (e instanceof PostError) {
console.log(e);
if (e.reason === 'unauthorized') {
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'unauthorized'
}); // Set the user into read-only mode
_platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_4___default.a.setItem('readOnly', 'true');
} else if (e.reason === 'network-failure') {
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'error',
subtype: 'network'
});
} else {
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'error',
subtype: e.reason
});
}
} else {
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_5__["captureException"])(e); // TODO: Send the message to the client and allow them to expand & view it
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'error'
});
}
return {
error: {
message: e.message,
reason: e.reason,
meta: e.meta
}
};
}
let tables = getTablesFromMessages(messages);
_main_app__WEBPACK_IMPORTED_MODULE_3__["default"].events.emit('sync', {
type: 'success',
tables,
syncDisabled: checkSyncingMode('disabled')
});
return {
messages
};
});
async function _fullSync(sinceTimestamp, count, prevDiffTime) {
let _ref = _prefs__WEBPACK_IMPORTED_MODULE_2__["getPrefs"]() || {},
cloudFileId = _ref.cloudFileId,
groupId = _ref.groupId,
lastSyncedTimestamp = _ref.lastSyncedTimestamp;
clearFullSyncTimeout();
if (checkSyncingMode('disabled') || checkSyncingMode('offline')) {
return [];
} // Snapshot the point at which we are currently syncing
let currentTime = Object(_timestamp__WEBPACK_IMPORTED_MODULE_14__["getClock"])().timestamp.toString();
let since = sinceTimestamp || lastSyncedTimestamp || // Default to 5 minutes ago
new _timestamp__WEBPACK_IMPORTED_MODULE_14__["default"](Date.now() - 5 * 60 * 1000, 0, '0').toString();
let messages = getMessagesSince(since);
let userToken = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_4___default.a.getItem('user-token');
_platform_server_log__WEBPACK_IMPORTED_MODULE_6__["default"].info('Syncing since', since, messages.length, '(attempt: ' + count + ')');
let buffer = await _encoder__WEBPACK_IMPORTED_MODULE_16__["encode"](groupId, cloudFileId, since, messages); // TODO: There a limit on how many messages we can send because of
// the payload size. Right now it's at 20MB on the server. We should
// check the worst case here and make multiple requests if it's
// really large.
let resBuffer = await Object(_post__WEBPACK_IMPORTED_MODULE_7__["postBinary"])(Object(_config__WEBPACK_IMPORTED_MODULE_17__["getConfig"])().SYNC_SERVER + '/sync', buffer, {
'X-ACTUAL-TOKEN': userToken
}); // Abort if the file is either no longer loaded, the group id has
// changed because of a sync reset
if (!_prefs__WEBPACK_IMPORTED_MODULE_2__["getPrefs"]() || _prefs__WEBPACK_IMPORTED_MODULE_2__["getPrefs"]().groupId !== groupId) {
return [];
}
let res = await _encoder__WEBPACK_IMPORTED_MODULE_16__["decode"](resBuffer);
_platform_server_log__WEBPACK_IMPORTED_MODULE_6__["default"].info('Got messages from server', res.messages.length);
let localTimeChanged = Object(_timestamp__WEBPACK_IMPORTED_MODULE_14__["getClock"])().timestamp.toString() !== currentTime; // Apply the new messages
let receivedMessages = [];
if (res.messages.length > 0) {
receivedMessages = await receiveMessages(res.messages.map(msg => _objectSpread(_objectSpread({}, msg), {}, {
value: deserializeValue(msg.value),
timestamp: _timestamp__WEBPACK_IMPORTED_MODULE_14__["default"].parse(msg.timestamp)
})));
}
let diffTime = _merkle__WEBPACK_IMPORTED_MODULE_15__["diff"](res.merkle, Object(_timestamp__WEBPACK_IMPORTED_MODULE_14__["getClock"])().merkle);
let result = res.messages;
if (diffTime !== null) {
// This is a bit wonky, but we loop until we are in sync with the
// server. While syncing, either the client or server could change
// out from under us, so it might take a couple passes to
// completely sync up. This is a check that stops the loop in case
// we are corrupted and can't sync up. We try 10 times if we keep
// getting the same diff time, and add a upper limit of 300 no
// matter what (just to stop this from ever being an infinite
// loop).
//
// It's slightly possible for the user to add more messages while we
// are in `receiveMessages`, but `localTimeChanged` would still be
// false. In that case, we don't reset the counter but it should be
// very unlikely that this happens enough to hit the loop limit.
if (count >= 10 && diffTime === prevDiffTime || count >= 100) {
_platform_server_log__WEBPACK_IMPORTED_MODULE_6__["default"].info('SENT -------');
_platform_server_log__WEBPACK_IMPORTED_MODULE_6__["default"].info(JSON.stringify(messages));
_platform_server_log__WEBPACK_IMPORTED_MODULE_6__["default"].info('RECEIVED -------');
_platform_server_log__WEBPACK_IMPORTED_MODULE_6__["default"].info(JSON.stringify(res.messages));
let rebuiltMerkle = Object(_repair__WEBPACK_IMPORTED_MODULE_18__["rebuildMerkleHash"])();
console.log(count, 'messages:', messages.length, messages.length > 0 ? messages[0] : null, 'res.messages:', res.messages.length, res.messages.length > 0 ? res.messages[0] : null, 'clientId', Object(_timestamp__WEBPACK_IMPORTED_MODULE_14__["getClock"])().timestamp.node(), 'groupId', groupId, 'diffTime:', diffTime, diffTime === prevDiffTime, 'local clock:', Object(_timestamp__WEBPACK_IMPORTED_MODULE_14__["getClock"])().timestamp.toString(), Object(_timestamp__WEBPACK_IMPORTED_MODULE_14__["getClock"])().merkle.hash, 'rebuilt hash:', rebuiltMerkle.numMessages, rebuiltMerkle.trie.hash, 'server hash:', res.merkle.hash, 'localTimeChanged:', localTimeChanged);
if (rebuiltMerkle.trie.hash === res.merkle.hash) {
// Rebuilding the merkle worked... but why?
let clocks = await _db__WEBPACK_IMPORTED_MODULE_8__["all"]('SELECT * FROM messages_clock');
if (clocks.length !== 1) {
console.log('Bad number of clocks:', clocks.length);
}
let hash = Object(_timestamp__WEBPACK_IMPORTED_MODULE_14__["deserializeClock"])(clocks[0]).merkle.hash;
console.log('Merkle hash in db:', hash);
}
throw new SyncError('out-of-sync');
}
receivedMessages = receivedMessages.concat(await _fullSync(new _timestamp__WEBPACK_IMPORTED_MODULE_14__["default"](diffTime, 0, '0').toString(), // If something local changed while we were syncing, always
// reset, token the counter. We never want to think syncing failed
// because we tried to syncing many times and couldn't sync,
// but it was because the user kept changing stuff in the
// middle of syncing.
localTimeChanged ? 0 : count + 1, diffTime));
} else {
// All synced up, store the current time as a simple optimization
// for the next sync
await _prefs__WEBPACK_IMPORTED_MODULE_2__["savePrefs"]({
lastSyncedTimestamp: Object(_timestamp__WEBPACK_IMPORTED_MODULE_14__["getClock"])().timestamp.toString()
});
}
return receivedMessages;
}
/***/ }),
/***/ "./packages/loot-core/src/server/sync/make-test-message.js":
/*!*****************************************************************!*\
!*** ./packages/loot-core/src/server/sync/make-test-message.js ***!
\*****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return makeTestMessage; });
/* harmony import */ var _encryption__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../encryption */ "./packages/loot-core/src/server/encryption.js");
let SyncPb = __webpack_require__(/*! ./proto/sync_pb */ "./packages/loot-core/src/server/sync/proto/sync_pb.js");
async function randomString() {
return (await _encryption__WEBPACK_IMPORTED_MODULE_0__["default"].randomBytes(12)).toString();
}
async function makeTestMessage(keyId) {
let messagePb = new SyncPb.Message();
messagePb.setDataset(await randomString());
messagePb.setRow(await randomString());
messagePb.setColumn(await randomString());
messagePb.setValue(await randomString());
let binaryMsg = messagePb.serializeBinary();
return await _encryption__WEBPACK_IMPORTED_MODULE_0__["default"].encrypt(binaryMsg, keyId);
}
/***/ }),
/***/ "./packages/loot-core/src/server/sync/migrate.js":
/*!*******************************************************!*\
!*** ./packages/loot-core/src/server/sync/migrate.js ***!
\*******************************************************/
/*! exports provided: listen, unlisten */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "listen", function() { return listen; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unlisten", function() { return unlisten; });
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./index */ "./packages/loot-core/src/server/sync/index.js");
/* harmony import */ var _timestamp__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../timestamp */ "./packages/loot-core/src/server/timestamp.js");
function migrateParentIds(oldValues, newValues) {
newValues.forEach((items, table) => {
if (table === 'transactions') {
let old = oldValues.get(table);
let toApply = [];
items.forEach(newValue => {
if (newValue.isChild === 1 && newValue.parent_id == null && newValue.id.includes('/')) {
let parentId = newValue.id.split('/')[0];
toApply.push({
dataset: 'transactions',
row: newValue.id,
column: 'parent_id',
value: parentId,
timestamp: _timestamp__WEBPACK_IMPORTED_MODULE_1__["default"].send()
});
}
});
if (toApply.length > 0) {
Object(_index__WEBPACK_IMPORTED_MODULE_0__["applyMessages"])(toApply);
}
}
});
}
let _unlisten = null;
function listen() {
unlisten();
_unlisten = Object(_index__WEBPACK_IMPORTED_MODULE_0__["addSyncListener"])(migrateParentIds);
}
function unlisten() {
if (_unlisten) {
_unlisten();
_unlisten = null;
}
}
/***/ }),
/***/ "./packages/loot-core/src/server/sync/proto/sync_pb.js":
/*!*************************************************************!*\
!*** ./packages/loot-core/src/server/sync/proto/sync_pb.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// source: sync.proto
/**
* @fileoverview
* @enhanceable
* @suppress {messageConventions} JS Compiler reports an error if a variable or
* field starts with 'MSG_' and isn't a translatable message.
* @public
*/
// GENERATED CODE -- DO NOT EDIT!
var jspb = __webpack_require__(/*! google-protobuf */ "./node_modules/google-protobuf/google-protobuf.js");
var goog = jspb;
var global = globalThis;
goog.exportSymbol('proto.EncryptedData', null, global);
goog.exportSymbol('proto.Message', null, global);
goog.exportSymbol('proto.MessageEnvelope', null, global);
goog.exportSymbol('proto.SyncRequest', null, global);
goog.exportSymbol('proto.SyncResponse', null, global);
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.EncryptedData = function (opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.EncryptedData, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.EncryptedData.displayName = 'proto.EncryptedData';
}
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.Message = function (opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.Message, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.Message.displayName = 'proto.Message';
}
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.MessageEnvelope = function (opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.MessageEnvelope, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.MessageEnvelope.displayName = 'proto.MessageEnvelope';
}
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.SyncRequest = function (opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, proto.SyncRequest.repeatedFields_, null);
};
goog.inherits(proto.SyncRequest, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.SyncRequest.displayName = 'proto.SyncRequest';
}
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.SyncResponse = function (opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, proto.SyncResponse.repeatedFields_, null);
};
goog.inherits(proto.SyncResponse, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.SyncResponse.displayName = 'proto.SyncResponse';
}
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.EncryptedData.prototype.toObject = function (opt_includeInstance) {
return proto.EncryptedData.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.EncryptedData} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.EncryptedData.toObject = function (includeInstance, msg) {
var f,
obj = {
iv: msg.getIv_asB64(),
authtag: msg.getAuthtag_asB64(),
data: msg.getData_asB64()
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.EncryptedData}
*/
proto.EncryptedData.deserializeBinary = function (bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.EncryptedData();
return proto.EncryptedData.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.EncryptedData} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.EncryptedData}
*/
proto.EncryptedData.deserializeBinaryFromReader = function (msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value =
/** @type {!Uint8Array} */
reader.readBytes();
msg.setIv(value);
break;
case 2:
var value =
/** @type {!Uint8Array} */
reader.readBytes();
msg.setAuthtag(value);
break;
case 3:
var value =
/** @type {!Uint8Array} */
reader.readBytes();
msg.setData(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.EncryptedData.prototype.serializeBinary = function () {
var writer = new jspb.BinaryWriter();
proto.EncryptedData.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.EncryptedData} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.EncryptedData.serializeBinaryToWriter = function (message, writer) {
var f = undefined;
f = message.getIv_asU8();
if (f.length > 0) {
writer.writeBytes(1, f);
}
f = message.getAuthtag_asU8();
if (f.length > 0) {
writer.writeBytes(2, f);
}
f = message.getData_asU8();
if (f.length > 0) {
writer.writeBytes(3, f);
}
};
/**
* optional bytes iv = 1;
* @return {!(string|Uint8Array)}
*/
proto.EncryptedData.prototype.getIv = function () {
return (
/** @type {!(string|Uint8Array)} */
jspb.Message.getFieldWithDefault(this, 1, "")
);
};
/**
* optional bytes iv = 1;
* This is a type-conversion wrapper around `getIv()`
* @return {string}
*/
proto.EncryptedData.prototype.getIv_asB64 = function () {
return (
/** @type {string} */
jspb.Message.bytesAsB64(this.getIv())
);
};
/**
* optional bytes iv = 1;
* Note that Uint8Array is not supported on all browsers.
* @see http://caniuse.com/Uint8Array
* This is a type-conversion wrapper around `getIv()`
* @return {!Uint8Array}
*/
proto.EncryptedData.prototype.getIv_asU8 = function () {
return (
/** @type {!Uint8Array} */
jspb.Message.bytesAsU8(this.getIv())
);
};
/**
* @param {!(string|Uint8Array)} value
* @return {!proto.EncryptedData} returns this
*/
proto.EncryptedData.prototype.setIv = function (value) {
return jspb.Message.setProto3BytesField(this, 1, value);
};
/**
* optional bytes authTag = 2;
* @return {!(string|Uint8Array)}
*/
proto.EncryptedData.prototype.getAuthtag = function () {
return (
/** @type {!(string|Uint8Array)} */
jspb.Message.getFieldWithDefault(this, 2, "")
);
};
/**
* optional bytes authTag = 2;
* This is a type-conversion wrapper around `getAuthtag()`
* @return {string}
*/
proto.EncryptedData.prototype.getAuthtag_asB64 = function () {
return (
/** @type {string} */
jspb.Message.bytesAsB64(this.getAuthtag())
);
};
/**
* optional bytes authTag = 2;
* Note that Uint8Array is not supported on all browsers.
* @see http://caniuse.com/Uint8Array
* This is a type-conversion wrapper around `getAuthtag()`
* @return {!Uint8Array}
*/
proto.EncryptedData.prototype.getAuthtag_asU8 = function () {
return (
/** @type {!Uint8Array} */
jspb.Message.bytesAsU8(this.getAuthtag())
);
};
/**
* @param {!(string|Uint8Array)} value
* @return {!proto.EncryptedData} returns this
*/
proto.EncryptedData.prototype.setAuthtag = function (value) {
return jspb.Message.setProto3BytesField(this, 2, value);
};
/**
* optional bytes data = 3;
* @return {!(string|Uint8Array)}
*/
proto.EncryptedData.prototype.getData = function () {
return (
/** @type {!(string|Uint8Array)} */
jspb.Message.getFieldWithDefault(this, 3, "")
);
};
/**
* optional bytes data = 3;
* This is a type-conversion wrapper around `getData()`
* @return {string}
*/
proto.EncryptedData.prototype.getData_asB64 = function () {
return (
/** @type {string} */
jspb.Message.bytesAsB64(this.getData())
);
};
/**
* optional bytes data = 3;
* Note that Uint8Array is not supported on all browsers.
* @see http://caniuse.com/Uint8Array
* This is a type-conversion wrapper around `getData()`
* @return {!Uint8Array}
*/
proto.EncryptedData.prototype.getData_asU8 = function () {
return (
/** @type {!Uint8Array} */
jspb.Message.bytesAsU8(this.getData())
);
};
/**
* @param {!(string|Uint8Array)} value
* @return {!proto.EncryptedData} returns this
*/
proto.EncryptedData.prototype.setData = function (value) {
return jspb.Message.setProto3BytesField(this, 3, value);
};
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.Message.prototype.toObject = function (opt_includeInstance) {
return proto.Message.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.Message} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.Message.toObject = function (includeInstance, msg) {
var f,
obj = {
dataset: jspb.Message.getFieldWithDefault(msg, 1, ""),
row: jspb.Message.getFieldWithDefault(msg, 2, ""),
column: jspb.Message.getFieldWithDefault(msg, 3, ""),
value: jspb.Message.getFieldWithDefault(msg, 4, "")
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.Message}
*/
proto.Message.deserializeBinary = function (bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.Message();
return proto.Message.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.Message} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.Message}
*/
proto.Message.deserializeBinaryFromReader = function (msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value =
/** @type {string} */
reader.readString();
msg.setDataset(value);
break;
case 2:
var value =
/** @type {string} */
reader.readString();
msg.setRow(value);
break;
case 3:
var value =
/** @type {string} */
reader.readString();
msg.setColumn(value);
break;
case 4:
var value =
/** @type {string} */
reader.readString();
msg.setValue(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.Message.prototype.serializeBinary = function () {
var writer = new jspb.BinaryWriter();
proto.Message.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.Message} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.Message.serializeBinaryToWriter = function (message, writer) {
var f = undefined;
f = message.getDataset();
if (f.length > 0) {
writer.writeString(1, f);
}
f = message.getRow();
if (f.length > 0) {
writer.writeString(2, f);
}
f = message.getColumn();
if (f.length > 0) {
writer.writeString(3, f);
}
f = message.getValue();
if (f.length > 0) {
writer.writeString(4, f);
}
};
/**
* optional string dataset = 1;
* @return {string}
*/
proto.Message.prototype.getDataset = function () {
return (
/** @type {string} */
jspb.Message.getFieldWithDefault(this, 1, "")
);
};
/**
* @param {string} value
* @return {!proto.Message} returns this
*/
proto.Message.prototype.setDataset = function (value) {
return jspb.Message.setProto3StringField(this, 1, value);
};
/**
* optional string row = 2;
* @return {string}
*/
proto.Message.prototype.getRow = function () {
return (
/** @type {string} */
jspb.Message.getFieldWithDefault(this, 2, "")
);
};
/**
* @param {string} value
* @return {!proto.Message} returns this
*/
proto.Message.prototype.setRow = function (value) {
return jspb.Message.setProto3StringField(this, 2, value);
};
/**
* optional string column = 3;
* @return {string}
*/
proto.Message.prototype.getColumn = function () {
return (
/** @type {string} */
jspb.Message.getFieldWithDefault(this, 3, "")
);
};
/**
* @param {string} value
* @return {!proto.Message} returns this
*/
proto.Message.prototype.setColumn = function (value) {
return jspb.Message.setProto3StringField(this, 3, value);
};
/**
* optional string value = 4;
* @return {string}
*/
proto.Message.prototype.getValue = function () {
return (
/** @type {string} */
jspb.Message.getFieldWithDefault(this, 4, "")
);
};
/**
* @param {string} value
* @return {!proto.Message} returns this
*/
proto.Message.prototype.setValue = function (value) {
return jspb.Message.setProto3StringField(this, 4, value);
};
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.MessageEnvelope.prototype.toObject = function (opt_includeInstance) {
return proto.MessageEnvelope.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.MessageEnvelope} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.MessageEnvelope.toObject = function (includeInstance, msg) {
var f,
obj = {
timestamp: jspb.Message.getFieldWithDefault(msg, 1, ""),
isencrypted: jspb.Message.getBooleanFieldWithDefault(msg, 2, false),
content: msg.getContent_asB64()
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.MessageEnvelope}
*/
proto.MessageEnvelope.deserializeBinary = function (bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.MessageEnvelope();
return proto.MessageEnvelope.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.MessageEnvelope} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.MessageEnvelope}
*/
proto.MessageEnvelope.deserializeBinaryFromReader = function (msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value =
/** @type {string} */
reader.readString();
msg.setTimestamp(value);
break;
case 2:
var value =
/** @type {boolean} */
reader.readBool();
msg.setIsencrypted(value);
break;
case 3:
var value =
/** @type {!Uint8Array} */
reader.readBytes();
msg.setContent(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.MessageEnvelope.prototype.serializeBinary = function () {
var writer = new jspb.BinaryWriter();
proto.MessageEnvelope.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.MessageEnvelope} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.MessageEnvelope.serializeBinaryToWriter = function (message, writer) {
var f = undefined;
f = message.getTimestamp();
if (f.length > 0) {
writer.writeString(1, f);
}
f = message.getIsencrypted();
if (f) {
writer.writeBool(2, f);
}
f = message.getContent_asU8();
if (f.length > 0) {
writer.writeBytes(3, f);
}
};
/**
* optional string timestamp = 1;
* @return {string}
*/
proto.MessageEnvelope.prototype.getTimestamp = function () {
return (
/** @type {string} */
jspb.Message.getFieldWithDefault(this, 1, "")
);
};
/**
* @param {string} value
* @return {!proto.MessageEnvelope} returns this
*/
proto.MessageEnvelope.prototype.setTimestamp = function (value) {
return jspb.Message.setProto3StringField(this, 1, value);
};
/**
* optional bool isEncrypted = 2;
* @return {boolean}
*/
proto.MessageEnvelope.prototype.getIsencrypted = function () {
return (
/** @type {boolean} */
jspb.Message.getBooleanFieldWithDefault(this, 2, false)
);
};
/**
* @param {boolean} value
* @return {!proto.MessageEnvelope} returns this
*/
proto.MessageEnvelope.prototype.setIsencrypted = function (value) {
return jspb.Message.setProto3BooleanField(this, 2, value);
};
/**
* optional bytes content = 3;
* @return {!(string|Uint8Array)}
*/
proto.MessageEnvelope.prototype.getContent = function () {
return (
/** @type {!(string|Uint8Array)} */
jspb.Message.getFieldWithDefault(this, 3, "")
);
};
/**
* optional bytes content = 3;
* This is a type-conversion wrapper around `getContent()`
* @return {string}
*/
proto.MessageEnvelope.prototype.getContent_asB64 = function () {
return (
/** @type {string} */
jspb.Message.bytesAsB64(this.getContent())
);
};
/**
* optional bytes content = 3;
* Note that Uint8Array is not supported on all browsers.
* @see http://caniuse.com/Uint8Array
* This is a type-conversion wrapper around `getContent()`
* @return {!Uint8Array}
*/
proto.MessageEnvelope.prototype.getContent_asU8 = function () {
return (
/** @type {!Uint8Array} */
jspb.Message.bytesAsU8(this.getContent())
);
};
/**
* @param {!(string|Uint8Array)} value
* @return {!proto.MessageEnvelope} returns this
*/
proto.MessageEnvelope.prototype.setContent = function (value) {
return jspb.Message.setProto3BytesField(this, 3, value);
};
/**
* List of repeated fields within this message type.
* @private {!Array<number>}
* @const
*/
proto.SyncRequest.repeatedFields_ = [1];
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.SyncRequest.prototype.toObject = function (opt_includeInstance) {
return proto.SyncRequest.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.SyncRequest} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.SyncRequest.toObject = function (includeInstance, msg) {
var f,
obj = {
messagesList: jspb.Message.toObjectList(msg.getMessagesList(), proto.MessageEnvelope.toObject, includeInstance),
fileid: jspb.Message.getFieldWithDefault(msg, 2, ""),
groupid: jspb.Message.getFieldWithDefault(msg, 3, ""),
keyid: jspb.Message.getFieldWithDefault(msg, 5, ""),
since: jspb.Message.getFieldWithDefault(msg, 6, "")
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.SyncRequest}
*/
proto.SyncRequest.deserializeBinary = function (bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.SyncRequest();
return proto.SyncRequest.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.SyncRequest} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.SyncRequest}
*/
proto.SyncRequest.deserializeBinaryFromReader = function (msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = new proto.MessageEnvelope();
reader.readMessage(value, proto.MessageEnvelope.deserializeBinaryFromReader);
msg.addMessages(value);
break;
case 2:
var value =
/** @type {string} */
reader.readString();
msg.setFileid(value);
break;
case 3:
var value =
/** @type {string} */
reader.readString();
msg.setGroupid(value);
break;
case 5:
var value =
/** @type {string} */
reader.readString();
msg.setKeyid(value);
break;
case 6:
var value =
/** @type {string} */
reader.readString();
msg.setSince(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.SyncRequest.prototype.serializeBinary = function () {
var writer = new jspb.BinaryWriter();
proto.SyncRequest.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.SyncRequest} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.SyncRequest.serializeBinaryToWriter = function (message, writer) {
var f = undefined;
f = message.getMessagesList();
if (f.length > 0) {
writer.writeRepeatedMessage(1, f, proto.MessageEnvelope.serializeBinaryToWriter);
}
f = message.getFileid();
if (f.length > 0) {
writer.writeString(2, f);
}
f = message.getGroupid();
if (f.length > 0) {
writer.writeString(3, f);
}
f = message.getKeyid();
if (f.length > 0) {
writer.writeString(5, f);
}
f = message.getSince();
if (f.length > 0) {
writer.writeString(6, f);
}
};
/**
* repeated MessageEnvelope messages = 1;
* @return {!Array<!proto.MessageEnvelope>}
*/
proto.SyncRequest.prototype.getMessagesList = function () {
return (
/** @type{!Array<!proto.MessageEnvelope>} */
jspb.Message.getRepeatedWrapperField(this, proto.MessageEnvelope, 1)
);
};
/**
* @param {!Array<!proto.MessageEnvelope>} value
* @return {!proto.SyncRequest} returns this
*/
proto.SyncRequest.prototype.setMessagesList = function (value) {
return jspb.Message.setRepeatedWrapperField(this, 1, value);
};
/**
* @param {!proto.MessageEnvelope=} opt_value
* @param {number=} opt_index
* @return {!proto.MessageEnvelope}
*/
proto.SyncRequest.prototype.addMessages = function (opt_value, opt_index) {
return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.MessageEnvelope, opt_index);
};
/**
* Clears the list making it empty but non-null.
* @return {!proto.SyncRequest} returns this
*/
proto.SyncRequest.prototype.clearMessagesList = function () {
return this.setMessagesList([]);
};
/**
* optional string fileId = 2;
* @return {string}
*/
proto.SyncRequest.prototype.getFileid = function () {
return (
/** @type {string} */
jspb.Message.getFieldWithDefault(this, 2, "")
);
};
/**
* @param {string} value
* @return {!proto.SyncRequest} returns this
*/
proto.SyncRequest.prototype.setFileid = function (value) {
return jspb.Message.setProto3StringField(this, 2, value);
};
/**
* optional string groupId = 3;
* @return {string}
*/
proto.SyncRequest.prototype.getGroupid = function () {
return (
/** @type {string} */
jspb.Message.getFieldWithDefault(this, 3, "")
);
};
/**
* @param {string} value
* @return {!proto.SyncRequest} returns this
*/
proto.SyncRequest.prototype.setGroupid = function (value) {
return jspb.Message.setProto3StringField(this, 3, value);
};
/**
* optional string keyId = 5;
* @return {string}
*/
proto.SyncRequest.prototype.getKeyid = function () {
return (
/** @type {string} */
jspb.Message.getFieldWithDefault(this, 5, "")
);
};
/**
* @param {string} value
* @return {!proto.SyncRequest} returns this
*/
proto.SyncRequest.prototype.setKeyid = function (value) {
return jspb.Message.setProto3StringField(this, 5, value);
};
/**
* optional string since = 6;
* @return {string}
*/
proto.SyncRequest.prototype.getSince = function () {
return (
/** @type {string} */
jspb.Message.getFieldWithDefault(this, 6, "")
);
};
/**
* @param {string} value
* @return {!proto.SyncRequest} returns this
*/
proto.SyncRequest.prototype.setSince = function (value) {
return jspb.Message.setProto3StringField(this, 6, value);
};
/**
* List of repeated fields within this message type.
* @private {!Array<number>}
* @const
*/
proto.SyncResponse.repeatedFields_ = [1];
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.SyncResponse.prototype.toObject = function (opt_includeInstance) {
return proto.SyncResponse.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.SyncResponse} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.SyncResponse.toObject = function (includeInstance, msg) {
var f,
obj = {
messagesList: jspb.Message.toObjectList(msg.getMessagesList(), proto.MessageEnvelope.toObject, includeInstance),
merkle: jspb.Message.getFieldWithDefault(msg, 2, "")
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.SyncResponse}
*/
proto.SyncResponse.deserializeBinary = function (bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.SyncResponse();
return proto.SyncResponse.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.SyncResponse} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.SyncResponse}
*/
proto.SyncResponse.deserializeBinaryFromReader = function (msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = new proto.MessageEnvelope();
reader.readMessage(value, proto.MessageEnvelope.deserializeBinaryFromReader);
msg.addMessages(value);
break;
case 2:
var value =
/** @type {string} */
reader.readString();
msg.setMerkle(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.SyncResponse.prototype.serializeBinary = function () {
var writer = new jspb.BinaryWriter();
proto.SyncResponse.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.SyncResponse} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.SyncResponse.serializeBinaryToWriter = function (message, writer) {
var f = undefined;
f = message.getMessagesList();
if (f.length > 0) {
writer.writeRepeatedMessage(1, f, proto.MessageEnvelope.serializeBinaryToWriter);
}
f = message.getMerkle();
if (f.length > 0) {
writer.writeString(2, f);
}
};
/**
* repeated MessageEnvelope messages = 1;
* @return {!Array<!proto.MessageEnvelope>}
*/
proto.SyncResponse.prototype.getMessagesList = function () {
return (
/** @type{!Array<!proto.MessageEnvelope>} */
jspb.Message.getRepeatedWrapperField(this, proto.MessageEnvelope, 1)
);
};
/**
* @param {!Array<!proto.MessageEnvelope>} value
* @return {!proto.SyncResponse} returns this
*/
proto.SyncResponse.prototype.setMessagesList = function (value) {
return jspb.Message.setRepeatedWrapperField(this, 1, value);
};
/**
* @param {!proto.MessageEnvelope=} opt_value
* @param {number=} opt_index
* @return {!proto.MessageEnvelope}
*/
proto.SyncResponse.prototype.addMessages = function (opt_value, opt_index) {
return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.MessageEnvelope, opt_index);
};
/**
* Clears the list making it empty but non-null.
* @return {!proto.SyncResponse} returns this
*/
proto.SyncResponse.prototype.clearMessagesList = function () {
return this.setMessagesList([]);
};
/**
* optional string merkle = 2;
* @return {string}
*/
proto.SyncResponse.prototype.getMerkle = function () {
return (
/** @type {string} */
jspb.Message.getFieldWithDefault(this, 2, "")
);
};
/**
* @param {string} value
* @return {!proto.SyncResponse} returns this
*/
proto.SyncResponse.prototype.setMerkle = function (value) {
return jspb.Message.setProto3StringField(this, 2, value);
};
goog.object.extend(exports, proto);
/***/ }),
/***/ "./packages/loot-core/src/server/sync/repair.js":
/*!******************************************************!*\
!*** ./packages/loot-core/src/server/sync/repair.js ***!
\******************************************************/
/*! exports provided: rebuildMerkleHash, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rebuildMerkleHash", function() { return rebuildMerkleHash; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return repairSync; });
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _timestamp__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../timestamp */ "./packages/loot-core/src/server/timestamp.js");
/* harmony import */ var _merkle__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../merkle */ "./packages/loot-core/src/server/merkle.js");
function rebuildMerkleHash() {
let rows = _db__WEBPACK_IMPORTED_MODULE_0__["runQuery"]('SELECT timestamp FROM messages_crdt', [], true);
let trie = {};
for (let i = 0; i < rows.length; i++) {
trie = _merkle__WEBPACK_IMPORTED_MODULE_2__["insert"](trie, _timestamp__WEBPACK_IMPORTED_MODULE_1__["default"].parse(rows[i].timestamp));
}
return {
numMessages: rows.length,
trie: trie
};
}
async function repairSync() {
let rebuilt = rebuildMerkleHash();
let clock = Object(_timestamp__WEBPACK_IMPORTED_MODULE_1__["getClock"])(); // Save it locally
clock.merkle = rebuilt.trie; // Persist it in the db
_db__WEBPACK_IMPORTED_MODULE_0__["runQuery"](_db__WEBPACK_IMPORTED_MODULE_0__["cache"]('INSERT OR REPLACE INTO messages_clock (id, clock) VALUES (1, ?)'), [Object(_timestamp__WEBPACK_IMPORTED_MODULE_1__["serializeClock"])(clock)]);
}
/***/ }),
/***/ "./packages/loot-core/src/server/sync/reset.js":
/*!*****************************************************!*\
!*** ./packages/loot-core/src/server/sync/reset.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return resetSync; });
/* harmony import */ var _cloud_storage__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../cloud-storage */ "./packages/loot-core/src/server/cloud-storage.js");
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _prefs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../prefs */ "./packages/loot-core/src/server/prefs.js");
/* harmony import */ var _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../platform/server/asyncStorage */ "./packages/loot-core/src/platform/server/asyncStorage/index.electron.js");
/* harmony import */ var _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _platform_exceptions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../platform/exceptions */ "./packages/loot-core/src/platform/exceptions/index.electron.js");
/* harmony import */ var _mutators__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../mutators */ "./packages/loot-core/src/server/mutators.js");
const connection = __webpack_require__(/*! ../../platform/server/connection */ "./packages/loot-core/src/platform/server/connection/index.api.js");
async function resetSync(keyState) {
if (!keyState) {
// If we aren't resetting the key, make sure our key is up-to-date
// so we don't accidentally upload a file encrypted with the wrong
// key (or not encrypted at all)
let _await$cloudStorage$c = await _cloud_storage__WEBPACK_IMPORTED_MODULE_0__["checkKey"](),
valid = _await$cloudStorage$c.valid,
error = _await$cloudStorage$c.error;
if (error) {
return {
error
};
} else if (!valid) {
return {
error: {
reason: 'file-has-new-key'
}
};
}
}
let _await$cloudStorage$r = await _cloud_storage__WEBPACK_IMPORTED_MODULE_0__["resetSyncState"](keyState),
error = _await$cloudStorage$r.error;
if (error) {
return {
error
};
}
await Object(_mutators__WEBPACK_IMPORTED_MODULE_5__["runMutator"])(async () => {
// TOOD: We could automatically generate the list of tables to
// cleanup by looking at the schema
//
// Be VERY careful here since we are bulk deleting data. It should
// never delete any data that doesn't have `tombstone = 1`
await _db__WEBPACK_IMPORTED_MODULE_1__["execQuery"](`
DELETE FROM messages_crdt;
DELETE FROM messages_clock;
DELETE FROM transactions WHERE tombstone = 1;
DELETE FROM accounts WHERE tombstone = 1;
DELETE FROM payees WHERE tombstone = 1;
DELETE FROM categories WHERE tombstone = 1;
DELETE FROM category_groups WHERE tombstone = 1;
DELETE FROM schedules WHERE tombstone = 1;
DELETE FROM rules WHERE tombstone = 1;
ANALYZE;
VACUUM;
`);
await _db__WEBPACK_IMPORTED_MODULE_1__["loadClock"]();
});
await _prefs__WEBPACK_IMPORTED_MODULE_2__["savePrefs"]({
groupId: null,
lastSyncedTimestamp: null,
lastUploaded: null
});
if (keyState) {
let key = keyState.key;
let _prefs$getPrefs = _prefs__WEBPACK_IMPORTED_MODULE_2__["getPrefs"](),
cloudFileId = _prefs$getPrefs.cloudFileId; // The key has changed, we need to update our local data to
// store the new key
// Persist key in async storage
let keys = JSON.parse((await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_3___default.a.getItem(`encrypt-keys`)) || '{}');
keys[cloudFileId] = key.serialize();
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_3___default.a.setItem('encrypt-keys', JSON.stringify(keys)); // Save the key id in prefs
await _prefs__WEBPACK_IMPORTED_MODULE_2__["savePrefs"]({
encryptKeyId: key.getId()
});
} // Finally, upload the file to make it the "true" version that all
// other clients need to pull down to get back in sync
try {
await _cloud_storage__WEBPACK_IMPORTED_MODULE_0__["upload"]();
} catch (e) {
if (e.reason) {
return {
error: e
};
}
Object(_platform_exceptions__WEBPACK_IMPORTED_MODULE_4__["captureException"])(e);
return {
error: {
reason: 'upload-failure'
}
};
} finally {
connection.send('prefs-updated');
}
return {};
}
/***/ }),
/***/ "./packages/loot-core/src/server/timestamp.js":
/*!****************************************************!*\
!*** ./packages/loot-core/src/server/timestamp.js ***!
\****************************************************/
/*! exports provided: setClock, getClock, makeClock, serializeClock, deserializeClock, makeClientId, default, MutableTimestamp */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setClock", function() { return setClock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getClock", function() { return getClock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeClock", function() { return makeClock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "serializeClock", function() { return serializeClock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deserializeClock", function() { return deserializeClock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeClientId", function() { return makeClientId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Timestamp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MutableTimestamp", function() { return MutableTimestamp; });
/* harmony import */ var murmurhash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! murmurhash */ "./node_modules/murmurhash/murmurhash.js");
/* harmony import */ var murmurhash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(murmurhash__WEBPACK_IMPORTED_MODULE_0__);
const uuid = __webpack_require__(/*! ../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js");
/**
* Hybrid Unique Logical Clock (HULC) timestamp generator
*
* Globally-unique, monotonic timestamps are generated from the
* combination of the unreliable system time, a counter, and an
* identifier for the current node (instance, machine, process, etc.).
* These timestamps can accommodate clock stuttering (duplicate values),
* regression, and node differences within the configured maximum drift.
*
* In order to generate timestamps locally or for transmission to another
* node, use the send() method. For global causality, timestamps must
* be included in each message processed by the system. Whenever a
* message is received, its timestamp must be passed to the recv()
* method.
*
* Timestamps serialize into a 46-character collatable string
* example: 2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF
* example: 2015-04-24T22:23:42.123Z-1000-A219E7A71CC18912
*
* The 64-bit hybrid clock is based on the HLC specification,
* http://www.cse.buffalo.edu/tech-reports/2014-04.pdf
*/
// A mutable global clock
let clock = null;
function setClock(clock_) {
clock = clock_;
}
function getClock() {
return clock;
}
function makeClock(timestamp, merkle = {}) {
return {
timestamp: MutableTimestamp.from(timestamp),
merkle
};
}
function serializeClock(clock) {
return JSON.stringify({
timestamp: clock.timestamp.toString(),
merkle: clock.merkle
});
}
function deserializeClock(clock) {
let data;
try {
data = JSON.parse(clock);
} catch (e) {
data = {
timestamp: '1970-01-01T00:00:00.000Z-0000-' + makeClientId(),
merkle: {}
};
}
return {
timestamp: MutableTimestamp.from(Timestamp.parse(data.timestamp)),
merkle: data.merkle
};
}
function makeClientId() {
return uuid.v4Sync().replace(/-/g, '').slice(-16);
}
var config = {
// Allow 5 minutes of clock drift
maxDrift: 5 * 60 * 1000
};
/**
* timestamp instance class
*/
class Timestamp {
constructor(millis, counter, node) {
this._state = {
millis: millis,
counter: counter,
node: node
};
}
valueOf() {
return this.toString();
}
toString() {
return [new Date(this.millis()).toISOString(), ('0000' + this.counter().toString(16).toUpperCase()).slice(-4), ('0000000000000000' + this.node()).slice(-16)].join('-');
}
millis() {
return this._state.millis;
}
counter() {
return this._state.counter;
}
node() {
return this._state.node;
}
hash() {
return murmurhash__WEBPACK_IMPORTED_MODULE_0___default.a.v3(this.toString());
}
}
class MutableTimestamp extends Timestamp {
setMillis(n) {
this._state.millis = n;
}
setCounter(n) {
this._state.counter = n;
}
setNode(n) {
this._state.node = n;
}
}
MutableTimestamp.from = timestamp => {
return new MutableTimestamp(timestamp.millis(), timestamp.counter(), timestamp.node());
}; // Timestamp generator initialization
// * sets the node ID to an arbitrary value
// * useful for mocking/unit testing
Timestamp.init = function (options = {}) {
if (options.maxDrift) {
config.maxDrift = options.maxDrift;
}
setClock(makeClock(new Timestamp(0, 0, options.node ? ('0000000000000000' + options.node).toString().slice(-16) : '')), null);
};
/**
* Timestamp send. Generates a unique, monotonic timestamp suitable
* for transmission to another system in string format
*/
Timestamp.send = function () {
if (!clock) {
return null;
} // retrieve the local wall time
var phys = Date.now(); // unpack the clock.timestamp logical time and counter
var lOld = clock.timestamp.millis();
var cOld = clock.timestamp.counter(); // calculate the next logical time and counter
// * ensure that the logical time never goes backward
// * increment the counter if phys time does not advance
var lNew = Math.max(lOld, phys);
var cNew = lOld === lNew ? cOld + 1 : 0; // check the result for drift and counter overflow
if (lNew - phys > config.maxDrift) {
throw new Timestamp.ClockDriftError(lNew, phys, config.maxDrift);
}
if (cNew > 65535) {
throw new Timestamp.OverflowError();
} // repack the logical time/counter
clock.timestamp.setMillis(lNew);
clock.timestamp.setCounter(cNew);
return new Timestamp(clock.timestamp.millis(), clock.timestamp.counter(), clock.timestamp.node());
}; // Timestamp receive. Parses and merges a timestamp from a remote
// system with the local timeglobal uniqueness and monotonicity are
// preserved
Timestamp.recv = function (msg) {
if (!clock) {
return null;
} // retrieve the local wall time
var phys = Date.now(); // unpack the message wall time/counter
var lMsg = msg.millis();
var cMsg = msg.counter(); // assert the node id and remote clock drift
// if (msg.node() === clock.timestamp.node()) {
// throw new Timestamp.DuplicateNodeError(clock.timestamp.node());
// }
if (lMsg - phys > config.maxDrift) {
throw new Timestamp.ClockDriftError();
} // unpack the clock.timestamp logical time and counter
var lOld = clock.timestamp.millis();
var cOld = clock.timestamp.counter(); // calculate the next logical time and counter
// . ensure that the logical time never goes backward
// . if all logical clocks are equal, increment the max counter
// . if max = old > message, increment local counter
// . if max = messsage > old, increment message counter
// . otherwise, clocks are monotonic, reset counter
var lNew = Math.max(Math.max(lOld, phys), lMsg);
var cNew = lNew === lOld && lNew === lMsg ? Math.max(cOld, cMsg) + 1 : lNew === lOld ? cOld + 1 : lNew === lMsg ? cMsg + 1 : 0; // check the result for drift and counter overflow
if (lNew - phys > config.maxDrift) {
throw new Timestamp.ClockDriftError();
}
if (cNew > 65535) {
throw new Timestamp.OverflowError();
} // repack the logical time/counter
clock.timestamp.setMillis(lNew);
clock.timestamp.setCounter(cNew);
return new Timestamp(clock.timestamp.millis(), clock.timestamp.counter(), clock.timestamp.node());
};
/**
* timestamp parsing
* converts a fixed-length string timestamp to the structured value
*/
Timestamp.parse = function (timestamp) {
if (typeof timestamp === 'string') {
var parts = timestamp.split('-');
if (parts && parts.length === 5) {
var millis = Date.parse(parts.slice(0, 3).join('-')).valueOf();
var counter = parseInt(parts[3], 16);
var node = parts[4];
if (!isNaN(millis) && !isNaN(counter)) return new Timestamp(millis, counter, node);
}
}
return null;
};
/**
* zero/minimum timestamp
*/
var zero = Timestamp.parse('1970-01-01T00:00:00.000Z-0000-0000000000000000');
Timestamp.zero = function () {
return zero;
};
/**
* maximum timestamp
*/
var max = Timestamp.parse('9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF');
Timestamp.max = function () {
return max;
};
Timestamp.since = isoString => {
return isoString + '-0000-0000000000000000';
};
/**
* error classes
*/
Timestamp.DuplicateNodeError = class extends Error {
constructor(node) {
super();
this.type = 'DuplicateNodeError';
this.message = 'duplicate node identifier ' + node;
}
};
Timestamp.ClockDriftError = class extends Error {
constructor(...args) {
super();
this.type = 'ClockDriftError';
this.message = ['maximum clock drift exceeded'].concat(args).join(' ');
}
};
Timestamp.OverflowError = class extends Error {
constructor() {
super();
this.type = 'OverflowError';
this.message = 'timestamp counter overflow';
}
};
/***/ }),
/***/ "./packages/loot-core/src/server/tools/app.js":
/*!****************************************************!*\
!*** ./packages/loot-core/src/server/tools/app.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _sync__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../sync */ "./packages/loot-core/src/server/sync/index.js");
/* harmony import */ var _mutators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../mutators */ "./packages/loot-core/src/server/mutators.js");
/* harmony import */ var _app__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../app */ "./packages/loot-core/src/server/app.js");
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _accounts_transactions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../accounts/transactions */ "./packages/loot-core/src/server/accounts/transactions.js");
let app = Object(_app__WEBPACK_IMPORTED_MODULE_2__["createApp"])();
app.method('tools/fix-split-transactions', async () => {
// 1. Check for child transactions that have a blank payee, and set
// the payee to whatever the parent has
let blankPayeeRows = await _db__WEBPACK_IMPORTED_MODULE_3__["all"](`
SELECT t.*, p.payee AS parentPayee FROM v_transactions_internal t
LEFT JOIN v_transactions_internal p ON t.parent_id = p.id
WHERE t.is_child = 1 AND t.payee IS NULL AND p.payee IS NOT NULL
`);
await Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["runMutator"])(async () => {
let updated = blankPayeeRows.map(row => ({
id: row.id,
payee: row.parentPayee
}));
await Object(_accounts_transactions__WEBPACK_IMPORTED_MODULE_4__["batchUpdateTransactions"])({
updated
});
}); // 2. Make sure the "cleared" flag is synced up with the parent
// transactions
let clearedRows = await _db__WEBPACK_IMPORTED_MODULE_3__["all"](`
SELECT t.id, p.cleared FROM v_transactions_internal t
LEFT JOIN v_transactions_internal p ON t.parent_id = p.id
WHERE t.is_child = 1 AND t.cleared != p.cleared
`);
await Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["runMutator"])(async () => {
let updated = clearedRows.map(row => ({
id: row.id,
cleared: row.cleared === 1
}));
await Object(_accounts_transactions__WEBPACK_IMPORTED_MODULE_4__["batchUpdateTransactions"])({
updated
});
}); // 3. Mark the `tombstone` field as true on any child transactions
// that have a dead parent
let deletedRows = await _db__WEBPACK_IMPORTED_MODULE_3__["all"](`
SELECT t.* FROM v_transactions_internal t
LEFT JOIN v_transactions_internal p ON t.parent_id = p.id
WHERE t.is_child = 1 AND t.tombstone = 0 AND (p.tombstone = 1 OR p.id IS NULL)
`);
await Object(_mutators__WEBPACK_IMPORTED_MODULE_1__["runMutator"])(async () => {
let updated = deletedRows.map(row => ({
id: row.id,
tombstone: 1
}));
await Object(_accounts_transactions__WEBPACK_IMPORTED_MODULE_4__["batchUpdateTransactions"])({
updated
});
});
return {
numBlankPayees: blankPayeeRows.length,
numCleared: clearedRows.length,
numDeleted: deletedRows.length
};
});
/* harmony default export */ __webpack_exports__["default"] = (app);
/***/ }),
/***/ "./packages/loot-core/src/server/tracking/events.js":
/*!**********************************************************!*\
!*** ./packages/loot-core/src/server/tracking/events.js ***!
\**********************************************************/
/*! exports provided: toggle, init, login, track, setProfile */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toggle", function() { return toggle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "init", function() { return init; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "login", function() { return login; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "track", function() { return track; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setProfile", function() { return setProfile; });
/* harmony import */ var _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../platform/server/asyncStorage */ "./packages/loot-core/src/platform/server/asyncStorage/index.electron.js");
/* harmony import */ var _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _encryption_internals__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../encryption-internals */ "./packages/loot-core/src/server/encryption-internals.js");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
let Mixpanel = __webpack_require__(/*! @jlongster/mixpanel */ "./node_modules/@jlongster/mixpanel/lib/mixpanel-node.js");
let uuid = __webpack_require__(/*! ../../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js");
let currentUniqueId;
let mixpanel;
let isEnabled = true;
function toggle(trackUsage) {
isEnabled = trackUsage == null || trackUsage === 'true' ? true : false;
} // TODO: Figure out location, send to EU data centers if in EU
// {
// host: "api-eu.mixpanel.com",
// },
// This must stay up-to-date with all apps that hit mixpanel! That includes the
// website and server. If changing this, make sure to change it everywhere
async function hash(userId) {
let hashed = await Object(_encryption_internals__WEBPACK_IMPORTED_MODULE_1__["sha256String"])(userId);
return `user-${hashed.replace(/[=/]/g, '')}`;
}
function isAnonymous(id) {
return !id.startsWith('user-');
}
async function init() {
mixpanel = Mixpanel.init('7e6461b8dde1d5dbf04ed1711768257a');
let _await$asyncStorage$m = await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_0___default.a.multiGet(['distinct-id-v2', 'user-id', 'track-usage']),
_await$asyncStorage$m2 = _slicedToArray(_await$asyncStorage$m, 3),
_await$asyncStorage$m3 = _slicedToArray(_await$asyncStorage$m2[0], 2),
distinctId = _await$asyncStorage$m3[1],
_await$asyncStorage$m4 = _slicedToArray(_await$asyncStorage$m2[1], 2),
userId = _await$asyncStorage$m4[1],
_await$asyncStorage$m5 = _slicedToArray(_await$asyncStorage$m2[2], 2),
trackUsage = _await$asyncStorage$m5[1];
toggle(trackUsage);
if (distinctId == null) {
if (userId) {
let hashedId = await hash(userId);
currentUniqueId = hashedId;
setProfile({
$name: hashedId
});
} else {
currentUniqueId = uuid.v4Sync();
}
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_0___default.a.setItem('distinct-id-v2', currentUniqueId);
} else {
currentUniqueId = distinctId;
if (!isAnonymous(distinctId)) {
setProfile({
$name: distinctId
});
}
}
}
async function login(userId) {
let hashedId = await hash(userId);
await _platform_server_asyncStorage__WEBPACK_IMPORTED_MODULE_0___default.a.setItem('distinct-id-v2', hashedId);
if (isAnonymous(currentUniqueId)) {
mixpanel.identify(hashedId, currentUniqueId);
startBuffering(); // So ridiculous. https://help.mixpanel.com/hc/en-us/articles/115004497803-Identity-Management-Best-Practices#serverside-aliasing
setTimeout(() => {
stopBuffering();
}, 2000);
currentUniqueId = hashedId;
setProfile({
$name: hashedId
});
} else {
currentUniqueId = hashedId;
}
}
let BUFFERING = false;
let BUFFER = [];
function startBuffering() {
BUFFERING = true;
BUFFER = [];
}
function stopBuffering() {
for (let call of BUFFER) {
call[0](...call[1]);
}
BUFFERING = false;
BUFFER = [];
}
function buffered(func) {
return (...args) => {
if (false) {}
};
}
const track = buffered((distinct_id, name, props) => {});
const setProfile = buffered((distinct_id, props) => {});
/***/ }),
/***/ "./packages/loot-core/src/server/undo.js":
/*!***********************************************!*\
!*** ./packages/loot-core/src/server/undo.js ***!
\***********************************************/
/*! exports provided: appendMessages, clearUndo, withUndo, undoable, undo, redo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendMessages", function() { return appendMessages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearUndo", function() { return clearUndo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withUndo", function() { return withUndo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "undoable", function() { return undoable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "undo", function() { return undo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "redo", function() { return redo; });
/* harmony import */ var _sync__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sync */ "./packages/loot-core/src/server/sync/index.js");
/* harmony import */ var _shared_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../shared/util */ "./packages/loot-core/src/shared/util.js");
/* harmony import */ var _timestamp__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./timestamp */ "./packages/loot-core/src/server/timestamp.js");
/* harmony import */ var _mutators__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mutators */ "./packages/loot-core/src/server/mutators.js");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const connection = __webpack_require__(/*! ../platform/server/connection */ "./packages/loot-core/src/platform/server/connection/index.api.js"); // A marker always sits as the first entry to simplify logic
let MESSAGE_HISTORY = [{
type: 'marker'
}];
let CURSOR = 0;
let HISTORY_SIZE = 20;
function trimHistory() {
MESSAGE_HISTORY = MESSAGE_HISTORY.slice(0, CURSOR + 1);
let markers = MESSAGE_HISTORY.filter(item => item.type === 'marker');
if (markers.length > HISTORY_SIZE) {
let slice = markers.slice(-HISTORY_SIZE);
let cutoff = MESSAGE_HISTORY.indexOf(slice[0]);
MESSAGE_HISTORY = MESSAGE_HISTORY.slice(cutoff);
CURSOR = MESSAGE_HISTORY.length - 1;
}
}
function appendMessages(messages, oldData) {
let context = Object(_mutators__WEBPACK_IMPORTED_MODULE_3__["getMutatorContext"])();
if (context.undoListening && messages.length > 0) {
trimHistory();
let undoTag = context.undoTag;
MESSAGE_HISTORY.push({
type: 'messages',
messages,
oldData,
undoTag
});
CURSOR++;
}
}
function clearUndo() {
MESSAGE_HISTORY = [{
type: 'marker'
}];
CURSOR = 0;
}
function withUndo(func, meta) {
let context = Object(_mutators__WEBPACK_IMPORTED_MODULE_3__["getMutatorContext"])();
if (context.undoDisabled || context.undoListening) {
return func();
}
MESSAGE_HISTORY = MESSAGE_HISTORY.slice(0, CURSOR + 1);
let marker = {
type: 'marker',
meta
};
if (MESSAGE_HISTORY[MESSAGE_HISTORY.length - 1].type === 'marker') {
MESSAGE_HISTORY[MESSAGE_HISTORY.length - 1] = marker;
} else {
MESSAGE_HISTORY.push(marker);
CURSOR++;
}
return Object(_mutators__WEBPACK_IMPORTED_MODULE_3__["withMutatorContext"])({
undoListening: true,
undoTag: context.undoTag
}, func);
}
function undoable(func) {
return (...args) => {
return withUndo(() => {
return func(...args);
});
};
}
async function applyUndoAction(messages, meta, undoTag) {
await Object(_mutators__WEBPACK_IMPORTED_MODULE_3__["withMutatorContext"])({
undoListening: false
}, () => {
return Object(_sync__WEBPACK_IMPORTED_MODULE_0__["sendMessages"])(messages.map(msg => _objectSpread(_objectSpread({}, msg), {}, {
timestamp: _timestamp__WEBPACK_IMPORTED_MODULE_2__["default"].send()
})));
});
const tables = messages.reduce((acc, message) => {
if (!acc.includes(message.dataset)) {
acc.push(message.dataset);
}
return acc;
}, []);
connection.send('undo-event', {
messages,
tables,
meta,
undoTag
});
}
async function undo() {
let end = CURSOR;
CURSOR = Math.max(CURSOR - 1, 0); // Walk back to the nearest marker
while (CURSOR > 0 && MESSAGE_HISTORY[CURSOR].type !== 'marker') {
CURSOR--;
}
let meta = MESSAGE_HISTORY[CURSOR].meta;
let start = Math.max(CURSOR, 0);
let entries = MESSAGE_HISTORY.slice(start, end + 1).filter(entry => entry.type === 'messages');
if (entries.length > 0) {
let toApply = entries.reduce((acc, entry) => {
return acc.concat(entry.messages.map(message => undoMessage(message, entry.oldData)).filter(x => x));
}, []).reverse();
await applyUndoAction(toApply, meta, entries[0].undoTag);
}
}
function undoMessage(message, oldData) {
let oldItem = Object(_shared_util__WEBPACK_IMPORTED_MODULE_1__["getIn"])(oldData, [message.dataset, message.row]);
if (oldItem) {
let column = message.column;
if (message.dataset === 'spreadsheet_cells') {
// The spreadsheet messages use the `expr` column, but only as a
// placeholder. We actually want to read the `cachedValue` prop
// from the old item.
column = 'cachedValue';
}
return _objectSpread(_objectSpread({}, message), {}, {
value: oldItem[column]
});
} else {
if (message.dataset === 'spreadsheet_cells') {
if (message.column === 'expr') {
return _objectSpread(_objectSpread({}, message), {}, {
value: null
});
}
return message;
} else if ( // The mapping fields aren't ever deleted... this should be
// harmless since all they are is meta information. Maybe we
// should fix this though.
message.dataset !== 'category_mapping' && message.dataset !== 'payee_mapping') {
if (message.dataset === 'zero_budget_months' || message.dataset === 'zero_budgets' || message.dataset === 'reflect_budgets') {
// Only these fields are reversable
if (['buffered', 'amount', 'carryover'].includes(message.column)) {
return _objectSpread(_objectSpread({}, message), {}, {
value: 0
});
}
return null;
} else if (message.dataset === 'notes') {
return _objectSpread(_objectSpread({}, message), {}, {
value: null
});
}
return _objectSpread(_objectSpread({}, message), {}, {
column: 'tombstone',
value: 1
});
}
}
return null;
}
async function redo() {
let meta = MESSAGE_HISTORY[CURSOR].type === 'marker' ? MESSAGE_HISTORY[CURSOR].meta : null;
let start = CURSOR;
CURSOR = Math.min(CURSOR + 1, MESSAGE_HISTORY.length - 1); // Walk forward to the nearest marker
while (CURSOR < MESSAGE_HISTORY.length - 1 && MESSAGE_HISTORY[CURSOR].type !== 'marker') {
CURSOR++;
}
let end = CURSOR;
let entries = MESSAGE_HISTORY.slice(start + 1, end + 1).filter(entry => entry.type === 'messages');
if (entries.length > 0) {
let toApply = entries.reduce((acc, entry) => {
return acc.concat(entry.messages).concat(redoResurrections(entry.messages, entry.oldData));
}, []);
await applyUndoAction(toApply, meta, entries[entries.length - 1].undoTag);
}
}
function redoResurrections(messages, oldData) {
let resurrect = new Set();
messages.forEach(message => {
// If any of the ids didn't exist before, we need to "resurrect"
// them by resetting their tombstones to 0
let oldItem = Object(_shared_util__WEBPACK_IMPORTED_MODULE_1__["getIn"])(oldData, [message.dataset, message.row]);
if (!oldItem && !['zero_budget_months', 'zero_budgets', 'reflect_budgets', 'notes', 'category_mapping', 'payee_mapping'].includes(message.dataset)) {
resurrect.add(message.dataset + '.' + message.row);
}
});
return [...resurrect].map(desc => {
let _desc$split = desc.split('.'),
_desc$split2 = _slicedToArray(_desc$split, 2),
table = _desc$split2[0],
row = _desc$split2[1];
return {
dataset: table,
row,
column: 'tombstone',
value: 0,
timestamp: _timestamp__WEBPACK_IMPORTED_MODULE_2__["default"].send()
};
});
}
/***/ }),
/***/ "./packages/loot-core/src/server/update.js":
/*!*************************************************!*\
!*** ./packages/loot-core/src/server/update.js ***!
\*************************************************/
/*! exports provided: updateViews, updateVersion */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateViews", function() { return updateViews; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateVersion", function() { return updateVersion; });
/* harmony import */ var md5__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! md5 */ "./node_modules/md5/md5.js");
/* harmony import */ var md5__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(md5__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _migrate_migrations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./migrate/migrations */ "./packages/loot-core/src/server/migrate/migrations.js");
/* harmony import */ var _db__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./db */ "./packages/loot-core/src/server/db/index.js");
/* harmony import */ var _aql_schema__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./aql/schema */ "./packages/loot-core/src/server/aql/schema/index.js");
/* harmony import */ var _aql_views__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./aql/views */ "./packages/loot-core/src/server/aql/views.js");
// Managing the init/update process
async function runMigrations() {
await _migrate_migrations__WEBPACK_IMPORTED_MODULE_1__["migrate"](_db__WEBPACK_IMPORTED_MODULE_2__["getDatabase"]());
}
async function updateViews() {
let hashKey = 'view-hash';
let row = await _db__WEBPACK_IMPORTED_MODULE_2__["first"]('SELECT value FROM __meta__ WHERE key = ?', [hashKey]);
let _ref = row || {},
hash = _ref.value;
let views = Object(_aql_views__WEBPACK_IMPORTED_MODULE_4__["makeViews"])(_aql_schema__WEBPACK_IMPORTED_MODULE_3__["schema"], _aql_schema__WEBPACK_IMPORTED_MODULE_3__["schemaConfig"]);
let currentHash = md5__WEBPACK_IMPORTED_MODULE_0___default()(views);
if (hash !== currentHash) {
await _db__WEBPACK_IMPORTED_MODULE_2__["execQuery"](views);
await _db__WEBPACK_IMPORTED_MODULE_2__["runQuery"]('INSERT OR REPLACE INTO __meta__ (key, value) VALUES (?, ?)', [hashKey, currentHash]);
}
}
async function updateVersion() {
await runMigrations();
await updateViews();
}
/***/ }),
/***/ "./packages/loot-core/src/server/util/budget-name.js":
/*!***********************************************************!*\
!*** ./packages/loot-core/src/server/util/budget-name.js ***!
\***********************************************************/
/*! exports provided: uniqueFileName, idFromFileName */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "uniqueFileName", function() { return uniqueFileName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "idFromFileName", function() { return idFromFileName; });
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../platform/server/fs */ "./packages/loot-core/src/platform/server/fs/index.electron.js");
/* harmony import */ var _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_platform_server_fs__WEBPACK_IMPORTED_MODULE_0__);
const uuid = __webpack_require__(/*! ../../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js");
async function uniqueFileName(existingFiles) {
let initialName = 'My Finances';
let idx = 1; // If there is a conflict, keep appending an index until there is no
// conflict and we have a unique name
let newName = initialName;
while (existingFiles.find(file => file.name === newName)) {
newName = `${initialName} ${idx}`;
idx++;
}
return newName;
}
async function idFromFileName(name) {
let id = name.replace(/( |[^A-Za-z0-9])/g, '-') + '-' + uuid.v4Sync().slice(0, 7); // Make sure the id is unique. There's a chance one could already
// exist (although very unlikely now that we append unique
// characters onto the id)
let index = 0;
let budgetDir = _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.getBudgetDir(id);
while (await _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.exists(budgetDir)) {
index++;
budgetDir = _platform_server_fs__WEBPACK_IMPORTED_MODULE_0___default.a.getBudgetDir(id + index.toString());
} // If a suffix was added, update the id
if (index > 0) {
id = id + index.toString();
}
return id;
}
/***/ }),
/***/ "./packages/loot-core/src/server/util/rschedule.js":
/*!*********************************************************!*\
!*** ./packages/loot-core/src/server/util/rschedule.js ***!
\*********************************************************/
/*! exports provided: StandardDateAdapter, ArgumentError, DateAdapter, DateAdapterBase, DateTime, InfiniteLoopError, InvalidDateAdapterError, InvalidDateTime, InvalidDateTimeError, RecurrenceRuleError, RecurrenceRulesIterator, RuleOptionError, ValidDateTime, cloneJSON, cloneRuleOptions, dateInputToDateAdapter, dateInputToDateTime, dateTimeSortComparer, freqToGranularity, getDaysInYear, getDifferenceBetweenWeekdays, isLeapYear, normalizeDateTimeTimezone, normalizeRuleOptions, numberSortComparer, orderedWeekdays, recurrenceRulesReducer, uniqDateTimes, AddOperator, Calendar, Collection, CollectionIterator, Dates, IntersectionOperator, MergeDurationOperator, MergeDurationOperatorError, OccurrenceGenerator, OccurrenceIterator, Operator, Rule, RuleBase, Schedule, ScheduleBase, SplitDurationOperator, SplitDurationOperatorError, SubtractOperator, UniqueOperator, add, intersection, mergeDuration, splitDuration, subtract, unique */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _rschedule_standard_date_adapter_setup__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @rschedule/standard-date-adapter/setup */ "./node_modules/@rschedule/standard-date-adapter/es2015/setup.js");
/* harmony import */ var _rschedule_json_tools_Schedule__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @rschedule/json-tools/Schedule */ "./node_modules/@rschedule/json-tools/es2015/Schedule.js");
/* harmony import */ var _rschedule_standard_date_adapter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @rschedule/standard-date-adapter */ "./node_modules/@rschedule/standard-date-adapter/es2015/main.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardDateAdapter", function() { return _rschedule_standard_date_adapter__WEBPACK_IMPORTED_MODULE_2__["StandardDateAdapter"]; });
/* harmony import */ var _rschedule_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @rschedule/core */ "./node_modules/@rschedule/core/es2015/main.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArgumentError", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["ArgumentError"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DateAdapter", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["DateAdapter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DateAdapterBase", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["DateAdapterBase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DateTime", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["DateTime"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfiniteLoopError", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["InfiniteLoopError"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InvalidDateAdapterError", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["InvalidDateAdapterError"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InvalidDateTime", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["InvalidDateTime"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InvalidDateTimeError", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["InvalidDateTimeError"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RecurrenceRuleError", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["RecurrenceRuleError"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RecurrenceRulesIterator", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["RecurrenceRulesIterator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RuleOptionError", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["RuleOptionError"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ValidDateTime", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["ValidDateTime"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "cloneJSON", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["cloneJSON"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "cloneRuleOptions", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["cloneRuleOptions"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dateInputToDateAdapter", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["dateInputToDateAdapter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dateInputToDateTime", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["dateInputToDateTime"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dateTimeSortComparer", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["dateTimeSortComparer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "freqToGranularity", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["freqToGranularity"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDaysInYear", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["getDaysInYear"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDifferenceBetweenWeekdays", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["getDifferenceBetweenWeekdays"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isLeapYear", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["isLeapYear"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "normalizeDateTimeTimezone", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["normalizeDateTimeTimezone"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "normalizeRuleOptions", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["normalizeRuleOptions"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "numberSortComparer", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["numberSortComparer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "orderedWeekdays", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["orderedWeekdays"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "recurrenceRulesReducer", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["recurrenceRulesReducer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "uniqDateTimes", function() { return _rschedule_core__WEBPACK_IMPORTED_MODULE_3__["uniqDateTimes"]; });
/* harmony import */ var _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @rschedule/core/generators */ "./node_modules/@rschedule/core/es2015/generators.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AddOperator", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["AddOperator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Calendar", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["Calendar"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Collection", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["Collection"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CollectionIterator", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["CollectionIterator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Dates", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["Dates"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IntersectionOperator", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["IntersectionOperator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MergeDurationOperator", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["MergeDurationOperator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MergeDurationOperatorError", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["MergeDurationOperatorError"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OccurrenceGenerator", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["OccurrenceGenerator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OccurrenceIterator", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["OccurrenceIterator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Operator", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["Operator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Rule", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["Rule"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RuleBase", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["RuleBase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Schedule", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["Schedule"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScheduleBase", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["ScheduleBase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SplitDurationOperator", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["SplitDurationOperator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SplitDurationOperatorError", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["SplitDurationOperatorError"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubtractOperator", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["SubtractOperator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UniqueOperator", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["UniqueOperator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "add", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["add"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "intersection", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["intersection"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mergeDuration", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["mergeDuration"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "splitDuration", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["splitDuration"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subtract", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["subtract"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "unique", function() { return _rschedule_core_generators__WEBPACK_IMPORTED_MODULE_4__["unique"]; });
/***/ }),
/***/ "./packages/loot-core/src/shared/accounts.js":
/*!***************************************************!*\
!*** ./packages/loot-core/src/shared/accounts.js ***!
\***************************************************/
/*! exports provided: fromPlaidAccountType, prettyAccountType, determineOffBudget */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromPlaidAccountType", function() { return fromPlaidAccountType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prettyAccountType", function() { return prettyAccountType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineOffBudget", function() { return determineOffBudget; });
function fromPlaidAccountType(type, subtype) {
switch (type) {
case 'brokerage':
case 'investment':
return 'investment';
case 'credit':
return 'credit';
case 'loan':
return 'debt';
case 'other':
return 'other';
case 'depository':
default:
switch (subtype) {
case 'money market':
case 'savings':
return 'savings';
case 'cd':
return 'cd';
default:
return 'checking';
}
}
}
function prettyAccountType(type) {
switch (type) {
case 'checking':
return 'Checking';
case 'savings':
return 'Savings';
case 'cd':
return 'CD';
case 'investment':
return 'Investment';
case 'credit':
return 'Credit Card';
case 'mortgage':
return 'Mortgage';
case 'debt':
return 'Debt';
case 'other':
default:
return 'Other';
}
}
function determineOffBudget(type) {
switch (type) {
case 'investment':
case 'mortgage':
case 'debt':
case 'other':
return true;
default:
}
return false;
}
/***/ }),
/***/ "./packages/loot-core/src/shared/async.js":
/*!************************************************!*\
!*** ./packages/loot-core/src/shared/async.js ***!
\************************************************/
/*! exports provided: sequential, once */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sequential", function() { return sequential; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "once", function() { return once; });
function sequential(fn) {
let sequenceState = {
running: null,
queue: []
};
function pump() {
if (sequenceState.queue.length > 0) {
const next = sequenceState.queue.shift();
run(next.args, next.resolve, next.reject);
} else {
sequenceState.running = null;
}
}
function run(args, resolve, reject) {
sequenceState.running = fn(...args);
sequenceState.running.then(val => {
pump();
resolve(val);
}, err => {
pump();
reject(err);
});
}
return (...args) => {
if (!sequenceState.running) {
return new Promise((resolve, reject) => {
return run(args, resolve, reject);
});
} else {
return new Promise((resolve, reject) => {
sequenceState.queue.push({
resolve,
reject,
args
});
});
}
};
}
function once(fn) {
let promise = null;
let onceFn = (...args) => {
if (!promise) {
promise = fn(...args).finally(() => {
promise = null;
});
return promise;
}
return promise;
};
return onceFn;
}
/***/ }),
/***/ "./packages/loot-core/src/shared/months.js":
/*!*************************************************!*\
!*** ./packages/loot-core/src/shared/months.js ***!
\*************************************************/
/*! exports provided: parseDate, yearFromDate, monthFromDate, dayFromDate, currentMonth, currentDay, nextMonth, prevMonth, addMonths, subMonths, addDays, subDays, isBefore, isAfter, bounds, _range, range, rangeInclusive, _dayRange, dayRange, dayRangeInclusive, getMonthIndex, getYear, getMonth, getYearStart, getYearEnd, sheetForMonth, nameForMonth, format, getDateFormatRegex, getDayMonthFormat, getDayMonthRegex, getMonthYearFormat, getMonthYearRegex, getShortYearFormat, getShortYearRegex */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseDate", function() { return parseDate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yearFromDate", function() { return yearFromDate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "monthFromDate", function() { return monthFromDate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dayFromDate", function() { return dayFromDate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "currentMonth", function() { return currentMonth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "currentDay", function() { return currentDay; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "nextMonth", function() { return nextMonth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prevMonth", function() { return prevMonth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addMonths", function() { return addMonths; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subMonths", function() { return subMonths; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addDays", function() { return addDays; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subDays", function() { return subDays; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBefore", function() { return isBefore; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isAfter", function() { return isAfter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bounds", function() { return bounds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_range", function() { return _range; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "range", function() { return range; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rangeInclusive", function() { return rangeInclusive; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_dayRange", function() { return _dayRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dayRange", function() { return dayRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dayRangeInclusive", function() { return dayRangeInclusive; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMonthIndex", function() { return getMonthIndex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getYear", function() { return getYear; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMonth", function() { return getMonth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getYearStart", function() { return getYearStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getYearEnd", function() { return getYearEnd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sheetForMonth", function() { return sheetForMonth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "nameForMonth", function() { return nameForMonth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDateFormatRegex", function() { return getDateFormatRegex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDayMonthFormat", function() { return getDayMonthFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDayMonthRegex", function() { return getDayMonthRegex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMonthYearFormat", function() { return getMonthYearFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMonthYearRegex", function() { return getMonthYearRegex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getShortYearFormat", function() { return getShortYearFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getShortYearRegex", function() { return getShortYearRegex; });
/* harmony import */ var date_fns__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! date-fns */ "./node_modules/date-fns/esm/index.js");
/* harmony import */ var memoize_one__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! memoize-one */ "./node_modules/memoize-one/dist/memoize-one.esm.js");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _parse(value) {
if (typeof value === 'string') {
// Dates are hard. We just want to deal with months in the format
// 2020-01 and days in the format 2020-01-01, but life is never
// simple. We want to rely on native dates for date logic because
// days are complicated (leap years, etc). But relying on native
// dates mean we're exposed to craziness.
//
// The biggest problem is that JS dates work with local time by
// default. We could try to only work with UTC, but there's not an
// easy way to make `format` avoid local time, and not sure if we
// want that anyway (`currentMonth` should surely print the local
// time). We need to embrace local time, and as long as inputs to
// date logic and outputs from format are local time, it should
// work.
//
// To make sure we're in local time, always give Date integer
// values. If you pass in a string to parse, different string
// formats produce different results.
//
// A big problem is daylight savings, however. Usually, when
// giving the time to the Date constructor, you get back a date
// specifically for that time in your local timezone. However, if
// daylight savings occurs on that exact time, you will get back
// something different:
//
// This is fine:
// > new Date(2017, 2, 12, 1).toString()
// > 'Sun Mar 12 2017 01:00:00 GMT-0500 (Eastern Standard Time)'
//
// But wait, we got back a different time (3AM instead of 2AM):
// > new Date(2017, 2, 12, 2).toString()
// > 'Sun Mar 12 2017 03:00:00 GMT-0400 (Eastern Daylight Time)'
//
// The time is "correctly" adjusted via DST, but we _really_
// wanted 2AM. The problem is that time simply doesn't exist.
//
// Why is this a problem? Well, consider a case where the DST
// shift happens *at midnight* and it goes back an hour. You think
// you have a date object for the next day, but when formatted it
// actually shows the previous day. A more likely scenario: buggy
// timezone data makes JS dates do this shift when it shouldn't,
// so using midnight at the time for date logic gives back the
// last day. See the time range of Sep 30 15:00 - Oct 1 1:00 for
// the AEST timezone when nodejs-mobile incorrectly gives you back
// a time an hour *before* you specified. Since this happens on
// Oct 1, doing `addMonths(September, 1)` still gives you back
// September. Issue here:
// https://github.com/JaneaSystems/nodejs-mobile/issues/251
//
// The fix is simple once you understand this. Always use the 12th
// hour of the day. That's it. There is no DST that shifts more
// than 12 hours (god let's hope not) so no matter how far DST has
// shifted backwards or forwards, doing date logic will stay
// within the day we want.
let _value$split = value.split('-'),
_value$split2 = _slicedToArray(_value$split, 3),
year = _value$split2[0],
month = _value$split2[1],
day = _value$split2[2];
if (day != null) {
return new Date(parseInt(year), parseInt(month) - 1, parseInt(day), 12);
} else if (month != null) {
return new Date(parseInt(year), parseInt(month) - 1, 1, 12);
} else {
return new Date(parseInt(year), 0, 1, 12);
}
}
return value;
}
const parseDate = _parse;
function yearFromDate(date) {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](_parse(date), 'yyyy');
}
function monthFromDate(date) {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](_parse(date), 'yyyy-MM');
}
function dayFromDate(date) {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](_parse(date), 'yyyy-MM-dd');
}
function currentMonth() {
if (global.IS_TESTING) {
return '2017-01';
} else {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](new Date(), 'yyyy-MM');
}
}
function currentDay() {
if (global.IS_TESTING) {
return '2017-01-01';
} else {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](new Date(), 'yyyy-MM-dd');
}
}
function nextMonth(month) {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](date_fns__WEBPACK_IMPORTED_MODULE_0__["addMonths"](_parse(month), 1), 'yyyy-MM');
}
function prevMonth(month) {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](date_fns__WEBPACK_IMPORTED_MODULE_0__["subMonths"](_parse(month), 1), 'yyyy-MM');
}
function addMonths(month, n) {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](date_fns__WEBPACK_IMPORTED_MODULE_0__["addMonths"](_parse(month), n), 'yyyy-MM');
}
function subMonths(month, n) {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](date_fns__WEBPACK_IMPORTED_MODULE_0__["subMonths"](_parse(month), n), 'yyyy-MM');
}
function addDays(day, n) {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](date_fns__WEBPACK_IMPORTED_MODULE_0__["addDays"](_parse(day), n), 'yyyy-MM-dd');
}
function subDays(day, n) {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](date_fns__WEBPACK_IMPORTED_MODULE_0__["subDays"](_parse(day), n), 'yyyy-MM-dd');
}
function isBefore(month1, month2) {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["isBefore"](_parse(month1), _parse(month2));
}
function isAfter(month1, month2) {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["isAfter"](_parse(month1), _parse(month2));
} // TODO: This doesn't really fit in this module anymore, should
// probably live elsewhere
function bounds(month) {
return {
start: parseInt(date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](date_fns__WEBPACK_IMPORTED_MODULE_0__["startOfMonth"](_parse(month)), 'yyyyMMdd')),
end: parseInt(date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](date_fns__WEBPACK_IMPORTED_MODULE_0__["endOfMonth"](_parse(month)), 'yyyyMMdd'))
};
}
function _range(start, end, inclusive) {
const months = [];
let month = monthFromDate(start);
while (date_fns__WEBPACK_IMPORTED_MODULE_0__["isBefore"](_parse(month), _parse(end))) {
months.push(month);
month = addMonths(month, 1);
}
if (inclusive) {
months.push(month);
}
return months;
}
function range(start, end) {
return _range(start, end);
}
function rangeInclusive(start, end) {
return _range(start, end, true);
}
function _dayRange(start, end, inclusive) {
const days = [];
let day = start;
while (date_fns__WEBPACK_IMPORTED_MODULE_0__["isBefore"](_parse(day), _parse(end))) {
days.push(day);
day = addDays(day, 1);
}
if (inclusive) {
days.push(day);
}
return days;
}
function dayRange(start, end) {
return _dayRange(start, end);
}
function dayRangeInclusive(start, end) {
return _dayRange(start, end, true);
}
function getMonthIndex(month) {
return parseInt(month.slice(5, 7)) - 1;
}
function getYear(month) {
return month.slice(0, 4);
}
function getMonth(day) {
return day.slice(0, 7);
}
function getYearStart(month) {
return getYear(month) + '-01';
}
function getYearEnd(month) {
return getYear(month) + '-12';
}
function sheetForMonth(month) {
return 'budget' + month.replace('-', '');
}
function nameForMonth(month) {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](_parse(month), "MMMM 'yy");
}
function format(month, str) {
return date_fns__WEBPACK_IMPORTED_MODULE_0__["format"](_parse(month), str);
}
const getDateFormatRegex = Object(memoize_one__WEBPACK_IMPORTED_MODULE_1__["default"])(format => {
return new RegExp(format.replace(/d+/g, '\\d{1,2}').replace(/M+/g, '\\d{1,2}').replace(/y+/g, '\\d{4}'));
});
const getDayMonthFormat = Object(memoize_one__WEBPACK_IMPORTED_MODULE_1__["default"])(format => {
return format.replace(/y+/g, '').replace(/[^\w]$/, '').replace(/^[^\w]/, '');
});
const getDayMonthRegex = Object(memoize_one__WEBPACK_IMPORTED_MODULE_1__["default"])(format => {
let regex = format.replace(/y+/g, '').replace(/[^\w]$/, '').replace(/^[^\w]/, '').replace(/d+/g, '\\d{1,2}').replace(/M+/g, '\\d{1,2}');
return new RegExp('^' + regex + '$');
});
const getMonthYearFormat = Object(memoize_one__WEBPACK_IMPORTED_MODULE_1__["default"])(format => {
return format.replace(/d+/g, '').replace(/[^\w]$/, '').replace(/^[^\w]/, '').replace(/\/\//, '/').replace(/\.\./, '.').replace(/--/, '-');
});
const getMonthYearRegex = Object(memoize_one__WEBPACK_IMPORTED_MODULE_1__["default"])(format => {
let regex = format.replace(/d+/g, '').replace(/[^\w]$/, '').replace(/^[^\w]/, '').replace(/\/\//, '/').replace(/M+/g, '\\d{1,2}').replace(/y+/g, '\\d{2,4}');
return new RegExp('^' + regex + '$');
});
const getShortYearFormat = Object(memoize_one__WEBPACK_IMPORTED_MODULE_1__["default"])(format => {
return format.replace(/y+/g, 'yy');
});
const getShortYearRegex = Object(memoize_one__WEBPACK_IMPORTED_MODULE_1__["default"])(format => {
let regex = format.replace(/[^\w]$/, '').replace(/^[^\w]/, '').replace(/d+/g, '\\d{1,2}').replace(/M+/g, '\\d{1,2}').replace(/y+/g, '\\d{2}');
return new RegExp('^' + regex + '$');
});
/***/ }),
/***/ "./packages/loot-core/src/shared/query.js":
/*!************************************************!*\
!*** ./packages/loot-core/src/shared/query.js ***!
\************************************************/
/*! exports provided: Query, getPrimaryOrderBy, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Query", function() { return Query; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPrimaryOrderBy", function() { return getPrimaryOrderBy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return q; });
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
class Query {
constructor(state) {
this.state = _objectSpread({
filterExpressions: state.filterExpressions || [],
selectExpressions: state.selectExpressions || [],
groupExpressions: state.groupExpressions || [],
orderExpressions: state.orderExpressions || [],
calculation: false,
rawMode: false,
withDead: false,
validateRefs: true,
limit: null,
offset: null
}, state);
}
filter(expr) {
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
filterExpressions: [...this.state.filterExpressions, expr]
}));
}
unfilter(exprs) {
let exprSet = new Set(exprs);
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
filterExpressions: this.state.filterExpressions.filter(expr => !exprSet.has(Object.keys(expr)[0]))
}));
}
select(exprs = []) {
if (!Array.isArray(exprs)) {
exprs = [exprs];
}
let query = new Query(_objectSpread(_objectSpread({}, this.state), {}, {
selectExpressions: exprs
}));
query.state.calculation = false;
return query;
}
calculate(expr) {
let query = this.select({
result: expr
});
query.state.calculation = true;
return query;
}
groupBy(exprs) {
if (!Array.isArray(exprs)) {
exprs = [exprs];
}
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
groupExpressions: [...this.state.groupExpressions, ...exprs]
}));
}
orderBy(exprs) {
if (!Array.isArray(exprs)) {
exprs = [exprs];
}
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
orderExpressions: [...this.state.orderExpressions, ...exprs]
}));
}
limit(num) {
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
limit: num
}));
}
offset(num) {
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
offset: num
}));
}
raw() {
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
rawMode: true
}));
}
withDead() {
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
withDead: true
}));
}
withoutValidatedRefs() {
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
validateRefs: false
}));
}
options(opts) {
return new Query(_objectSpread(_objectSpread({}, this.state), {}, {
tableOptions: opts
}));
}
serialize() {
return this.state;
}
}
function getPrimaryOrderBy(query, defaultOrderBy) {
let orderExprs = query.serialize().orderExpressions;
if (orderExprs.length === 0) {
if (defaultOrderBy) {
return _objectSpread({
order: 'asc'
}, defaultOrderBy);
}
return null;
}
let firstOrder = orderExprs[0];
if (typeof firstOrder === 'string') {
return {
field: firstOrder,
order: 'asc'
};
} // Handle this form: { field: 'desc' }
let _Object$keys = Object.keys(firstOrder),
_Object$keys2 = _slicedToArray(_Object$keys, 1),
field = _Object$keys2[0];
return {
field,
order: firstOrder[field]
};
}
function q(table) {
return new Query({
table
});
}
/***/ }),
/***/ "./packages/loot-core/src/shared/rules.js":
/*!************************************************!*\
!*** ./packages/loot-core/src/shared/rules.js ***!
\************************************************/
/*! exports provided: TYPE_INFO, FIELD_TYPES, mapField, friendlyOp, deserializeField, getFieldError, sortNumbers, parse, unparse, makeValue, getApproxNumberThreshold */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TYPE_INFO", function() { return TYPE_INFO; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FIELD_TYPES", function() { return FIELD_TYPES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapField", function() { return mapField; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "friendlyOp", function() { return friendlyOp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deserializeField", function() { return deserializeField; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFieldError", function() { return getFieldError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sortNumbers", function() { return sortNumbers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unparse", function() { return unparse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeValue", function() { return makeValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getApproxNumberThreshold", function() { return getApproxNumberThreshold; });
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util */ "./packages/loot-core/src/shared/util.js");
const _excluded = ["error", "inputKey"];
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
// For now, this info is duplicated from the backend. Figure out how
// to share it later.
const TYPE_INFO = {
date: {
ops: ['is', 'isapprox', 'gt', 'gte', 'lt', 'lte'],
nullable: false
},
id: {
ops: ['is', 'contains', 'oneOf'],
nullable: true
},
string: {
ops: ['is', 'contains', 'oneOf'],
nullable: false
},
number: {
ops: ['is', 'isapprox', 'isbetween', 'gt', 'gte', 'lt', 'lte'],
nullable: false
},
boolean: {
ops: ['is'],
nullable: false
}
};
const FIELD_TYPES = new Map(Object.entries({
imported_payee: 'string',
payee: 'id',
date: 'date',
notes: 'string',
amount: 'number',
amountInflow: 'number',
amountOutfow: 'number',
category: 'id',
account: 'id',
cleared: 'boolean'
}));
function mapField(field, opts) {
opts = opts || {};
switch (field) {
case 'imported_payee':
return 'imported payee';
case 'amount':
if (opts.inflow) {
return 'amount (inflow)';
} else if (opts.outflow) {
return 'amount (outflow)';
}
return 'amount';
case 'amount-inflow':
return 'amount (inflow)';
case 'amount-outflow':
return 'amount (outflow)';
default:
return field;
}
}
function friendlyOp(op, type) {
switch (op) {
case 'oneOf':
return 'one of';
case 'is':
return 'is';
case 'isapprox':
return 'is approx';
case 'isbetween':
return 'is between';
case 'contains':
return 'contains';
case 'gt':
if (type === 'date') {
return 'is after';
}
return 'is greater than';
case 'gte':
if (type === 'date') {
return 'is after or equals';
}
return 'is greater than or equals';
case 'lt':
if (type === 'date') {
return 'is before';
}
return 'is less than';
case 'lte':
if (type === 'date') {
return 'is before or equals';
}
return 'is less than or equals';
case 'true':
return 'is true';
case 'false':
return 'is false';
case 'set':
return 'set';
case 'link-schedule':
return 'link schedule';
default:
return '';
}
}
function deserializeField(field) {
if (field === 'amount-inflow') {
return {
field: 'amount',
options: {
inflow: true
}
};
} else if (field === 'amount-outflow') {
return {
field: 'amount',
options: {
outflow: true
}
};
} else {
return {
field
};
}
}
function getFieldError(type) {
switch (type) {
case 'date-format':
return 'Invalid date format';
case 'no-null':
case 'no-empty-array':
case 'no-empty-string':
return 'Value cannot be empty';
case 'not-number':
return 'Value must be a number';
case 'invalid-field':
return 'Please choose a valid field for this type of rule';
default:
return 'Internal error, sorry! Contact help@actualbudget.com';
}
}
function sortNumbers(num1, num2) {
if (num1 < num2) {
return [num1, num2];
}
return [num2, num1];
}
function parse(item) {
switch (item.type) {
case 'number':
{
let parsed = item.value;
if (item.field === 'amount' && item.op !== 'isbetween') {
parsed = Object(_util__WEBPACK_IMPORTED_MODULE_0__["integerToAmount"])(parsed);
}
return _objectSpread(_objectSpread({}, item), {}, {
value: parsed
});
}
case 'string':
{
let parsed = item.value == null ? '' : item.value;
return _objectSpread(_objectSpread({}, item), {}, {
value: parsed
});
}
default:
}
return _objectSpread(_objectSpread({}, item), {}, {
error: null
});
}
function unparse(_ref) {
let error = _ref.error,
inputKey = _ref.inputKey,
item = _objectWithoutProperties(_ref, _excluded);
switch (item.type) {
case 'number':
{
let unparsed = item.value;
if (item.field === 'amount' && item.op !== 'isbetween') {
unparsed = Object(_util__WEBPACK_IMPORTED_MODULE_0__["amountToInteger"])(unparsed);
}
return _objectSpread(_objectSpread({}, item), {}, {
value: unparsed
});
}
case 'string':
{
let unparsed = item.value == null ? '' : item.value;
return _objectSpread(_objectSpread({}, item), {}, {
value: unparsed
});
}
default:
}
return item;
}
function makeValue(value, cond) {
switch (cond.type) {
case 'number':
{
if (cond.op !== 'isbetween') {
return _objectSpread(_objectSpread({}, cond), {}, {
error: null,
value: value ? Object(_util__WEBPACK_IMPORTED_MODULE_0__["currencyToAmount"])(value) || 0 : 0
});
}
break;
}
default:
}
return _objectSpread(_objectSpread({}, cond), {}, {
error: null,
value
});
}
function getApproxNumberThreshold(number) {
return Math.abs(number) * 0.075 | 0;
}
/***/ }),
/***/ "./packages/loot-core/src/shared/schedules.js":
/*!****************************************************!*\
!*** ./packages/loot-core/src/shared/schedules.js ***!
\****************************************************/
/*! exports provided: getStatus, getHasTransactionsQuery, getRecurringDescription, recurConfigToRSchedule, extractScheduleConds, getScheduledAmount */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStatus", function() { return getStatus; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getHasTransactionsQuery", function() { return getHasTransactionsQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRecurringDescription", function() { return getRecurringDescription; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "recurConfigToRSchedule", function() { return recurConfigToRSchedule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "extractScheduleConds", function() { return extractScheduleConds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getScheduledAmount", function() { return getScheduledAmount; });
/* harmony import */ var _months__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./months */ "./packages/loot-core/src/shared/months.js");
/* harmony import */ var _query__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./query */ "./packages/loot-core/src/shared/query.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getStatus(nextDate, completed, hasTrans) {
let today = _months__WEBPACK_IMPORTED_MODULE_0__["currentDay"]();
if (completed) {
return 'completed';
} else if (hasTrans) {
return 'paid';
} else if (nextDate === today) {
return 'due';
} else if (nextDate > today && nextDate <= _months__WEBPACK_IMPORTED_MODULE_0__["addDays"](today, 7)) {
return 'upcoming';
} else if (nextDate < today) {
return 'missed';
} else {
return 'scheduled';
}
}
function getHasTransactionsQuery(schedules) {
let filters = schedules.map(schedule => {
let dateCond = schedule._conditions.find(c => c.field === 'date');
return {
$and: {
schedule: schedule.id,
date: {
$gte: dateCond && dateCond.op === 'is' ? schedule.next_date : _months__WEBPACK_IMPORTED_MODULE_0__["subDays"](schedule.next_date, 2)
}
}
};
});
return Object(_query__WEBPACK_IMPORTED_MODULE_1__["default"])('transactions').filter({
$or: filters
}).orderBy({
date: 'desc'
}).groupBy('schedule').select(['schedule', 'date']);
}
function makeNumberSuffix(num) {
// Slight abuse of date-fns to turn a number like "1" into the full
// form "1st" but formatting a date with that number
return _months__WEBPACK_IMPORTED_MODULE_0__["format"](new Date(2020, 0, num, 12), 'do');
}
function prettyDayName(day) {
let days = {
SU: 'Sunday',
MO: 'Monday',
TU: 'Tuesday',
WE: 'Wednesday',
TH: 'Thursday',
FR: 'Friday',
SA: 'Saturday'
};
return days[day];
}
function getRecurringDescription(config) {
let interval = config.interval || 1;
switch (config.frequency) {
case 'weekly':
{
let desc = 'Every ';
desc += interval !== 1 ? `${interval} weeks` : 'week';
desc += ' on ' + _months__WEBPACK_IMPORTED_MODULE_0__["format"](config.start, 'EEEE');
return desc;
}
case 'monthly':
{
let desc = 'Every ';
desc += interval !== 1 ? `${interval} months` : 'month';
if (config.patterns && config.patterns.length > 0) {
// Sort the days ascending. We filter out -1 because that
// represents "last days" and should always be last, but this
// sort would put them first
let patterns = [...config.patterns].sort((p1, p2) => {
let typeOrder = (p1.type === 'day' ? 1 : 0) - (p2.type === 'day' ? 1 : 0);
let valOrder = p1.value - p2.value;
if (typeOrder === 0) {
return valOrder;
}
return typeOrder;
}).filter(p => p.value !== -1); // Add on all -1 values to the end
patterns = patterns.concat(config.patterns.filter(p => p.value === -1));
desc += ' on the ';
let strs = [];
let uniqueDays = new Set(patterns.map(p => p.type));
let isSameDay = uniqueDays.length === 1 && !uniqueDays.has('day');
for (let pattern of patterns) {
if (pattern.type === 'day') {
if (pattern.value === -1) {
strs.push('last day');
} else {
// Example: 15th day
strs.push(makeNumberSuffix(pattern.value));
}
} else {
let dayName = isSameDay ? '' : ' ' + prettyDayName(pattern.type);
if (pattern.value === -1) {
// Example: last Monday
strs.push('last' + dayName);
} else {
// Example: 3rd Monday
strs.push(makeNumberSuffix(pattern.value) + dayName);
}
}
}
if (strs.length > 2) {
desc += strs.slice(0, strs.length - 1).join(', ');
desc += ', and ';
desc += strs[strs.length - 1];
} else {
desc += strs.join(' and ');
}
if (isSameDay) {
desc += ' ' + prettyDayName(patterns[0].type);
}
} else {
desc += ' on the ' + _months__WEBPACK_IMPORTED_MODULE_0__["format"](config.start, 'do');
}
return desc;
}
case 'yearly':
{
let desc = 'Every ';
desc += interval !== 1 ? `${interval} years` : 'year';
desc += ' on ' + _months__WEBPACK_IMPORTED_MODULE_0__["format"](config.start, 'LLL do');
return desc;
}
default:
return 'Recurring error';
}
}
function recurConfigToRSchedule(config) {
let base = {
start: _months__WEBPACK_IMPORTED_MODULE_0__["parseDate"](config.start),
frequency: config.frequency.toUpperCase(),
byHourOfDay: [12]
};
if (config.interval) {
base.interval = config.interval;
}
let abbrevDay = name => name.slice(0, 2).toUpperCase();
switch (config.frequency) {
case 'weekly':
// Nothing to do
return [base];
case 'monthly':
if (config.patterns && config.patterns.length > 0) {
let days = config.patterns.filter(p => p.type === 'day');
let dayNames = config.patterns.filter(p => p.type !== 'day');
return [days.length > 0 && _objectSpread(_objectSpread({}, base), {}, {
byDayOfMonth: days.map(p => p.value)
}), dayNames.length > 0 && _objectSpread(_objectSpread({}, base), {}, {
byDayOfWeek: dayNames.map(p => [abbrevDay(p.type), p.value])
})].filter(Boolean);
} else {
// Nothing to do
return [base];
}
case 'yearly':
return [base];
default:
throw new Error('Invalid recurring date config');
}
}
function extractScheduleConds(conditions) {
return {
payee: conditions.find(cond => cond.op === 'is' && cond.field === 'payee') || conditions.find(cond => cond.op === 'is' && cond.field === 'description') || null,
account: conditions.find(cond => cond.op === 'is' && cond.field === 'account') || conditions.find(cond => cond.op === 'is' && cond.field === 'acct') || null,
amount: conditions.find(cond => (cond.op === 'is' || cond.op === 'isapprox' || cond.op === 'isbetween') && cond.field === 'amount') || null,
date: conditions.find(cond => (cond.op === 'is' || cond.op === 'isapprox') && cond.field === 'date') || null
};
}
function getScheduledAmount(amount) {
if (amount && typeof amount !== 'number') {
return (amount.num1 + amount.num2) / 2 | 0;
}
return amount;
}
/***/ }),
/***/ "./packages/loot-core/src/shared/transactions.js":
/*!*******************************************************!*\
!*** ./packages/loot-core/src/shared/transactions.js ***!
\*******************************************************/
/*! exports provided: makeChild, recalculateSplit, findParentIndex, getSplit, ungroupTransactions, groupTransaction, ungroupTransaction, applyTransactionDiff, replaceTransactions, addSplitTransaction, updateTransaction, deleteTransaction, splitTransaction, realizeTempTransactions */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeChild", function() { return makeChild; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "recalculateSplit", function() { return recalculateSplit; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findParentIndex", function() { return findParentIndex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSplit", function() { return getSplit; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ungroupTransactions", function() { return ungroupTransactions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "groupTransaction", function() { return groupTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ungroupTransaction", function() { return ungroupTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyTransactionDiff", function() { return applyTransactionDiff; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "replaceTransactions", function() { return replaceTransactions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addSplitTransaction", function() { return addSplitTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateTransaction", function() { return updateTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteTransaction", function() { return deleteTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "splitTransaction", function() { return splitTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "realizeTempTransactions", function() { return realizeTempTransactions; });
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util */ "./packages/loot-core/src/shared/util.js");
const _excluded = ["subtransactions"];
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const uuid = __webpack_require__(/*! ../platform/uuid */ "./packages/loot-core/src/platform/uuid/index.electron.js"); // The amount might be null when adding a new transaction
function num(n) {
return typeof n === 'number' ? n : 0;
}
function SplitTransactionError(total, parent) {
let difference = num(parent.amount) - total;
return {
type: 'SplitTransactionError',
version: 1,
difference
};
}
function makeChild(parent, data) {
let prefix = parent.id === 'temp' ? 'temp' : '';
return _objectSpread(_objectSpread({
amount: 0
}, data), {}, {
payee: data.payee || parent.payee,
id: data.id ? data.id : prefix + uuid.v4Sync(),
account: parent.account,
date: parent.date,
cleared: parent.cleared != null ? parent.cleared : null,
starting_balance_flag: parent.starting_balance_flag != null ? parent.starting_balance_flag : null,
is_child: true,
parent_id: parent.id,
error: null
});
}
function recalculateSplit(trans) {
// Calculate the new total of split transactions and make sure
// that it equals the parent amount
const total = trans.subtransactions.reduce((acc, t) => acc + num(t.amount), 0);
return _objectSpread(_objectSpread({}, trans), {}, {
error: total === num(trans.amount) ? null : SplitTransactionError(total, trans)
});
}
function findParentIndex(transactions, idx) {
// This relies on transactions being sorted in a way where parents
// are always before children, which is enforced in the db layer.
// Walk backwards and find the last parent;
while (idx >= 0) {
let trans = transactions[idx];
if (trans.is_parent) {
return idx;
}
idx--;
}
return null;
}
function getSplit(transactions, parentIndex) {
let split = [transactions[parentIndex]];
let curr = parentIndex + 1;
while (curr < transactions.length && transactions[curr].is_child) {
split.push(transactions[curr]);
curr++;
}
return split;
}
function ungroupTransactions(transactions) {
let x = transactions.reduce((list, parent) => {
let subtransactions = parent.subtransactions,
trans = _objectWithoutProperties(parent, _excluded);
subtransactions = subtransactions || [];
list.push(trans);
for (let i = 0; i < subtransactions.length; i++) {
list.push(subtransactions[i]);
}
return list;
}, []);
return x;
}
function groupTransaction(split) {
return _objectSpread(_objectSpread({}, split[0]), {}, {
subtransactions: split.slice(1)
});
}
function ungroupTransaction(split) {
if (split == null) {
return null;
}
return ungroupTransactions([split]);
}
function applyTransactionDiff(groupedTrans, diff) {
return groupTransaction(Object(_util__WEBPACK_IMPORTED_MODULE_0__["applyChanges"])(diff, ungroupTransaction(groupedTrans)));
}
function replaceTransactions(transactions, id, func) {
let idx = transactions.findIndex(t => t.id === id);
let trans = transactions[idx];
let transactionsCopy = [...transactions];
if (idx === -1) {
throw new Error('Tried to edit unknown transaction id: ' + id);
}
if (trans.is_parent || trans.is_child) {
let parentIndex = findParentIndex(transactions, idx);
if (parentIndex == null) {
console.log('Cannot find parent index');
return {
diff: {
deleted: [],
updated: []
}
};
}
let split = getSplit(transactions, parentIndex);
let grouped = func(groupTransaction(split));
let newSplit = ungroupTransaction(grouped);
let diff;
if (newSplit == null) {
// If everything was deleted, just delete the parent which will
// delete everything
diff = {
deleted: [{
id: split[0].id
}],
updated: []
};
grouped = {
id: split[0].id,
_deleted: true
};
transactionsCopy.splice(parentIndex, split.length);
} else {
diff = Object(_util__WEBPACK_IMPORTED_MODULE_0__["diffItems"])(split, newSplit);
transactionsCopy.splice(parentIndex, split.length, ...newSplit);
}
return {
data: transactionsCopy,
newTransaction: grouped,
diff
};
} else {
let grouped = func(trans);
let newTrans = ungroupTransaction(grouped) || [];
if (grouped) {
grouped.subtransactions = grouped.subtransactions || [];
}
transactionsCopy.splice(idx, 1, ...newTrans);
return {
data: transactionsCopy,
newTransaction: grouped || {
id: trans.id,
_deleted: true
},
diff: Object(_util__WEBPACK_IMPORTED_MODULE_0__["diffItems"])([trans], newTrans)
};
}
}
function addSplitTransaction(transactions, id) {
return replaceTransactions(transactions, id, trans => {
if (!trans.is_parent) {
return trans;
}
let prevSub = Object(_util__WEBPACK_IMPORTED_MODULE_0__["last"])(trans.subtransactions);
trans.subtransactions.push(makeChild(trans, {
amount: 0,
sort_order: num(prevSub && prevSub.sort_order) - 1
}));
return trans;
});
}
function updateTransaction(transactions, transaction) {
return replaceTransactions(transactions, transaction.id, trans => {
if (trans.is_parent) {
let parent = trans.id === transaction.id ? transaction : trans;
let sub = trans.subtransactions.map(t => {
// Make sure to update the children to reflect the updated
// properties (if the parent updated)
let child = t;
if (trans.id === transaction.id) {
child = _objectSpread(_objectSpread({}, t), {}, {
payee: t.payee === trans.payee ? transaction.payee : t.payee
});
} else if (t.id === transaction.id) {
child = transaction;
}
return makeChild(parent, child);
});
return recalculateSplit(_objectSpread(_objectSpread({}, parent), {}, {
subtransactions: sub
}));
} else {
return transaction;
}
});
}
function deleteTransaction(transactions, id) {
return replaceTransactions(transactions, id, trans => {
if (trans.is_parent) {
if (trans.id === id) {
return null;
} else if (trans.subtransactions.length === 1) {
return _objectSpread(_objectSpread({}, trans), {}, {
subtransactions: null,
is_parent: false,
error: null
});
} else {
let sub = trans.subtransactions.filter(t => t.id !== id);
return recalculateSplit(_objectSpread(_objectSpread({}, trans), {}, {
subtransactions: sub
}));
}
} else {
return null;
}
});
}
function splitTransaction(transactions, id) {
return replaceTransactions(transactions, id, trans => {
if (trans.is_parent || trans.is_child) {
return trans;
}
return _objectSpread(_objectSpread({}, trans), {}, {
is_parent: true,
error: num(trans.amount) === 0 ? null : SplitTransactionError(0, trans),
subtransactions: [makeChild(trans, {
amount: 0,
sort_order: -1
})]
});
});
}
function realizeTempTransactions(transactions) {
let parent = transactions.find(t => !t.is_child);
parent = _objectSpread(_objectSpread({}, parent), {}, {
id: uuid.v4Sync()
});
let children = transactions.filter(t => t.is_child);
return [parent, ...children.map(child => _objectSpread(_objectSpread({}, child), {}, {
id: uuid.v4Sync(),
parent_id: parent.id
}))];
}
/***/ }),
/***/ "./packages/loot-core/src/shared/util.js":
/*!***********************************************!*\
!*** ./packages/loot-core/src/shared/util.js ***!
\***********************************************/
/*! exports provided: cleanUUID, last, mergeObjects, composeCellChanges, flattenArray, shallowEqual, getChangedValues, hasFieldsChanged, applyChanges, partitionByField, groupBy, groupBySingle, diffItems, groupById, debugMemoFailure, setIn, getIn, throwError, fastSetMerge, titleFirst, numberFormats, setNumberFormat, getNumberFormat, toRelaxedNumber, toRelaxedInteger, integerToCurrency, amountToCurrency, amountToPrettyCurrency, currencyToAmount, currencyToInteger, stringToInteger, amountToInteger, integerToAmount, looselyParseAmount, semverToNumber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cleanUUID", function() { return cleanUUID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "last", function() { return last; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeObjects", function() { return mergeObjects; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "composeCellChanges", function() { return composeCellChanges; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "flattenArray", function() { return flattenArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shallowEqual", function() { return shallowEqual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getChangedValues", function() { return getChangedValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasFieldsChanged", function() { return hasFieldsChanged; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyChanges", function() { return applyChanges; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "partitionByField", function() { return partitionByField; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "groupBy", function() { return groupBy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "groupBySingle", function() { return groupBySingle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "diffItems", function() { return diffItems; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "groupById", function() { return groupById; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "debugMemoFailure", function() { return debugMemoFailure; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setIn", function() { return setIn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getIn", function() { return getIn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throwError", function() { return throwError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fastSetMerge", function() { return fastSetMerge; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "titleFirst", function() { return titleFirst; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "numberFormats", function() { return numberFormats; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setNumberFormat", function() { return setNumberFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNumberFormat", function() { return getNumberFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toRelaxedNumber", function() { return toRelaxedNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toRelaxedInteger", function() { return toRelaxedInteger; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "integerToCurrency", function() { return integerToCurrency; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "amountToCurrency", function() { return amountToCurrency; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "amountToPrettyCurrency", function() { return amountToPrettyCurrency; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "currencyToAmount", function() { return currencyToAmount; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "currencyToInteger", function() { return currencyToInteger; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stringToInteger", function() { return stringToInteger; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "amountToInteger", function() { return amountToInteger; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "integerToAmount", function() { return integerToAmount; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "looselyParseAmount", function() { return looselyParseAmount; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "semverToNumber", function() { return semverToNumber; });
const _excluded = ["id"];
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
let currencyFormatter = __webpack_require__(/*! currency-formatter */ "./node_modules/currency-formatter/index.js");
function cleanUUID(uuid) {
return uuid.replace(/-/g, '');
}
function last(arr) {
return arr[arr.length - 1];
}
function mergeObjects(objects) {
return Object.assign.apply(null, [{}, ...objects]);
}
function composeCellChanges(objects) {
const merged = {};
Object.keys(objects).forEach(key => {
if (merged[key]) {
merged[key] = _objectSpread(_objectSpread({}, merged[key]), objects[key]);
} else {
merged[key] = objects[key];
}
});
}
function flattenArray(arrays) {
return Array.prototype.concat.apply([], arrays);
}
function shallowEqual(a, b) {
if (a === b) {
return true;
}
var numKeysA = 0,
numKeysB = 0,
key;
for (key in b) {
numKeysB++;
if (!a.hasOwnProperty(key) || a[key] !== b[key]) {
return false;
}
}
for (key in a) {
numKeysA++;
}
return numKeysA === numKeysB;
}
function getChangedValues(obj1, obj2) {
// Keep the id field because this is mostly used to diff database
// objects
const diff = obj1.id ? {
id: obj1.id
} : {};
const keys = Object.keys(obj2);
let hasChanged = false;
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
if (obj1[key] !== obj2[key]) {
diff[key] = obj2[key];
hasChanged = true;
}
}
return hasChanged ? diff : null;
}
function hasFieldsChanged(obj1, obj2, fields) {
let changed = false;
for (var i = 0; i < fields.length; i++) {
let field = fields[i];
if (obj1[field] !== obj2[field]) {
changed = true;
break;
}
}
return changed;
}
function applyChanges(changes, items) {
items = [...items];
if (changes.added) {
changes.added.forEach(add => {
items.push(add);
});
}
if (changes.updated) {
changes.updated.forEach(_ref => {
let id = _ref.id,
fields = _objectWithoutProperties(_ref, _excluded);
const idx = items.findIndex(t => t.id === id);
items[idx] = _objectSpread(_objectSpread({}, items[idx]), fields);
});
}
if (changes.deleted) {
changes.deleted.forEach(t => {
const idx = items.findIndex(t2 => t.id === t2.id);
if (idx !== -1) {
items.splice(idx, 1);
}
});
}
return items;
}
function partitionByField(data, field) {
let res = new Map();
for (let i = 0; i < data.length; i++) {
let item = data[i];
let key = item[field];
let items = res.get(key) || [];
items.push(item);
res.set(key, items);
}
return res;
}
function groupBy(data, field, mapper) {
let res = new Map();
for (let i = 0; i < data.length; i++) {
let item = data[i];
let key = item[field];
let existing = res.get(key) || [];
res.set(key, existing.concat([mapper ? mapper(item) : data[i]]));
}
return res;
}
function groupBySingle(data, field, mapper) {
let res = new Map();
for (let i = 0; i < data.length; i++) {
let item = data[i];
let key = item[field];
if (res.has(key)) {
throw new Error('groupBySingle found conflicting key: ' + key);
}
res.set(key, mapper ? mapper(item) : data[i]);
}
return res;
} // This should replace the existing `groupById` function, since a
// `Map` is better, but we can't swap it out because `Map` has a
// different API and we need to go through and update everywhere that
// uses it.
function _groupById(data) {
let res = new Map();
for (let i = 0; i < data.length; i++) {
let item = data[i];
res.set(item.id, item);
}
return res;
}
function diffItems(items, newItems) {
let grouped = _groupById(items);
let newGrouped = _groupById(newItems);
let added = [];
let updated = [];
let deleted = items.filter(item => !newGrouped.has(item.id)).map(item => ({
id: item.id
}));
newItems.forEach(newItem => {
let item = grouped.get(newItem.id);
if (!item) {
added.push(newItem);
} else {
const changes = getChangedValues(item, newItem);
if (changes) {
updated.push(changes);
}
}
});
return {
added,
updated,
deleted
};
}
function groupById(data) {
let res = {};
for (let i = 0; i < data.length; i++) {
let item = data[i];
res[item.id] = item;
}
return res;
}
function debugMemoFailure(prevProps, nextProps) {
let changed = getChangedValues(prevProps, nextProps);
if (changed !== null) {
console.log(changed);
}
return changed === null;
}
function setIn(map, keys, item) {
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
if (i === keys.length - 1) {
map.set(key, item);
} else {
if (!map.has(key)) {
map.set(key, new Map());
}
map = map.get(key);
}
}
}
function getIn(map, keys) {
let item = map;
for (let i = 0; i < keys.length; i++) {
item = item.get(keys[i]);
if (item == null) {
return item;
}
}
return item;
} // Useful for throwing exception from expressions
function throwError(err) {
throw err;
}
function fastSetMerge(set1, set2) {
let finalSet = new Set(set1);
let iter = set2.values();
let value = iter.next();
while (!value.done) {
finalSet.add(value.value);
value = iter.next();
}
return finalSet;
}
function titleFirst(str) {
return str[0].toUpperCase() + str.slice(1);
}
let numberFormats = [{
value: 'comma-dot',
label: '1,000.33'
}, {
value: 'dot-comma',
label: '1.000,33'
}, {
value: 'space-comma',
label: '1 000,33'
}];
let numberFormat = {
value: null,
formatter: null,
regex: null
};
function setNumberFormat(format) {
let locale, regex, separator;
switch (format) {
case 'space-comma':
locale = 'za-ZA';
regex = /[^-0-9,]/g;
separator = ',';
break;
case 'dot-comma':
locale = 'de-DE';
regex = /[^-0-9,]/g;
separator = ',';
break;
case 'comma-dot':
default:
locale = 'en-US';
regex = /[^-0-9.]/g;
separator = '.';
}
numberFormat = {
value: format,
separator,
// This is the keep in line with the Intl API which we might
// switch to when it's available on all mobile platforms
formatter: {
format: number => currencyFormatter.format(number, {
locale,
format: '%v'
})
},
regex
};
}
function getNumberFormat() {
return numberFormat;
}
setNumberFormat('1,000.33');
function toRelaxedNumber(value) {
return integerToAmount(currencyToInteger(value) || 0);
}
function toRelaxedInteger(value) {
return stringToInteger(value) || 0;
}
function integerToCurrency(n) {
// Awesome
return numberFormat.formatter.format(n / 100);
}
function amountToCurrency(n) {
return numberFormat.formatter.format(n);
}
function amountToPrettyCurrency(n, code) {
return currencyFormatter.format(n, {
code
});
}
function currencyToAmount(str) {
let amount = parseFloat(str.replace(numberFormat.regex, '').replace(numberFormat.separator, '.'));
return isNaN(amount) ? null : amount;
}
function currencyToInteger(str) {
let amount = currencyToAmount(str);
return amount ? amountToInteger(amount) : null;
}
function stringToInteger(str) {
let amount = parseInt(str.replace(/[^-0-9.,]/g, ''));
if (!isNaN(amount)) {
return amount;
}
return null;
}
function amountToInteger(n) {
return Math.round(n * 100);
}
function integerToAmount(n) {
return parseFloat((n / 100).toFixed(2));
} // This is used when the input format could be anything (from
// financial files and we don't want to parse based on the user's
// number format, because the user could be importing from many
// currencies. We extract out the numbers and just ignore separators.
function looselyParseAmount(amount) {
function safeNumber(v) {
return isNaN(v) ? null : v;
}
let m = amount.match(/[.,][^.,]*$/);
if (!m || m.index === 0) {
return safeNumber(parseFloat(amount));
}
let left = amount.slice(0, m.index);
let right = amount.slice(m.index + 1);
return safeNumber(parseFloat(left.replace(/[^0-9-]/g, '') + '.' + right));
}
function semverToNumber(str) {
return parseInt('1' + str.split('.').map(x => {
return ('000' + x.replace(/[^0-9]/g, '')).slice(-3);
}).join(''));
}
/***/ }),
/***/ "better-sqlite3":
/*!*********************************!*\
!*** external "better-sqlite3" ***!
\*********************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = require("better-sqlite3");
/***/ }),
/***/ "crypto":
/*!*************************!*\
!*** external "crypto" ***!
\*************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = require("crypto");
/***/ }),
/***/ "fs":
/*!*********************!*\
!*** external "fs" ***!
\*********************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = require("fs");
/***/ }),
/***/ "node-fetch":
/*!*****************************!*\
!*** external "node-fetch" ***!
\*****************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = require("node-fetch");
/***/ }),
/***/ "node-libofx":
/*!******************************!*\
!*** external "node-libofx" ***!
\******************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = require("node-libofx");
/***/ }),
/***/ "path":
/*!***********************!*\
!*** external "path" ***!
\***********************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = require("path");
/***/ }),
/***/ "stream":
/*!*************************!*\
!*** external "stream" ***!
\*************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = require("stream");
/***/ }),
/***/ "string_decoder":
/*!*********************************!*\
!*** external "string_decoder" ***!
\*********************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = require("string_decoder");
/***/ }),
/***/ "util":
/*!***********************!*\
!*** external "util" ***!
\***********************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = require("util");
/***/ }),
/***/ "zlib":
/*!***********************!*\
!*** external "zlib" ***!
\***********************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = require("zlib");
/***/ })
/******/ });
//# sourceMappingURL=bundle.api.js.map