UNPKG

aws-cron-parser

Version:

A util to parse cron expressions used by AWS services

118 lines 3.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parse = void 0; var parseIntMinMax = function (str, min, max) { var num = parseInt(str, 10); if (num < min || num > max) throw new Error("Invalid: number " + num + " is not between " + min + " and " + max); return num; }; var parseOneRule = function (rule, min, max) { if (rule === '?') { return []; } if (rule === 'L') { return ['L', 0]; } if (rule.startsWith('L-')) { return ['L', parseIntMinMax(rule.substring(2), min, max)]; } if (rule.endsWith('L')) { return ['L', parseIntMinMax(rule.substring(0, rule.length - 1), min, max)]; } if (rule.endsWith('W')) { return ['W', parseIntMinMax(rule.substring(0, rule.length - 1), min, max)]; } if (rule.includes('#')) { return ['#', parseIntMinMax(rule.split('#')[0], min, max), parseIntMinMax(rule.split('#')[1], min, max)]; } var newRule; if (rule === '*') { newRule = min + "-" + max; } else if (rule.includes('/')) { var parts = rule.split('/'); var start = void 0, end = void 0; if (parts[0] === '*') { start = min; end = max; } else if (parts[0].includes('-')) { var splits = parts[0].split('-'); start = parseIntMinMax(splits[0], min, max); end = parseIntMinMax(splits[1], min, max); } else { start = parseIntMinMax(parts[0], min, max); end = max; } var increment = parseIntMinMax(parts[1], 1, max); newRule = ''; while (start <= end) { newRule += "," + start; start += increment; } newRule = newRule.substring(1); } else { newRule = rule; } var allows = []; newRule.split(',').forEach(function (s) { if (s.includes('-')) { var parts = s.split('-'); var start = parseIntMinMax(parts[0], min, max); var end = parseIntMinMax(parts[1], min, max); for (var i = start; i <= end; i += 1) allows.push(i); } else { allows.push(parseIntMinMax(s, min, max)); } }); return allows; }; var replace = function (s, rules) { var rs = s.toUpperCase(); rules.forEach(function (_a) { var from = _a[0], to = _a[1]; rs = rs.replace(from, to); }); return rs; }; var monthReplaces = [ ['JAN', '1'], ['FEB', '2'], ['MAR', '3'], ['APR', '4'], ['MAY', '5'], ['JUN', '6'], ['JUL', '7'], ['AUG', '8'], ['SEP', '9'], ['OCT', '10'], ['NOV', '11'], ['DEC', '12'], ]; var dayWeekReplaces = [ ['SUN', '1'], ['MON', '2'], ['TUE', '3'], ['WED', '4'], ['THU', '5'], ['FRI', '6'], ['SAT', '7'], ]; function parse(cron) { var rules = cron.split(' '); return { minutes: parseOneRule(rules[0], 0, 59), hours: parseOneRule(rules[1], 0, 23), daysOfMonth: parseOneRule(rules[2], 1, 31), months: parseOneRule(replace(rules[3], monthReplaces), 1, 12), daysOfWeek: parseOneRule(replace(rules[4], dayWeekReplaces), 1, 7), years: parseOneRule(rules[5], 1970, 2199), }; } exports.parse = parse; //# sourceMappingURL=parse.js.map