UNPKG

rrule

Version:

JavaScript library for working with recurrence rules for calendar dates.

1,383 lines (1,333 loc) 131 kB
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["rrule"] = factory(); else root["rrule"] = factory(); })(typeof self !== 'undefined' ? self : this, () => { return /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ // The require scope /******/ var __webpack_require__ = {}; /******/ /************************************************************************/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /************************************************************************/ var __webpack_exports__ = {}; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { "ALL_WEEKDAYS": () => (/* reexport */ ALL_WEEKDAYS), "Frequency": () => (/* reexport */ Frequency), "RRule": () => (/* reexport */ RRule), "RRuleSet": () => (/* reexport */ RRuleSet), "Weekday": () => (/* reexport */ Weekday), "datetime": () => (/* reexport */ datetime), "rrulestr": () => (/* reexport */ rrulestr) }); ;// CONCATENATED MODULE: ./src/weekday.ts // ============================================================================= // Weekday // ============================================================================= var ALL_WEEKDAYS = [ 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU', ]; var Weekday = /** @class */ (function () { function Weekday(weekday, n) { if (n === 0) throw new Error("Can't create weekday with n == 0"); this.weekday = weekday; this.n = n; } Weekday.fromStr = function (str) { return new Weekday(ALL_WEEKDAYS.indexOf(str)); }; // __call__ - Cannot call the object directly, do it through // e.g. RRule.TH.nth(-1) instead, Weekday.prototype.nth = function (n) { return this.n === n ? this : new Weekday(this.weekday, n); }; // __eq__ Weekday.prototype.equals = function (other) { return this.weekday === other.weekday && this.n === other.n; }; // __repr__ Weekday.prototype.toString = function () { var s = ALL_WEEKDAYS[this.weekday]; if (this.n) s = (this.n > 0 ? '+' : '') + String(this.n) + s; return s; }; Weekday.prototype.getJsWeekday = function () { return this.weekday === 6 ? 0 : this.weekday + 1; }; return Weekday; }()); ;// CONCATENATED MODULE: ./src/helpers.ts // ============================================================================= // Helper functions // ============================================================================= var isPresent = function (value) { return value !== null && value !== undefined; }; var isNumber = function (value) { return typeof value === 'number'; }; var isWeekdayStr = function (value) { return typeof value === 'string' && ALL_WEEKDAYS.includes(value); }; var isArray = Array.isArray; /** * Simplified version of python's range() */ var range = function (start, end) { if (end === void 0) { end = start; } if (arguments.length === 1) { end = start; start = 0; } var rang = []; for (var i = start; i < end; i++) rang.push(i); return rang; }; var clone = function (array) { return [].concat(array); }; var repeat = function (value, times) { var i = 0; var array = []; if (isArray(value)) { for (; i < times; i++) array[i] = [].concat(value); } else { for (; i < times; i++) array[i] = value; } return array; }; var toArray = function (item) { if (isArray(item)) { return item; } return [item]; }; function padStart(item, targetLength, padString) { if (padString === void 0) { padString = ' '; } var str = String(item); targetLength = targetLength >> 0; if (str.length > targetLength) { return String(str); } targetLength = targetLength - str.length; if (targetLength > padString.length) { padString += repeat(padString, targetLength / padString.length); } return padString.slice(0, targetLength) + String(str); } /** * Python like split */ var split = function (str, sep, num) { var splits = str.split(sep); return num ? splits.slice(0, num).concat([splits.slice(num).join(sep)]) : splits; }; /** * closure/goog/math/math.js:modulo * Copyright 2006 The Closure Library Authors. * The % operator in JavaScript returns the remainder of a / b, but differs from * some other languages in that the result will have the same sign as the * dividend. For example, -1 % 8 == -1, whereas in some other languages * (such as Python) the result would be 7. This function emulates the more * correct modulo behavior, which is useful for certain applications such as * calculating an offset index in a circular list. * * @param {number} a The dividend. * @param {number} b The divisor. * @return {number} a % b where the result is between 0 and b (either 0 <= x < b * or b < x <= 0, depending on the sign of b). */ var pymod = function (a, b) { var r = a % b; // If r and b differ in sign, add b to wrap the result to the correct sign. return r * b < 0 ? r + b : r; }; /** * @see: <http://docs.python.org/library/functions.html#divmod> */ var divmod = function (a, b) { return { div: Math.floor(a / b), mod: pymod(a, b) }; }; var empty = function (obj) { return !isPresent(obj) || obj.length === 0; }; /** * Python-like boolean * * @return {Boolean} value of an object/primitive, taking into account * the fact that in Python an empty list's/tuple's * boolean value is False, whereas in JS it's true */ var notEmpty = function (obj) { return !empty(obj); }; /** * Return true if a value is in an array */ var includes = function (arr, val) { return notEmpty(arr) && arr.indexOf(val) !== -1; }; ;// CONCATENATED MODULE: ./src/dateutil.ts var datetime = function (y, m, d, h, i, s) { if (h === void 0) { h = 0; } if (i === void 0) { i = 0; } if (s === void 0) { s = 0; } return new Date(Date.UTC(y, m - 1, d, h, i, s)); }; /** * General date-related utilities. * Also handles several incompatibilities between JavaScript and Python * */ var MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; /** * Number of milliseconds of one day */ var ONE_DAY = 1000 * 60 * 60 * 24; /** * @see: <http://docs.python.org/library/datetime.html#datetime.MAXYEAR> */ var MAXYEAR = 9999; /** * Python uses 1-Jan-1 as the base for calculating ordinals but we don't * want to confuse the JS engine with milliseconds > Number.MAX_NUMBER, * therefore we use 1-Jan-1970 instead */ var ORDINAL_BASE = datetime(1970, 1, 1); /** * Python: MO-SU: 0 - 6 * JS: SU-SAT 0 - 6 */ var PY_WEEKDAYS = [6, 0, 1, 2, 3, 4, 5]; /** * py_date.timetuple()[7] */ var getYearDay = function (date) { var dateNoTime = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); return (Math.ceil((dateNoTime.valueOf() - new Date(date.getUTCFullYear(), 0, 1).valueOf()) / ONE_DAY) + 1); }; var isLeapYear = function (year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; }; var isDate = function (value) { return value instanceof Date; }; var isValidDate = function (value) { return isDate(value) && !isNaN(value.getTime()); }; /** * @return {Number} the date's timezone offset in ms */ var tzOffset = function (date) { return date.getTimezoneOffset() * 60 * 1000; }; /** * @see: <http://www.mcfedries.com/JavaScript/DaysBetween.asp> */ var daysBetween = function (date1, date2) { // The number of milliseconds in one day // Convert both dates to milliseconds var date1ms = date1.getTime(); var date2ms = date2.getTime(); // Calculate the difference in milliseconds var differencems = date1ms - date2ms; // Convert back to days and return return Math.round(differencems / ONE_DAY); }; /** * @see: <http://docs.python.org/library/datetime.html#datetime.date.toordinal> */ var toOrdinal = function (date) { return daysBetween(date, ORDINAL_BASE); }; /** * @see - <http://docs.python.org/library/datetime.html#datetime.date.fromordinal> */ var fromOrdinal = function (ordinal) { return new Date(ORDINAL_BASE.getTime() + ordinal * ONE_DAY); }; var getMonthDays = function (date) { var month = date.getUTCMonth(); return month === 1 && isLeapYear(date.getUTCFullYear()) ? 29 : MONTH_DAYS[month]; }; /** * @return {Number} python-like weekday */ var getWeekday = function (date) { return PY_WEEKDAYS[date.getUTCDay()]; }; /** * @see: <http://docs.python.org/library/calendar.html#calendar.monthrange> */ var monthRange = function (year, month) { var date = datetime(year, month + 1, 1); return [getWeekday(date), getMonthDays(date)]; }; /** * @see: <http://docs.python.org/library/datetime.html#datetime.datetime.combine> */ var combine = function (date, time) { time = time || date; return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), time.getHours(), time.getMinutes(), time.getSeconds(), time.getMilliseconds())); }; var dateutil_clone = function (date) { var dolly = new Date(date.getTime()); return dolly; }; var cloneDates = function (dates) { var clones = []; for (var i = 0; i < dates.length; i++) { clones.push(dateutil_clone(dates[i])); } return clones; }; /** * Sorts an array of Date or Time objects */ var sort = function (dates) { dates.sort(function (a, b) { return a.getTime() - b.getTime(); }); }; var timeToUntilString = function (time, utc) { if (utc === void 0) { utc = true; } var date = new Date(time); return [ padStart(date.getUTCFullYear().toString(), 4, '0'), padStart(date.getUTCMonth() + 1, 2, '0'), padStart(date.getUTCDate(), 2, '0'), 'T', padStart(date.getUTCHours(), 2, '0'), padStart(date.getUTCMinutes(), 2, '0'), padStart(date.getUTCSeconds(), 2, '0'), utc ? 'Z' : '', ].join(''); }; var untilStringToDate = function (until) { var re = /^(\d{4})(\d{2})(\d{2})(T(\d{2})(\d{2})(\d{2})Z?)?$/; var bits = re.exec(until); if (!bits) throw new Error("Invalid UNTIL value: ".concat(until)); return new Date(Date.UTC(parseInt(bits[1], 10), parseInt(bits[2], 10) - 1, parseInt(bits[3], 10), parseInt(bits[5], 10) || 0, parseInt(bits[6], 10) || 0, parseInt(bits[7], 10) || 0)); }; var dateTZtoISO8601 = function (date, timeZone) { // date format for sv-SE is almost ISO8601 var dateStr = date.toLocaleString('sv-SE', { timeZone: timeZone }); // '2023-02-07 10:41:36' return dateStr.replace(' ', 'T') + 'Z'; }; var dateInTimeZone = function (date, timeZone) { var localTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; // Date constructor can only reliably parse dates in ISO8601 format var dateInLocalTZ = new Date(dateTZtoISO8601(date, localTimeZone)); var dateInTargetTZ = new Date(dateTZtoISO8601(date, timeZone !== null && timeZone !== void 0 ? timeZone : 'UTC')); var tzOffset = dateInTargetTZ.getTime() - dateInLocalTZ.getTime(); return new Date(date.getTime() - tzOffset); }; ;// CONCATENATED MODULE: ./src/iterresult.ts /** * This class helps us to emulate python's generators, sorta. */ var IterResult = /** @class */ (function () { function IterResult(method, args) { this.minDate = null; this.maxDate = null; this._result = []; this.total = 0; this.method = method; this.args = args; if (method === 'between') { this.maxDate = args.inc ? args.before : new Date(args.before.getTime() - 1); this.minDate = args.inc ? args.after : new Date(args.after.getTime() + 1); } else if (method === 'before') { this.maxDate = args.inc ? args.dt : new Date(args.dt.getTime() - 1); } else if (method === 'after') { this.minDate = args.inc ? args.dt : new Date(args.dt.getTime() + 1); } } /** * Possibly adds a date into the result. * * @param {Date} date - the date isn't necessarly added to the result * list (if it is too late/too early) * @return {Boolean} true if it makes sense to continue the iteration * false if we're done. */ IterResult.prototype.accept = function (date) { ++this.total; var tooEarly = this.minDate && date < this.minDate; var tooLate = this.maxDate && date > this.maxDate; if (this.method === 'between') { if (tooEarly) return true; if (tooLate) return false; } else if (this.method === 'before') { if (tooLate) return false; } else if (this.method === 'after') { if (tooEarly) return true; this.add(date); return false; } return this.add(date); }; /** * * @param {Date} date that is part of the result. * @return {Boolean} whether we are interested in more values. */ IterResult.prototype.add = function (date) { this._result.push(date); return true; }; /** * 'before' and 'after' return only one date, whereas 'all' * and 'between' an array. * * @return {Date,Array?} */ IterResult.prototype.getValue = function () { var res = this._result; switch (this.method) { case 'all': case 'between': return res; case 'before': case 'after': default: return (res.length ? res[res.length - 1] : null); } }; IterResult.prototype.clone = function () { return new IterResult(this.method, this.args); }; return IterResult; }()); /* harmony default export */ const iterresult = (IterResult); ;// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; } return __assign.apply(this, arguments); } function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var __setModuleDefault = Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } function __classPrivateFieldIn(state, receiver) { if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); return typeof state === "function" ? receiver === state : state.has(receiver); } ;// CONCATENATED MODULE: ./src/callbackiterresult.ts /** * IterResult subclass that calls a callback function on each add, * and stops iterating when the callback returns false. */ var CallbackIterResult = /** @class */ (function (_super) { __extends(CallbackIterResult, _super); function CallbackIterResult(method, args, iterator) { var _this = _super.call(this, method, args) || this; _this.iterator = iterator; return _this; } CallbackIterResult.prototype.add = function (date) { if (this.iterator(date, this._result.length)) { this._result.push(date); return true; } return false; }; return CallbackIterResult; }(iterresult)); /* harmony default export */ const callbackiterresult = (CallbackIterResult); ;// CONCATENATED MODULE: ./src/nlp/i18n.ts // ============================================================================= // i18n // ============================================================================= var ENGLISH = { dayNames: [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ], monthNames: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ], tokens: { SKIP: /^[ \r\n\t]+|^\.$/, number: /^[1-9][0-9]*/, numberAsText: /^(one|two|three)/i, every: /^every/i, 'day(s)': /^days?/i, 'weekday(s)': /^weekdays?/i, 'week(s)': /^weeks?/i, 'hour(s)': /^hours?/i, 'minute(s)': /^minutes?/i, 'month(s)': /^months?/i, 'year(s)': /^years?/i, on: /^(on|in)/i, at: /^(at)/i, the: /^the/i, first: /^first/i, second: /^second/i, third: /^third/i, nth: /^([1-9][0-9]*)(\.|th|nd|rd|st)/i, last: /^last/i, for: /^for/i, 'time(s)': /^times?/i, until: /^(un)?til/i, monday: /^mo(n(day)?)?/i, tuesday: /^tu(e(s(day)?)?)?/i, wednesday: /^we(d(n(esday)?)?)?/i, thursday: /^th(u(r(sday)?)?)?/i, friday: /^fr(i(day)?)?/i, saturday: /^sa(t(urday)?)?/i, sunday: /^su(n(day)?)?/i, january: /^jan(uary)?/i, february: /^feb(ruary)?/i, march: /^mar(ch)?/i, april: /^apr(il)?/i, may: /^may/i, june: /^june?/i, july: /^july?/i, august: /^aug(ust)?/i, september: /^sep(t(ember)?)?/i, october: /^oct(ober)?/i, november: /^nov(ember)?/i, december: /^dec(ember)?/i, comma: /^(,\s*|(and|or)\s*)+/i, }, }; /* harmony default export */ const i18n = (ENGLISH); ;// CONCATENATED MODULE: ./src/nlp/totext.ts // ============================================================================= // Helper functions // ============================================================================= /** * Return true if a value is in an array */ var contains = function (arr, val) { return arr.indexOf(val) !== -1; }; var defaultGetText = function (id) { return id.toString(); }; var defaultDateFormatter = function (year, month, day) { return "".concat(month, " ").concat(day, ", ").concat(year); }; /** * * @param {RRule} rrule * Optional: * @param {Function} gettext function * @param {Object} language definition * @constructor */ var ToText = /** @class */ (function () { function ToText(rrule, gettext, language, dateFormatter) { if (gettext === void 0) { gettext = defaultGetText; } if (language === void 0) { language = i18n; } if (dateFormatter === void 0) { dateFormatter = defaultDateFormatter; } this.text = []; this.language = language || i18n; this.gettext = gettext; this.dateFormatter = dateFormatter; this.rrule = rrule; this.options = rrule.options; this.origOptions = rrule.origOptions; if (this.origOptions.bymonthday) { var bymonthday = [].concat(this.options.bymonthday); var bynmonthday = [].concat(this.options.bynmonthday); bymonthday.sort(function (a, b) { return a - b; }); bynmonthday.sort(function (a, b) { return b - a; }); // 1, 2, 3, .., -5, -4, -3, .. this.bymonthday = bymonthday.concat(bynmonthday); if (!this.bymonthday.length) this.bymonthday = null; } if (isPresent(this.origOptions.byweekday)) { var byweekday = !isArray(this.origOptions.byweekday) ? [this.origOptions.byweekday] : this.origOptions.byweekday; var days = String(byweekday); this.byweekday = { allWeeks: byweekday.filter(function (weekday) { return !weekday.n; }), someWeeks: byweekday.filter(function (weekday) { return Boolean(weekday.n); }), isWeekdays: days.indexOf('MO') !== -1 && days.indexOf('TU') !== -1 && days.indexOf('WE') !== -1 && days.indexOf('TH') !== -1 && days.indexOf('FR') !== -1 && days.indexOf('SA') === -1 && days.indexOf('SU') === -1, isEveryDay: days.indexOf('MO') !== -1 && days.indexOf('TU') !== -1 && days.indexOf('WE') !== -1 && days.indexOf('TH') !== -1 && days.indexOf('FR') !== -1 && days.indexOf('SA') !== -1 && days.indexOf('SU') !== -1, }; var sortWeekDays = function (a, b) { return a.weekday - b.weekday; }; this.byweekday.allWeeks.sort(sortWeekDays); this.byweekday.someWeeks.sort(sortWeekDays); if (!this.byweekday.allWeeks.length) this.byweekday.allWeeks = null; if (!this.byweekday.someWeeks.length) this.byweekday.someWeeks = null; } else { this.byweekday = null; } } /** * Test whether the rrule can be fully converted to text. * * @param {RRule} rrule * @return {Boolean} */ ToText.isFullyConvertible = function (rrule) { var canConvert = true; if (!(rrule.options.freq in ToText.IMPLEMENTED)) return false; if (rrule.origOptions.until && rrule.origOptions.count) return false; for (var key in rrule.origOptions) { if (contains(['dtstart', 'tzid', 'wkst', 'freq'], key)) return true; if (!contains(ToText.IMPLEMENTED[rrule.options.freq], key)) return false; } return canConvert; }; ToText.prototype.isFullyConvertible = function () { return ToText.isFullyConvertible(this.rrule); }; /** * Perform the conversion. Only some of the frequencies are supported. * If some of the rrule's options aren't supported, they'll * be omitted from the output an "(~ approximate)" will be appended. * * @return {*} */ ToText.prototype.toString = function () { var gettext = this.gettext; if (!(this.options.freq in ToText.IMPLEMENTED)) { return gettext('RRule error: Unable to fully convert this rrule to text'); } this.text = [gettext('every')]; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore this[RRule.FREQUENCIES[this.options.freq]](); if (this.options.until) { this.add(gettext('until')); var until = this.options.until; this.add(this.dateFormatter(until.getUTCFullYear(), this.language.monthNames[until.getUTCMonth()], until.getUTCDate())); } else if (this.options.count) { this.add(gettext('for')) .add(this.options.count.toString()) .add(this.plural(this.options.count) ? gettext('times') : gettext('time')); } if (!this.isFullyConvertible()) this.add(gettext('(~ approximate)')); return this.text.join(''); }; ToText.prototype.HOURLY = function () { var gettext = this.gettext; if (this.options.interval !== 1) this.add(this.options.interval.toString()); this.add(this.plural(this.options.interval) ? gettext('hours') : gettext('hour')); }; ToText.prototype.MINUTELY = function () { var gettext = this.gettext; if (this.options.interval !== 1) this.add(this.options.interval.toString()); this.add(this.plural(this.options.interval) ? gettext('minutes') : gettext('minute')); }; ToText.prototype.DAILY = function () { var gettext = this.gettext; if (this.options.interval !== 1) this.add(this.options.interval.toString()); if (this.byweekday && this.byweekday.isWeekdays) { this.add(this.plural(this.options.interval) ? gettext('weekdays') : gettext('weekday')); } else { this.add(this.plural(this.options.interval) ? gettext('days') : gettext('day')); } if (this.origOptions.bymonth) { this.add(gettext('in')); this._bymonth(); } if (this.bymonthday) { this._bymonthday(); } else if (this.byweekday) { this._byweekday(); } else if (this.origOptions.byhour) { this._byhour(); } }; ToText.prototype.WEEKLY = function () { var gettext = this.gettext; if (this.options.interval !== 1) { this.add(this.options.interval.toString()).add(this.plural(this.options.interval) ? gettext('weeks') : gettext('week')); } if (this.byweekday && this.byweekday.isWeekdays) { if (this.options.interval === 1) { this.add(this.plural(this.options.interval) ? gettext('weekdays') : gettext('weekday')); } else { this.add(gettext('on')).add(gettext('weekdays')); } } else if (this.byweekday && this.byweekday.isEveryDay) { this.add(this.plural(this.options.interval) ? gettext('days') : gettext('day')); } else { if (this.options.interval === 1) this.add(gettext('week')); if (this.origOptions.bymonth) { this.add(gettext('in')); this._bymonth(); } if (this.bymonthday) { this._bymonthday(); } else if (this.byweekday) { this._byweekday(); } if (this.origOptions.byhour) { this._byhour(); } } }; ToText.prototype.MONTHLY = function () { var gettext = this.gettext; if (this.origOptions.bymonth) { if (this.options.interval !== 1) { this.add(this.options.interval.toString()).add(gettext('months')); if (this.plural(this.options.interval)) this.add(gettext('in')); } else { // this.add(gettext('MONTH')) } this._bymonth(); } else { if (this.options.interval !== 1) { this.add(this.options.interval.toString()); } this.add(this.plural(this.options.interval) ? gettext('months') : gettext('month')); } if (this.bymonthday) { this._bymonthday(); } else if (this.byweekday && this.byweekday.isWeekdays) { this.add(gettext('on')).add(gettext('weekdays')); } else if (this.byweekday) { this._byweekday(); } }; ToText.prototype.YEARLY = function () { var gettext = this.gettext; if (this.origOptions.bymonth) { if (this.options.interval !== 1) { this.add(this.options.interval.toString()); this.add(gettext('years')); } else { // this.add(gettext('YEAR')) } this._bymonth(); } else { if (this.options.interval !== 1) { this.add(this.options.interval.toString()); } this.add(this.plural(this.options.interval) ? gettext('years') : gettext('year')); } if (this.bymonthday) { this._bymonthday(); } else if (this.byweekday) { this._byweekday(); } if (this.options.byyearday) { this.add(gettext('on the')) .add(this.list(this.options.byyearday, this.nth, gettext('and'))) .add(gettext('day')); } if (this.options.byweekno) { this.add(gettext('in')) .add(this.plural(this.options.byweekno.length) ? gettext('weeks') : gettext('week')) .add(this.list(this.options.byweekno, undefined, gettext('and'))); } }; ToText.prototype._bymonthday = function () { var gettext = this.gettext; if (this.byweekday && this.byweekday.allWeeks) { this.add(gettext('on')) .add(this.list(this.byweekday.allWeeks, this.weekdaytext, gettext('or'))) .add(gettext('the')) .add(this.list(this.bymonthday, this.nth, gettext('or'))); } else { this.add(gettext('on the')).add(this.list(this.bymonthday, this.nth, gettext('and'))); } // this.add(gettext('DAY')) }; ToText.prototype._byweekday = function () { var gettext = this.gettext; if (this.byweekday.allWeeks && !this.byweekday.isWeekdays) { this.add(gettext('on')).add(this.list(this.byweekday.allWeeks, this.weekdaytext)); } if (this.byweekday.someWeeks) { if (this.byweekday.allWeeks) this.add(gettext('and')); this.add(gettext('on the')).add(this.list(this.byweekday.someWeeks, this.weekdaytext, gettext('and'))); } }; ToText.prototype._byhour = function () { var gettext = this.gettext; this.add(gettext('at')).add(this.list(this.origOptions.byhour, undefined, gettext('and'))); }; ToText.prototype._bymonth = function () { this.add(this.list(this.options.bymonth, this.monthtext, this.gettext('and'))); }; ToText.prototype.nth = function (n) { n = parseInt(n.toString(), 10); var nth; var gettext = this.gettext; if (n === -1) return gettext('last'); var npos = Math.abs(n); switch (npos) { case 1: case 21: case 31: nth = npos + gettext('st'); break; case 2: case 22: nth = npos + gettext('nd'); break; case 3: case 23: nth = npos + gettext('rd'); break; default: nth = npos + gettext('th'); } return n < 0 ? nth + ' ' + gettext('last') : nth; }; ToText.prototype.monthtext = function (m) { return this.language.monthNames[m - 1]; }; ToText.prototype.weekdaytext = function (wday) { var weekday = isNumber(wday) ? (wday + 1) % 7 : wday.getJsWeekday(); return ((wday.n ? this.nth(wday.n) + ' ' : '') + this.language.dayNames[weekday]); }; ToText.prototype.plural = function (n) { return n % 100 !== 1; }; ToText.prototype.add = function (s) { this.text.push(' '); this.text.push(s); return this; }; ToText.prototype.list = function (arr, callback, finalDelim, delim) { var _this = this; if (delim === void 0) { delim = ','; } if (!isArray(arr)) { arr = [arr]; } var delimJoin = function (array, delimiter, finalDelimiter) { var list = ''; for (var i = 0; i < array.length; i++) { if (i !== 0) { if (i === array.length - 1) { list += ' ' + finalDelimiter + ' '; } else { list += delimiter + ' '; } } list += array[i]; } return list; }; callback = callback || function (o) { return o.toString(); }; var realCallback = function (arg) { return callback && callback.call(_this, arg); }; if (finalDelim) { return delimJoin(arr.map(realCallback), delim, finalDelim); } else { return arr.map(realCallback).join(delim + ' '); } }; return ToText; }()); /* harmony default export */ const totext = (ToText); ;// CONCATENATED MODULE: ./src/nlp/parsetext.ts // ============================================================================= // Parser // ============================================================================= var Parser = /** @class */ (function () { function Parser(rules) { this.done = true; this.rules = rules; } Parser.prototype.start = function (text) { this.text = text; this.done = false; return this.nextSymbol(); }; Parser.prototype.isDone = function () { return this.done && this.symbol === null; }; Parser.prototype.nextSymbol = function () { var best; var bestSymbol; this.symbol = null; this.value = null; do { if (this.done) return false; var rule = void 0; best = null; for (var name_1 in this.rules) { rule = this.rules[name_1]; var match = rule.exec(this.text); if (match) { if (best === null || match[0].length > best[0].length) { best = match; bestSymbol = name_1; } } } if (best != null) { this.text = this.text.substr(best[0].length); if (this.text === '') this.done = true; } if (best == null) { this.done = true; this.symbol = null; this.value = null; return; } } while (bestSymbol === 'SKIP'); this.symbol = bestSymbol; this.value = best; return true; }; Parser.prototype.accept = function (name) { if (this.symbol === name) { if (this.value) { var v = this.value; this.nextSymbol(); return v; } this.nextSymbol(); return true; } return false; }; Parser.prototype.acceptNumber = function () { return this.accept('number'); }; Parser.prototype.expect = function (name) { if (this.accept(name)) return true; throw new Error('expected ' + name + ' but found ' + this.symbol); }; return Parser; }()); function parseText(text, language) { if (language === void 0) { language = i18n; } var options = {}; var ttr = new Parser(language.tokens); if (!ttr.start(text)) return null; S(); return options; function S() { // every [n] ttr.expect('every'); var n = ttr.acceptNumber(); if (n) options.interval = parseInt(n[0], 10); if (ttr.isDone()) throw new Error('Unexpected end'); switch (ttr.symbol) { case 'day(s)': options.freq = RRule.DAILY; if (ttr.nextSymbol()) { AT(); F(); } break; // FIXME Note: every 2 weekdays != every two weeks on weekdays. // DAILY on weekdays is not a valid rule case 'weekday(s)': options.freq = RRule.WEEKLY; options.byweekday = [RRule.MO, RRule.TU, RRule.WE, RRule.TH, RRule.FR]; ttr.nextSymbol(); AT(); F(); break; case 'week(s)': options.freq = RRule.WEEKLY; if (ttr.nextSymbol()) { ON(); AT(); F(); } break; case 'hour(s)': options.freq = RRule.HOURLY; if (ttr.nextSymbol()) { ON(); F(); } break; case 'minute(s)': options.freq = RRule.MINUTELY; if (ttr.nextSymbol()) { ON(); F(); } break; case 'month(s)': options.freq = RRule.MONTHLY; if (ttr.nextSymbol()) { ON(); F(); } break; case 'year(s)': options.freq = RRule.YEARLY; if (ttr.nextSymbol()) { ON(); F(); } break; case 'monday': case 'tuesday': case 'wednesday': case 'thursday': case 'friday': case 'saturday': case 'sunday': options.freq = RRule.WEEKLY; var key = ttr.symbol .substr(0, 2) .toUpperCase(); options.byweekday = [RRule[key]]; if (!ttr.nextSymbol()) return;