MediaWiki:Gadget-cron.js

MediaWiki界面页面
一位史蒂夫讨论 | 贡献2024年1月2日 (二) 23:28的版本
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的变更的影响。

  • Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5Ctrl-R(Mac为⌘-R
  • Google Chrome:Ctrl-Shift-R(Mac为⌘-Shift-R
  • Internet Explorer或Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5
  • Opera:Ctrl-F5
"use strict";
var require = function () { return window.luxon; };
(function () {
    var createModuleFactory = function createModuleFactory(t) { var e; return function (r) { return e || t(e = { exports: {}, parent: r }, e.exports), e.exports; }; };
    var _$CronJob_3 = createModuleFactory(function (module, exports) {
        function CronJob(CronTime, spawn) {
            function fnWrap(cmd) {
                var command;
                var args;
                switch (typeof cmd) {
                    case 'string':
                        args = cmd.split(' ');
                        command = args.shift();
                        return spawn.bind(undefined, command, args);
                    case 'object':
                        command = cmd && cmd.command;
                        if (command) {
                            args = cmd.args;
                            var options = cmd.options;
                            return spawn.bind(undefined, command, args, options);
                        }
                        break;
                }
                return cmd;
            }
            function CJ(cronTime, onTick, onComplete, startNow, timeZone, context, runOnInit, utcOffset, unrefTimeout) {
                var _cronTime = cronTime;
                var argCount = 0;
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] !== undefined) {
                        argCount++;
                    }
                }
                if (typeof cronTime !== 'string' && argCount === 1) {
                    onTick = cronTime.onTick;
                    onComplete = cronTime.onComplete;
                    context = cronTime.context;
                    startNow = cronTime.start || cronTime.startNow || cronTime.startJob;
                    timeZone = cronTime.timeZone;
                    runOnInit = cronTime.runOnInit;
                    _cronTime = cronTime.cronTime;
                    utcOffset = cronTime.utcOffset;
                    unrefTimeout = cronTime.unrefTimeout;
                }
                this.context = context || this;
                this._callbacks = [];
                this.onComplete = fnWrap(onComplete);
                this.cronTime = new CronTime(_cronTime, timeZone, utcOffset);
                this.unrefTimeout = unrefTimeout;
                addCallback.call(this, fnWrap(onTick));
                if (runOnInit) {
                    this.lastExecution = new Date();
                    fireOnTick.call(this);
                }
                if (startNow) {
                    start.call(this);
                }
                return this;
            }
            var addCallback = function (callback) {
                if (typeof callback === 'function') {
                    this._callbacks.push(callback);
                }
            };
            CJ.prototype.addCallback = addCallback;
            CJ.prototype.setTime = function (time) {
                if (typeof time !== 'object') {
                    throw new Error('time must be an instance of CronTime.');
                }
                this.stop();
                this.cronTime = time;
                this.start();
            };
            CJ.prototype.nextDate = function () {
                return this.cronTime.sendAt();
            };
            var fireOnTick = function () {
                for (var i = this._callbacks.length - 1; i >= 0; i--) {
                    this._callbacks[i].call(this.context, this.onComplete);
                }
            };
            CJ.prototype.fireOnTick = fireOnTick;
            CJ.prototype.nextDates = function (i) {
                return this.cronTime.sendAt(i);
            };
            var start = function () {
                if (this.running) {
                    return;
                }
                var MAXDELAY = 2147483647;
                var self = this;
                var timeout = this.cronTime.getTimeout();
                var remaining = 0;
                var startTime;
                if (this.cronTime.realDate) {
                    this.runOnce = true;
                }
                function _setTimeout(timeout) {
                    startTime = Date.now();
                    self._timeout = setTimeout(callbackWrapper, timeout);
                    if (self.unrefTimeout && typeof self._timeout.unref === 'function') {
                        self._timeout.unref();
                    }
                }
                function callbackWrapper() {
                    var diff = startTime + timeout - Date.now();
                    if (diff > 0) {
                        var newTimeout = self.cronTime.getTimeout();
                        if (newTimeout > diff) {
                            newTimeout = diff;
                        }
                        remaining += newTimeout;
                    }
                    self.lastExecution = new Date();
                    if (remaining) {
                        if (remaining > MAXDELAY) {
                            remaining -= MAXDELAY;
                            timeout = MAXDELAY;
                        }
                        else {
                            timeout = remaining;
                            remaining = 0;
                        }
                        _setTimeout(timeout);
                    }
                    else {
                        self.running = false;
                        if (!self.runOnce) {
                            self.start();
                        }
                        self.fireOnTick();
                    }
                }
                if (timeout >= 0) {
                    this.running = true;
                    if (timeout > MAXDELAY) {
                        remaining = timeout - MAXDELAY;
                        timeout = MAXDELAY;
                    }
                    _setTimeout(timeout);
                }
                else {
                    this.stop();
                }
            };
            CJ.prototype.start = start;
            CJ.prototype.lastDate = function () {
                return this.lastExecution;
            };
            CJ.prototype.stop = function () {
                if (this._timeout)
                    clearTimeout(this._timeout);
                this.running = false;
                if (typeof this.onComplete === 'function') {
                    this.onComplete();
                }
            };
            return CJ;
        }
        module.exports = CronJob;
    });
    var _$CronTime_4 = createModuleFactory(function (module, exports) {
        var CONSTRAINTS = [
            [0, 59],
            [0, 59],
            [0, 23],
            [1, 31],
            [0, 11],
            [0, 6]
        ];
        var MONTH_CONSTRAINTS = [
            31,
            29,
            31,
            30,
            31,
            30,
            31,
            31,
            30,
            31,
            30,
            31
        ];
        var PARSE_DEFAULTS = ['0', '*', '*', '*', '*', '*'];
        var ALIASES = {
            jan: 0,
            feb: 1,
            mar: 2,
            apr: 3,
            may: 4,
            jun: 5,
            jul: 6,
            aug: 7,
            sep: 8,
            oct: 9,
            nov: 10,
            dec: 11,
            sun: 0,
            mon: 1,
            tue: 2,
            wed: 3,
            thu: 4,
            fri: 5,
            sat: 6
        };
        var TIME_UNITS = [
            'second',
            'minute',
            'hour',
            'dayOfMonth',
            'month',
            'dayOfWeek'
        ];
        var TIME_UNITS_LEN = TIME_UNITS.length;
        var PRESETS = {
            '@yearly': '0 0 0 1 0 *',
            '@monthly': '0 0 0 1 * *',
            '@weekly': '0 0 0 * * 0',
            '@daily': '0 0 0 * * *',
            '@hourly': '0 0 * * * *',
            '@minutely': '0 * * * * *',
            '@secondly': '* * * * * *',
            '@weekdays': '0 0 0 * * 1-5',
            '@weekends': '0 0 0 * * 0,6'
        };
        var RE_WILDCARDS = /\*/g;
        var RE_RANGE = /^(\d+)(?:-(\d+))?(?:\/(\d+))?$/g;
        function CronTime(luxon) {
            function CT(source, zone, utcOffset) {
                this.source = source;
                if (zone) {
                    var dt = luxon.DateTime.fromObject({ zone: zone });
                    if (dt.invalid) {
                        throw new Error('Invalid timezone.');
                    }
                    this.zone = zone;
                }
                if (typeof utcOffset !== 'undefined') {
                    this.utcOffset = utcOffset;
                }
                var that = this;
                TIME_UNITS.map(function (timeUnit) {
                    that[timeUnit] = {};
                });
                if (this.source instanceof Date || this.source instanceof luxon.DateTime) {
                    if (this.source instanceof Date) {
                        this.source = luxon.DateTime.fromJSDate(this.source);
                    }
                    this.realDate = true;
                }
                else {
                    this._parse(this.source);
                    this._verifyParse();
                }
            }
            CT.prototype = {
                _verifyParse: function () {
                    var months = Object.keys(this.month);
                    var dom = Object.keys(this.dayOfMonth);
                    var ok = false;
                    var lastWrongMonth = NaN;
                    for (var i = 0; i < months.length; i++) {
                        var m = months[i];
                        var con = MONTH_CONSTRAINTS[parseInt(m, 10)];
                        for (var j = 0; j < dom.length; j++) {
                            var day = dom[j];
                            if (day <= con) {
                                ok = true;
                            }
                        }
                        if (!ok) {
                            lastWrongMonth = m;
                            console.warn("Month '".concat(m, "' is limited to '").concat(con, "' days."));
                        }
                    }
                    if (!ok) {
                        var notOkCon = MONTH_CONSTRAINTS[parseInt(lastWrongMonth, 10)];
                        for (var k = 0; k < dom.length; k++) {
                            var notOkDay = dom[k];
                            if (notOkDay > notOkCon) {
                                delete this.dayOfMonth[notOkDay];
                                var fixedDay = Number(notOkDay) % notOkCon;
                                this.dayOfMonth[fixedDay] = true;
                            }
                        }
                    }
                },
                sendAt: function (i) {
                    var date = this.realDate ? this.source : luxon.DateTime.local();
                    if (this.zone) {
                        date = date.setZone(this.zone);
                    }
                    if (typeof this.utcOffset !== 'undefined') {
                        var offset = this.utcOffset >= 60 || this.utcOffset <= -60
                            ? this.utcOffset / 60
                            : this.utcOffset;
                        offset = parseInt(offset);
                        var utcZone = 'UTC';
                        if (offset < 0) {
                            utcZone += offset;
                        }
                        else if (offset > 0) {
                            utcZone += "+".concat(offset);
                        }
                        date = date.setZone(utcZone);
                        if (date.invalid) {
                            throw new Error('ERROR: You specified an invalid UTC offset.');
                        }
                    }
                    if (this.realDate) {
                        if (luxon.DateTime.local() > date) {
                            throw new Error('WARNING: Date in past. Will never be fired.');
                        }
                        return date;
                    }
                    if (isNaN(i) || i < 0) {
                        return this._getNextDateFrom(date);
                    }
                    else {
                        var dates = [];
                        for (; i > 0; i--) {
                            date = this._getNextDateFrom(date);
                            dates.push(date);
                        }
                        return dates;
                    }
                },
                getTimeout: function () {
                    return Math.max(-1, this.sendAt() - luxon.DateTime.local());
                },
                toString: function () {
                    return this.toJSON().join(' ');
                },
                toJSON: function () {
                    var self = this;
                    return TIME_UNITS.map(function (timeName) {
                        return self._wcOrAll(timeName);
                    });
                },
                _getNextDateFrom: function (start, zone) {
                    if (start instanceof Date) {
                        start = luxon.DateTime.fromJSDate(start);
                    }
                    var date = start;
                    var firstDate = start.toMillis();
                    if (zone) {
                        date = date.setZone(zone);
                    }
                    if (!this.realDate) {
                        if (date.millisecond > 0) {
                            date = date.set({ millisecond: 0, second: date.second + 1 });
                        }
                    }
                    if (date.invalid) {
                        throw new Error('ERROR: You specified an invalid date.');
                    }
                    var timeout = Date.now() + 5000;
                    while (true) {
                        var diff = date - start;
                        if (Date.now() > timeout) {
                            throw new Error("Something went wrong. It took over five seconds to find the next execution time for the cron job.\n\t\t\t\t\t\t\tPlease refer to the canonical issue (https://github.com/kelektiv/node-cron/issues/467) and provide the following string if you would like to help debug:\n\t\t\t\t\t\t\tTime Zone: ".concat(zone || '""', " - Cron String: ").concat(this, " - UTC offset: ").concat(date.format('Z'), " - current Date: ").concat(luxon.DateTime.local().toString()));
                        }
                        if (!(date.month - 1 in this.month) &&
                            Object.keys(this.month).length !== 12) {
                            date = date.plus({ months: 1 });
                            date = date.set({ day: 1, hour: 0, minute: 0, second: 0 });
                            continue;
                        }
                        if (!(date.day in this.dayOfMonth) &&
                            Object.keys(this.dayOfMonth).length !== 31 &&
                            !(date.getWeekDay() in this.dayOfWeek &&
                                Object.keys(this.dayOfWeek).length !== 7)) {
                            date = date.plus({ days: 1 });
                            date = date.set({ hour: 0, minute: 0, second: 0 });
                            continue;
                        }
                        if (!(date.getWeekDay() in this.dayOfWeek) &&
                            Object.keys(this.dayOfWeek).length !== 7 &&
                            !(date.day in this.dayOfMonth &&
                                Object.keys(this.dayOfMonth).length !== 31)) {
                            date = date.plus({ days: 1 });
                            date = date.set({ hour: 0, minute: 0, second: 0 });
                            continue;
                        }
                        if (!(date.hour in this.hour) && Object.keys(this.hour).length !== 24) {
                            date = date.set({
                                hour: date.hour === 23 && diff > 86400000 ? 0 : date.hour + 1
                            });
                            date = date.set({ minute: 0, second: 0 });
                            continue;
                        }
                        if (!(date.minute in this.minute) &&
                            Object.keys(this.minute).length !== 60) {
                            date = date.set({
                                minute: date.minute === 59 && diff > 3600000 ? 0 : date.minute + 1
                            });
                            date = date.set({ second: 0 });
                            continue;
                        }
                        if (!(date.second in this.second) &&
                            Object.keys(this.second).length !== 60) {
                            date = date.set({
                                second: date.second === 59 && diff > 60000 ? 0 : date.second + 1
                            });
                            continue;
                        }
                        if (date.toMillis() === firstDate) {
                            date = date.set({ second: date.second + 1 });
                            continue;
                        }
                        break;
                    }
                    return date;
                },
                _wcOrAll: function (type) {
                    if (this._hasAll(type)) {
                        return '*';
                    }
                    var all = [];
                    for (var time in this[type]) {
                        all.push(time);
                    }
                    return all.join(',');
                },
                _hasAll: function (type) {
                    var constraints = CONSTRAINTS[TIME_UNITS.indexOf(type)];
                    for (var i = constraints[0], n = constraints[1]; i < n; i++) {
                        if (!(i in this[type])) {
                            return false;
                        }
                    }
                    return true;
                },
                _parse: function (source) {
                    source = source.toLowerCase();
                    if (source in PRESETS) {
                        source = PRESETS[source];
                    }
                    source = source.replace(/[a-z]{1,3}/gi, function (alias) {
                        if (alias in ALIASES) {
                            return ALIASES[alias];
                        }
                        throw new Error("Unknown alias: ".concat(alias));
                    });
                    var units = source.trim().split(/\s+/);
                    if (units.length < TIME_UNITS_LEN - 1) {
                        throw new Error('Too few fields');
                    }
                    if (units.length > TIME_UNITS_LEN) {
                        throw new Error('Too many fields');
                    }
                    var unitsLen = units.length;
                    for (var i = 0; i < TIME_UNITS_LEN; i++) {
                        var cur = units[i - (TIME_UNITS_LEN - unitsLen)] || PARSE_DEFAULTS[i];
                        this._parseField(cur, TIME_UNITS[i], CONSTRAINTS[i]);
                    }
                },
                _parseField: function (value, type, constraints) {
                    var typeObj = this[type];
                    var pointer;
                    var low = constraints[0];
                    var high = constraints[1];
                    var fields = value.split(',');
                    fields.forEach(function (field) {
                        var wildcardIndex = field.indexOf('*');
                        if (wildcardIndex !== -1 && wildcardIndex !== 0) {
                            throw new Error("Field (".concat(field, ") has an invalid wildcard expression"));
                        }
                    });
                    value = value.replace(RE_WILDCARDS, "".concat(low, "-").concat(high));
                    var allRanges = value.split(',');
                    for (var i = 0; i < allRanges.length; i++) {
                        if (allRanges[i].match(RE_RANGE)) {
                            allRanges[i].replace(RE_RANGE, function ($0, lower, upper, step) {
                                lower = parseInt(lower, 10);
                                upper = parseInt(upper, 10) || undefined;
                                var wasStepDefined = !isNaN(parseInt(step, 10));
                                if (step === '0') {
                                    throw new Error("Field (".concat(type, ") has a step of zero"));
                                }
                                step = parseInt(step, 10) || 1;
                                if (upper && lower > upper) {
                                    throw new Error("Field (".concat(type, ") has an invalid range"));
                                }
                                var outOfRangeError = lower < low ||
                                    (upper && upper > high) ||
                                    (!upper && lower > high);
                                if (outOfRangeError) {
                                    throw new Error("Field value (".concat(value, ") is out of range"));
                                }
                                lower = Math.min(Math.max(low, ~~Math.abs(lower)), high);
                                if (upper) {
                                    upper = Math.min(high, ~~Math.abs(upper));
                                }
                                else {
                                    upper = wasStepDefined ? high : lower;
                                }
                                pointer = lower;
                                do {
                                    typeObj[pointer] = true;
                                    pointer += step;
                                } while (pointer <= upper);
                            });
                        }
                        else {
                            throw new Error("Field (".concat(type, ") cannot be parsed"));
                        }
                    }
                }
            };
            return CT;
        }
        module.exports = CronTime;
    });
    var _$_empty_1 = createModuleFactory(function (module, exports) {
    });
    var _$cron_2 = {};
    (function (root, factory) {
        if (typeof define === 'function' && define.amd) {
            define(['luxon'], factory);
        }
        else if (typeof _$cron_2 === 'object') {
            _$cron_2 = factory(require(5), _$_empty_1({}));
        }
        else {
            root.Cron = factory(root.luxon);
        }
    })(this, function (luxon, childProcess) {
        var exports = {};
        var spawn = childProcess && childProcess.spawn;
        var CronTime = _$CronTime_4({})(luxon);
        var CronJob = _$CronJob_3({})(CronTime, spawn);
        luxon.DateTime.prototype.getWeekDay = function () {
            return this.weekday === 7 ? 0 : this.weekday;
        };
        exports.job = function (cronTime, onTick, onComplete, startNow, timeZone, context, runOnInit, utcOffset, unrefTimeout) {
            return new CronJob(cronTime, onTick, onComplete, startNow, timeZone, context, runOnInit, utcOffset, unrefTimeout);
        };
        exports.time = function (cronTime, timeZone) { return new CronTime(cronTime, timeZone); };
        exports.sendAt = function (cronTime) { return exports.time(cronTime).sendAt(); };
        exports.timeout = function (cronTime) { return exports.time(cronTime).getTimeout(); };
        exports.CronJob = CronJob;
        exports.CronTime = CronTime;
        return exports;
    });
    var _$input_6 = {};
    (function (global) {
        (function () {
            "use strict";
            var _cron = _interopRequireDefault(_$cron_2);
            function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
            global["Cron"] = _cron["default"];
        }).call(this);
    }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
}());