跳转到内容

MediaWiki:Gadget-libCachedCode.js:修订间差异

来自萌娘共享
代码变动:103d1a56 - feat: rename (#594) by U:AnnAngela, co-authored-by: GH:github-actions[bot]
标签由机器人或全自动脚本执行的操作
代码变动:103d1a56 - feat: rename (#594) by U:AnnAngela, co-authored-by: GH:github-actions[bot]
标签由机器人或全自动脚本执行的操作
第9行: 第9行:


"use strict";
"use strict";
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
(() => {
    try {
     const localObjectStorage = new LocalObjectStorage("AnnTools-libCachedCode");
        var info = gen[key](arg);
     for (const i of Object.keys(localStorage)) {
        var value = info.value;
        if (i.startsWith("AnnTools-libCachedCode")) {
    } catch (error) {
            localStorage.removeItem(i);
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
function _ts_generator(thisArg, body) {
    var f, y, t, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["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(g && (g = 0, op[0] && (_ = 0)), _)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
        };
     }
}
(function() {
    var localObjectStorage = new LocalObjectStorage("AnnTools-libCachedCode");
     var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = Object.keys(localStorage)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var i = _step.value;
            if (i.startsWith("AnnTools-libCachedCode")) {
                localStorage.removeItem(i);
            }
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
         }
         }
     }
     }
     var codeToUrl = function(code) {
     const codeToUrl = (code) => {
         var blob = new Blob([
         const blob = new Blob([code], { type: "text/plain" });
            code
        ], {
            type: "text/plain"
        });
         return URL.createObjectURL(blob);
         return URL.createObjectURL(blob);
     };
     };
     var getCachedCode = function(url) {
     const getCachedCode = async (url) => {
         return _async_to_generator(function() {
         let { code } = localObjectStorage.getItem(`${url}`) || {};
            var code;
        if (!code) {
            return _ts_generator(this, function(_state) {
            code = await (await fetch(url)).text();
                switch(_state.label){
        }
                    case 0:
        localObjectStorage.setItem(`AnnTools-libCachedCode:${url}`, { code, timestamp: Date.now() });
                        code = (localObjectStorage.getItem("".concat(url)) || {}).code; // 读取缓存
        return code;
                        if (!!code) return [
                            3,
                            3
                        ];
                        return [
                            4,
                            fetch(url)
                        ];
                    case 1:
                        return [
                            4,
                            _state.sent().text()
                        ];
                    case 2:
                        code = _state.sent();
                        _state.label = 3;
                    case 3:
                        localObjectStorage.setItem("AnnTools-libCachedCode:".concat(url), {
                            code: code,
                            timestamp: Date.now()
                        }); // 设置缓存
                        return [
                            2,
                            code
                        ];
                }
            });
        })();
     };
     };
     var getCachedCodeUrl = function(url) {
     const getCachedCodeUrl = async (url) => codeToUrl(await getCachedCode(url));
         return _async_to_generator(function() {
    const injectCachedCode = async (url, _type) => {
            return _ts_generator(this, function(_state) {
         const type = _type.toLowerCase();
                switch(_state.label){
        if (["script", "javascript", "js"].includes(type)) {
                    case 0:
            const script = document.createElement("script");
                        return [
            script.src = await getCachedCodeUrl(url);
                            4,
            return await new Promise((res) => {
                            getCachedCode(url)
                script.addEventListener("load", () => {
                        ];
                    res();
                    case 1:
                });
                        return [
                 document.head.append(script);
                            2,
                            codeToUrl.apply(void 0, [
                                _state.sent()
                            ])
                        ];
                 }
             });
             });
         })();
         }
        if (["css", "style"].includes(type)) {
            mw.loader.addStyleTag(await getCachedCode(url));
            return;
        }
     };
     };
     var injectCachedCode = function(url, _type) {
     const batchInjectCachedCode = (urls, type) => Promise.all(urls.map((url) => injectCachedCode(url, type)));
        return _async_to_generator(function() {
     const expired = Date.now() - 30 * 24 * 60 * 60 * 1000;
            var type, script, _, _1;
     for (const k of localObjectStorage.getAllKeys()) {
            return _ts_generator(this, function(_state) {
        if (localObjectStorage.getItem(k).timestamp < expired) {
                switch(_state.label){
            localObjectStorage.removeItem(k);
                    case 0:
                        type = _type.toLowerCase();
                        if (![
                            "script",
                            "javascript",
                            "js"
                        ].includes(type)) return [
                            3,
                            3
                        ];
                        script = document.createElement("script");
                        return [
                            4,
                            getCachedCodeUrl(url)
                        ];
                    case 1:
                        script.src = _state.sent();
                        return [
                            4,
                            new Promise(function(res) {
                                script.addEventListener("load", function() {
                                    res();
                                });
                                document.head.append(script);
                            })
                        ];
                    case 2:
                        return [
                            2,
                            _state.sent()
                        ];
                    case 3:
                        if (![
                            "css",
                            "style"
                        ].includes(type)) return [
                            3,
                            5
                        ];
                        _1 = (_ = mw.loader).addStyleTag;
                        return [
                            4,
                            getCachedCode(url)
                        ];
                    case 4:
                        _1.apply(_, [
                            _state.sent()
                        ]);
                        return [
                            2
                        ];
                    case 5:
                        return [
                            2
                        ];
                }
            });
        })();
    };
    var batchInjectCachedCode = function(urls, type) {
        return Promise.all(urls.map(function(url) {
            return injectCachedCode(url, type);
        }));
     };
    // 移除过期缓存(30 天内无使用)
    var expired = Date.now() - 30 * 24 * 60 * 60 * 1000;
     var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
    try {
        for(var _iterator1 = localObjectStorage.getAllKeys()[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
            var k = _step1.value;
            if (localObjectStorage.getItem(k).timestamp < expired) {
                localObjectStorage.removeItem(k);
            }
        }
    } catch (err) {
        _didIteratorError1 = true;
        _iteratorError1 = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
                _iterator1.return();
            }
        } finally{
            if (_didIteratorError1) {
                throw _iteratorError1;
            }
         }
         }
     }
     }
     window.libCachedCode = {
     window.libCachedCode = {
         getCachedCode: getCachedCode,
         getCachedCode,
         getCachedCodeUrl: getCachedCodeUrl,
         getCachedCodeUrl,
         injectCachedCode: injectCachedCode,
         injectCachedCode,
         batchInjectCachedCode: batchInjectCachedCode
         batchInjectCachedCode,
     };
     };
})();  
})();  


/* </pre> */
/* </pre> */

2025年7月24日 (四) 20:54的版本

/**
 * -------------------------------------------------------------------------
 * !!! DON'T MODIFY THIS PAGE MANUALLY, YOUR CHANGES WILL BE OVERWRITTEN !!!
 * -------------------------------------------------------------------------
 */
var _addText = '{{GHIACode|page=GHIA:MoegirlPediaInterfaceCodes/blob/master/src/gadgets/libCachedCode/Gadget-libCachedCode.js|user=[[U:AnnAngela]]|co-authors=GH:github-actions[bot]|longId=103d1a563ea4ccc8ff29fb55c9bcd88329a56eb5|shortId=103d1a56|summary=feat: rename (#594)|body=<nowiki>Co-authored-by: github-actions[bot] <41898282+github-actions[bot]📧users.noreply.github.com></nowiki>}}'; 

/* <pre> */

"use strict";
(() => {
    const localObjectStorage = new LocalObjectStorage("AnnTools-libCachedCode");
    for (const i of Object.keys(localStorage)) {
        if (i.startsWith("AnnTools-libCachedCode")) {
            localStorage.removeItem(i);
        }
    }
    const codeToUrl = (code) => {
        const blob = new Blob([code], { type: "text/plain" });
        return URL.createObjectURL(blob);
    };
    const getCachedCode = async (url) => {
        let { code } = localObjectStorage.getItem(`${url}`) || {};
        if (!code) {
            code = await (await fetch(url)).text();
        }
        localObjectStorage.setItem(`AnnTools-libCachedCode:${url}`, { code, timestamp: Date.now() });
        return code;
    };
    const getCachedCodeUrl = async (url) => codeToUrl(await getCachedCode(url));
    const injectCachedCode = async (url, _type) => {
        const type = _type.toLowerCase();
        if (["script", "javascript", "js"].includes(type)) {
            const script = document.createElement("script");
            script.src = await getCachedCodeUrl(url);
            return await new Promise((res) => {
                script.addEventListener("load", () => {
                    res();
                });
                document.head.append(script);
            });
        }
        if (["css", "style"].includes(type)) {
            mw.loader.addStyleTag(await getCachedCode(url));
            return;
        }
    };
    const batchInjectCachedCode = (urls, type) => Promise.all(urls.map((url) => injectCachedCode(url, type)));
    const expired = Date.now() - 30 * 24 * 60 * 60 * 1000;
    for (const k of localObjectStorage.getAllKeys()) {
        if (localObjectStorage.getItem(k).timestamp < expired) {
            localObjectStorage.removeItem(k);
        }
    }
    window.libCachedCode = {
        getCachedCode,
        getCachedCodeUrl,
        injectCachedCode,
        batchInjectCachedCode,
    };
})(); 

/* </pre> */