CF Workers实例
CF Workers实例
Last edited 2024-1-10
password
type
Post
status
Published
date
Aug 21, 2021
slug
summary
Cloudflare Workers
tags
cloudflare
category
技术分享
icon
CF-Worker-Dir是一款适用于Cloudflare Worker平台上的云函数程序,可以使用它在一分钟内搭建属于自己的导航页面。CF-Worker-Dir提供丰富的自定义配置,同时它还可以预留了接口帮助你售出自己域名。如果你的域名还没有搭建网站,不如先利用CF-Worker-Dir让你的域名不再浪费。
在绑定域名之后,选择Workers
notion image
选择Manage Workers
notion image
选择Create a Worker
在右侧能看到每天100000次的请求数量
notion image
选择{}Quick edit,进行编辑
 
notion image
将CF-Worker-Dir里的index.js复制粘贴至对应的config{},并修改成自己的信息
最后点击保存并发布。
notion image
你就拥有了属于自己的导航页。
notion image
ps:原作者还在持续更新!
addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) /** * Respond to the request * @param {Request} request */ async function handleRequest(request) { return new Response('hello world', {status: 200}) } /** * 自定义网站配置 */ const config = { title: "三生万物", //write your website title subtitle: "道生一,一生二,二生三", //write your website subtitle logo_icon: "sitemap", //select your logo by semantic-ui icon (you can get more msg in:https://semantic-ui.com/elements/icon.html) hitokoto: true, //use hitokoto or not search:true, //enable search function search_engine:[ //choose search engine which you use { name:"必 应", template:"https://cn.bing.com/search?q=$s" }, { name:"YANDEX", template:"https://yandex.com/search/?text=$s" }, { name:"谷 歌", template:"https://www.google.com/search?q=$s" }, { name:"百 度", template:"https://www.baidu.com/s?wd=$s" }, ], selling_ads: false, //Selling your domain or not.(turning on may be helpful for selling this domain by showing some ads.) sell_info:{ domain:"011223.xyz", price:1000, //domain price mon_unit:"yen sign", //monetary unit contact:[ { type:"phone", content:"+" },//how to contact you { type:"envelope", //contact type ("weixin","qq","telegram plane","envelope" or "phone") content:"gmail.com" } ] }, lists: [ //Url list { name:"技术", icon:"code", list:[ { url:"https://wiki.011223.xyz", name:"7秒记忆", desc:"GITHUB站点" }, { url:"https://zhong.011223.xyz", name:"东皇钟", desc:"NOTION" }, { url:"https://xyz.011223.xyz/", name:"知识库", desc:"主站" }, { url:"https://notion.011223.xyz", name:"知识库", desc:"备用" }, { url:"https://musicforprogramming.net/", name:"背景音乐", desc:"适合程序员的背景音乐" }, ] }, { name:"博客", icon:"BLOG", list:[ { url:"https://wzyboy.im", name:"wzyboy", desc:"wzyboy" }, { url:"https://blog.naaln.com", name:"Whyliam", desc:"人生若如初見" }, { url:"https://ednovas.xyz", name:"ednovas", desc:"ednovas" }, { url:"https://www.hongweipeng.com/", name:"栖迟於一丘", desc:"栖迟於一丘" }, { url:"https://gine.me/", name:"Mayne", desc:"Notion/Gatsby/Netlify" }, { url:"https://xiaolincoding.com", name:"小林", desc:"小林coding" }, { url:"https://iao.su", name:"不死鸟", desc:"分享为王" }, ] }, { name:"图库", icon:"graduation cap", list:[ { url:"https://www.backblaze.com", name:"B2", desc:"自建图库" }, { url:"https://imgchr.com", name:"路过图库", desc:"永不收费" }, { url:"https://sm.ms", name:"SM.MS", desc:"图库" }, { url:"https://www.instapaper.com/", name:"instapaper", desc:"FEED" }, { url:"https://portal.qiniu.com/signup?type=1", name:"qiniu", desc:"oss" }, { url:"https://unsplash.com/login", name:"unsplash", desc:"unsplash" }, { url:"http://www.52pojie.cn", name:"52pojie", desc:"52pojie" }, ] }, { name:"社区", icon:"graduation cap", list:[ { url:"https://www.msdmanuals.cn", name:"MSD诊疗手册", desc:"MSD诊疗手册" }, { url:"http://upwith.me/", name:"永澄老师", desc:"个人成长目标" }, { url:"https://www.phodal.com/", name:"Phodal", desc:"狼和凤凰" }, { url:"https://www.eslbuzz.com/", name:"1000+英语课程", desc:"FREE" }, { url:"https://segmentfault.com/", name:"思否社区", desc:"程序员集散地" }, { url:"https://jianshu.com/", name:"简书", desc:"程序员集散地" }, { url:"https://w3school.com.cn/", name:"W3school在线教程", desc:"程序员集散地" }, { url:"https://www.fakenamegenerator.com", name:"神奇的社工网站", desc:"自动身份" }, { url:"https://www.csdn.net", name:"csdn", desc:"csdn" }, { url:"http://www.51cto.com", name:"51CTO", desc:"51CTO" }, { url:"https://www.ituring.com.cn", name:"图灵社区", desc:"图灵社区" }, { url:"http://guanjianfeng.com/", name:"老管网络日志", desc:"虚拟化" }, { url:"https://www.c82.net/werner/#preface", name:"配色", desc:"配色" }, { url:"https://jianshu.com/", name:"简书", desc:"程序员集散地" }, ] }, { name:"七色花", icon:"graduation cap", list:[ { url:"https://ddrk.me/", name:"低端影视", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"https://www.qianoo.cn/", name:"厂长资源", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"https://www.libvio.me/", name:"Libvio", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"https://www.ysgc.cc/", name:"影视工厂", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"https://www.zxzj.fun", name:"在线之家", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"http://www.lezhutv.com", name:"乐猪TV", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"https://auete.com", name:"Auete", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"https://cokemv.me/", name:"Cokemv", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"https://www.o8tv.com/", name:"555电影", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" },//https://www.555dy.fun/ { url:"https://dmys1.com/", name:"大米星球", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"https://www.hdmoli.com/", name:"HDmoli", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"http://bukaivip1.com/", name:"不开VIP", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"https://www.duboku.net", name:"独播库", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"https://app.movie", name:"APP", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"https://www.adcmove.com", name:"ADC电影网", desc:"支持正版人人有责,日常观看请使用正版软件,仅作搜索用" }, { url:"https://epg.112114.xyz/", name:"直播电子节目单", desc:"EPG配合IPTV使用,效果更佳" }, { url:"https://www.tvcha.cn/", name:"TVCHA", desc:"EPG配合IPTV使用,效果更佳" }, { url:"http://www.tv.cn/", name:"TVCN", desc:"EPG配合IPTV使用,效果更佳" }, { url:"https://www.tvmao.com/", name:"电视猫", desc:"EPG配合IPTV使用,效果更佳" }, { url:"https://SQ688.Com", name:"无损音乐", desc:"支持正版人人有责,仅作搜索之用" }, { url:"http://www.yinfans.me/", name:"音范丝", desc:" " }, { url:"http://api.ckzy.vip", name:"超快资源", desc:"利用API解析" }, { url:"http://www.meiriyixue.cn/jx/", name:"每日一学", desc:"含解析和直播" }, { url:"http://home.jundie.top:81/TVBox/yosakoi.json", name:"解析合集", desc:"Box配置表" }, { url:"https://notabug.org/GY1111", name:"合集", desc:"TV菜单" }, { url:"https://github.com/Kimentanm", name:"APTV作者", desc:"GITHUB" }, { url:"http://lcoc.top/vip2.3/", name:"蓝调", desc:"智能解析" }, { url:"https://www.ikukk.com/?url=", name:"爱酷解析", desc:"" }, ] }, { name:"BT", icon:"graduation cap", list:[ { url:"https://thepiratebay.org/", name:"free-api", desc:"收集免费的接口服务" }, { url:"http://torrentz.eu/", name:"lightink-小说API", desc:"阅读书源在线解析api接口" }, { url:"http://www.sumotorrent.com/", name:"free-api", desc:"收集免费的接口服务" }, { url:"http://bitsnoop.com/", name:"lightink-小说API", desc:"阅读书源在线解析api接口" }, { url:" http://katcr.to/", name:"free-api", desc:"收集免费的接口服务" }, { url:"http://www.eztv.it", name:"lightink-小说API", desc:"阅读书源在线解析api接口" }, ] }, { name:"API", icon:"graduation cap", list:[ { url:"https://github.com/fangzesheng/free-api", name:"free-api", desc:"收集免费的接口服务" }, { url:"https://github.com/lightink-qingmo/lightink-server", name:"lightink-小说API", desc:"阅读书源在线解析api接口" } ] } ] } const el = (tag, attrs, content) => `<${tag} ${attrs.join(" ")}>${content}</${tag}>`; async function handleRequest(request) { const init = { headers: { 'content-type': 'text/html;charset=UTF-8', }, } return new Response(renderHTML(renderIndex(),config.selling_ads? renderSeller() :null), init); } addEventListener('fetch', event => { return event.respondWith(handleRequest(event.request)) }) /*通过分析链接 实时获取favicon * @url 需要分析的Url地址 */ function getFavicon(url){ if(url.match(/https{0,1}:\/\//)){ //return "https://ui-avatars.com/api/?bold=true&size=36&background=0D8ABC&color=fff&rounded=true&name=" + url.split('//')[1]; return "https://icon.occ.hk/get.php?url=" + url; }else{ //return "https://ui-avatars.com/api/?bold=true&size=36&background=0D8ABC&color=fff&rounded=true&name=" + url; return "https://icon.occ.hk/get.php?url=http://" + url; } } /** Render Functions * 渲染模块函数 */ function renderIndex(){ const footer = el('footer',[],el('div',['class="footer"'],'Powered by' + el('a',['class="ui label"','href="https://github.com/sleepwood/cf-worker-dir"','target="_blank"'],el('i',['class="github icon"'],"") + 'Cf-Worker-Dir') + ' &copy; Base on ' + el('a',['class="ui label"'],el('i',['class="balance scale icon"'],"") + 'MIT License'))); return renderHeader() + renderMain() + footer; } function renderHeader(){ const item = (template,name) => el('a',['class="item"',`data-url="${template}"`],name); var nav = el('div',['class="ui large secondary inverted menu"'],el('div',['class="item"'],el('p',['id="hitokoto"'],'条条大路通罗马'))) var title = el('h1',['class="ui inverted header"'],el('i',[`class="${config.logo_icon} icon"`],"") + el('div',['class="content"'],config.title + el('div',['class="sub header"'],config.subtitle))); var menu = el('div',['id="sengine"','class="ui bottom attached tabular inverted secondary menu"'],el('div',['class="header item"'],'&nbsp;') + config.search_engine.map((link,key) =>{ if(key == 0){ return el('a',['class="active item"',`data-url="${link.template}"`],link.name); }else{ return item(link.template,link.name); } }).join("")) var input = el('div',['class="ui left corner labeled right icon fluid large input"'],el('div',['class="ui left corner label"'],el('img',['id="search-fav"','class="left floated avatar ui image"','src="https://www.baidu.com/favicon.ico"'],"")) + el('input',['id="searchinput"','type="search"','placeholder="搜索你想要知道的……"','autocomplete="off"'],"") + el('i',['class="inverted circular search link icon"'],"")); return el('header',[],el('div',['id="head"','class="ui inverted vertical masthead center aligned segment"'],(config.hitokoto ? el('div',['id="nav"','class="ui container"'],nav) : "") + el('div',['id="title"','class="ui text container"'],title + (config.search ? input + menu :"") + `${config.selling_ads ? '<div><a id="menubtn" class="red ui icon inverted button"><i class="heart icon"></i> 喜欢此域名 </a></div>' : ''}`))) } function renderMain() { var main = config.lists.map((item) => { const card = (url,name,desc)=> el('a',['class="card"',`href=${url}`,'target="_blank"'],el('div',['class="content"'],el('img',['class="left floated avatar ui image"',`src=${getFavicon(url)}`],"") + el('div',['class="header"'],name) + el('div',['class="meta"'],desc))); const divider = el('h4',['class="ui horizontal divider header"'],el('i',[`class="${item.icon} icon"`],"")+item.name); var content = el('div',['class="ui four stackable cards"'],item.list.map((link) =>{ return card(link.url,link.name,link.desc); }).join("")); return el('div',['class="ui basic segment"'],divider + content); }).join(""); return el('main',[],el('div',['class="ui container"'],main)); } function renderSeller() { const item = (type,content) => el('div',['class="item"'],el('i',[`class="${type} icon"`],"") + el('div',['class="content"'],content)); var title = el('h1',['class="ui yellow dividing header"'],el('i',['class="gem outline icon"'],"") + el('div',['class="content"'],config.sell_info.domain + ' 正在出售')); var action = el('div',['class="actions"'],el('div',['class="ui basic cancel inverted button"'],el('i',['class="reply icon"'],"") + '返回')); var contact = config.sell_info.contact.map((list) => { return item(list.type,list.content); }).join(""); var column = el('div',['class="column"'],el('h3',['class="ui center aligned icon inverted header"'],el('i',['class="circular envelope open outline grey inverted icon"'],"") + '联系我') + el('div',['class="ui relaxed celled large list"'],contact)); var price = el('div',['class="column"'],el('div',['class="ui large yellow statistic"'],el('div',['class="value"'],el('i',[`class="${config.sell_info.mon_unit} icon"`],"") + config.sell_info.price))); var content = el('div',['class="content"'],el('div',['class="ui basic segment"'],el('div',['class="ui two column stackable center aligned grid"'],el('div',['class="ui inverted vertical divider"'],'感兴趣?') + el('div',['class="middle aligned row"'],price + column)))); return el('div',['id="seller"','class="ui basic modal"'],title + content + action); } function renderHTML(index,seller) { return `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>${config.title} - ${config.subtitle}</title> <link href="https://cdn.jsdelivr.net/npm/semantic-ui-css@2.4.1/semantic.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/gh/sleepwood/cf-worker-dir@0.1.1/style.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/semantic-ui-css@2.4.1/semantic.min.js"></script> </head> <body> ${index} ${config.selling_ads ? seller : ''} <script src="https://v1.hitokoto.cn/?encode=js&select=%23hitokoto" defer></script> <script> $('#sengine a').on('click', function (e) { $('#sengine a.active').toggleClass('active'); $(e.target).toggleClass('active'); $('#search-fav').attr('src',$(e.target).data('url').match(`+/https{0,1}:\/\/\S+\//+`)[0] + '/favicon.ico') ; }); $('.search').on('click', function (e) { var url = $('#sengine a.active').data('url'); url = url.replace(`+/\$s/+`,$('#searchinput').val()); window.open(url); }); /* 鼠标聚焦时,回车事件 */ $("#searchinput").bind("keypress", function(){ if (event.keyCode == 13){ // 触发需要调用的方法 $(".search").click(); } }); $('#menubtn').on('click', function (e) { $('#seller').modal('show'); }); </script> </body> </html>` }
/** * For OneDrive * IS_CN: 如果为世纪互联版本,请将 0 改为 1 * EXPOSE_PATH:暴露路径,如全盘展示请留空,否则按 '/媒体/音乐' 的格式填写 * ONEDRIVE_REFRESHTOKEN: refresh_token */ const IS_CN = 0; const EXPOSE_PATH = "" const ONEDRIVE_REFRESHTOKEN = "" async function handleRequest(request) { let requestPath let querySplited let queryString = request.url.split('?')[1] if (queryString) { querySplited = queryString.split('=') } if (querySplited && querySplited[0] === 'file') { const file = querySplited[1] const fileName = file.split('/').pop(); requestPath = file.replace('/' + fileName, '') const url = await fetchFiles(requestPath, fileName) return Response.redirect(url, 302) } else { const { headers } = request const contentType = headers.get('content-type') let body={} if (contentType && contentType.includes('form')) { const formData = await request.formData() for (let entry of formData.entries()) { body[entry[0]] = entry[1] } } requestPath = body ? body['?path'] : ''; const files = await fetchFiles(requestPath, null, body.passwd); return new Response(files, { headers: { 'content-type': 'application/json; charset=utf-8', 'Access-Control-Allow-Origin': '*' } }) } } addEventListener('fetch', event => { return event.respondWith(handleRequest(event.request)) }) const clientId = [ '4da3e7f2-bf6d-467c-aaf0-578078f0bf7c', '04c3ca0b-8d07-4773-85ad-98b037d25631' ] const clientSecret = [ '7/+ykq2xkfx:.DWjacuIRojIaaWL0QI6', 'h8@B7kFVOmj0+8HKBWeNTgl@pU/z4yLB' ] const oauthHost = [ 'https://login.microsoftonline.com', 'https://login.partner.microsoftonline.cn' ] const apiHost = [ 'https://graph.microsoft.com', 'https://microsoftgraph.chinacloudapi.cn' ] const OAUTH = { 'redirectUri': 'https://scfonedrive.github.io', 'refreshToken': ONEDRIVE_REFRESHTOKEN, 'clientId': clientId[IS_CN], 'clientSecret': clientSecret[IS_CN], 'oauthUrl': oauthHost[IS_CN] + '/common/oauth2/v2.0/', 'apiUrl': apiHost[IS_CN] + '/v1.0/me/drive/root', 'scope': apiHost[IS_CN] + '/Files.ReadWrite.All offline_access' } async function gatherResponse(response) { const { headers } = response const contentType = headers.get('content-type') if (contentType.includes('application/json')) { return await response.json() } else if (contentType.includes('application/text')) { return await response.text() } else if (contentType.includes('text/html')) { return await response.text() } else { return await response.text() } } async function getContent(url) { const response = await fetch(url) const result = await gatherResponse(response) return result } async function getContentWithHeaders(url, headers) { const response = await fetch(url, { headers: headers }) const result = await gatherResponse(response) return result } async function fetchFormData(url, data) { const formdata = new FormData(); for (const key in data) { if (data.hasOwnProperty(key)) { formdata.append(key, data[key]) } } const requestOptions = { method: 'POST', body: formdata }; const response = await fetch(url, requestOptions) const result = await gatherResponse(response) return result } async function fetchAccessToken() { url = OAUTH['oauthUrl'] + 'token' data = { 'client_id': OAUTH['clientId'], 'client_secret': OAUTH['clientSecret'], 'grant_type': 'refresh_token', 'requested_token_use': 'on_behalf_of', 'refresh_token': OAUTH['refreshToken'] } const result = await fetchFormData(url, data) return result.access_token } async function fetchFiles(path, fileName, passwd) { if (!path || path === '/') { if (EXPOSE_PATH === '') { path = '' } else { path = ':' + EXPOSE_PATH } } else { if (EXPOSE_PATH === '') { path = ':' + path } else { path = ':' + EXPOSE_PATH + path } } const accessToken = await fetchAccessToken() const uri = OAUTH.apiUrl + encodeURI(path) + '?expand=children(select=name,size,parentReference,lastModifiedDateTime,@microsoft.graph.downloadUrl)' const body = await getContentWithHeaders(uri, { Authorization: 'Bearer ' + accessToken }) if (fileName) { let thisFile = null body.children.forEach(file => { if (file.name === decodeURIComponent(fileName)) { thisFile = file['@microsoft.graph.downloadUrl'] return } }) return thisFile } else { let files = [] let encrypted = false for (let i = 0; i < body.children.length; i++) { const file = body.children[i] if (file.name === '.password') { const PASSWD = await getContent(file['@microsoft.graph.downloadUrl']) if (PASSWD !== passwd) { encrypted = true; break } else { continue } } files.push({ name: file.name, size: file.size, time: file.lastModifiedDateTime, url: file['@microsoft.graph.downloadUrl'] }) } let parent if (body.children.length) { parent = body.children[0].parentReference.path } else { parent = body.parentReference.path } parent = parent.split(':').pop().replace(EXPOSE_PATH, '') || '/' parent = decodeURIComponent(parent) if (encrypted) { return JSON.stringify({ parent: parent, files: [], encrypted: true }) } else { return JSON.stringify({ parent: parent, files: files }) } } }
/* *For NotionBlog */ const MY_DOMAIN = "" const START_PAGE = "https://www.notion.so/{'公开的路径'}" addEventListener('fetch', event => { event.respondWith(fetchAndApply(event.request)) }) const corsHeaders = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, HEAD, POST,PUT, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", } function handleOptions(request) { if (request.headers.get("Origin") !== null && request.headers.get("Access-Control-Request-Method") !== null && request.headers.get("Access-Control-Request-Headers") !== null) { // Handle CORS pre-flight request. return new Response(null, { headers: corsHeaders }) } else { // Handle standard OPTIONS request. return new Response(null, { headers: { "Allow": "GET, HEAD, POST, PUT, OPTIONS", } }) } } async function fetchAndApply(request) { if (request.method === "OPTIONS") { return handleOptions(request) } let url = new URL(request.url) let response if (url.pathname.startsWith("/app") && url.pathname.endsWith("js")) { response = await fetch(`https://www.notion.so${url.pathname}`) let body = await response.text() try { response = new Response(body.replace(/www.notion.so/g, MY_DOMAIN).replace(/notion.so/g, MY_DOMAIN), response) // response = new Response(response.body, response) response.headers.set('Content-Type', "application/x-javascript") console.log("get rewrite app.js") } catch (err) { console.log(err) } } else if ((url.pathname.startsWith("/api"))) { response = await fetch(`https://www.notion.so${url.pathname}`, { body: request.body, // must match 'Content-Type' header headers: { 'content-type': 'application/json;charset=UTF-8', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36' }, method: "POST", // *GET, POST, PUT, DELETE, etc. }) response = new Response(response.body, response) response.headers.set('Access-Control-Allow-Origin', "*") } else if (url.pathname === `/`) { let pageUrlList = START_PAGE.split("/") let redrictUrl = `https://${MY_DOMAIN}/${pageUrlList[pageUrlList.length-1]}` return Response.redirect(redrictUrl, 301) } else { response = await fetch(`https://www.notion.so${url.pathname}`, { body: request.body, // must match 'Content-Type' header headers: request.headers, method: request.method, // *GET, POST, PUT, DELETE, etc. }) } return response }
DEEPLX翻译API
var yt=t=>{let r=t.split("/");return r[0]===""&&r.shift(),r},vt=t=>{let r=[];for(let e=0;;){let s=!1;if(t=t.replace(/\{[^}]+\}/g,i=>{let o=`@\\${e}`;return r[e]=[o,i],e++,s=!0,o}),!s)break}let n=t.split("/");n[0]===""&&n.shift();for(let e=r.length-1;e>=0;e--){let[s]=r[e];for(let i=n.length-1;i>=0;i--)if(n[i].indexOf(s)!==-1){n[i]=n[i].replace(s,r[e][1]);break}}return n},z={},rt=t=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);return r?(z[t]||(r[2]?z[t]=[t,r[1],new RegExp("^"+r[2]+"$")]:z[t]=[t,r[1],!0]),z[t]):null},nt=t=>{let r=t.url.match(/^https?:\/\/[^/]+(\/[^?]*)/);return r?r[1]:""},wt=t=>{let r=t.indexOf("?",8);return r===-1?"":"?"+t.slice(r+1)},xt=t=>{let r=nt(t);return r.length>1&&r[r.length-1]==="/"?r.slice(0,-1):r},M=(...t)=>{let r="",n=!1;for(let e of t)r[r.length-1]==="/"&&(r=r.slice(0,-1),n=!0),e[0]!=="/"&&(e=`/${e}`),e==="/"&&n?r=`${r}/`:e!=="/"&&(r=`${r}${e}`),e==="/"&&r===""&&(r="/");return r},K=t=>{let r=t.match(/^(.+|)(\/\:[^\/]+)\?$/);if(!r)return null;let n=r[1],e=n+r[2];return[n===""?"/":n.replace(/\/$/,""),e]},et=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),/%/.test(t)?I(t):t):t,_t=(t,r,n)=>{let e;if(!n&&r&&!/[%+]/.test(r)){let o=t.indexOf(`?${r}`,8);for(o===-1&&(o=t.indexOf(`&${r}`,8));o!==-1;){let a=t.charCodeAt(o+r.length+1);if(a===61){let h=o+r.length+2,c=t.indexOf("&",h);return et(t.slice(h,c===-1?void 0:c))}else if(a==38||isNaN(a))return"";o=t.indexOf(`&${r}`,o+1)}if(e=/[%+]/.test(t),!e)return}let s={};e??(e=/[%+]/.test(t));let i=t.indexOf("?",8);for(;i!==-1;){let o=t.indexOf("&",i+1),a=t.indexOf("=",i);a>o&&o!==-1&&(a=-1);let h=t.slice(i+1,a===-1?o===-1?void 0:o:a);if(e&&(h=et(h)),i=o,h==="")continue;let c;a===-1?c="":(c=t.slice(a+1,o===-1?void 0:o),e&&(c=et(c))),n?(s[h]??(s[h]=[])).push(c):s[h]??(s[h]=c)}return r?s[r]:s},Et=_t,bt=(t,r)=>_t(t,r,!0),I=decodeURIComponent;var Bt=/^[\w!#$%&'*.^`|~+-]+$/,Ut=/^[ !#-:<-[\]-~]*$/,Rt=(t,r)=>t.trim().split(";").reduce((e,s)=>{s=s.trim();let i=s.indexOf("=");if(i===-1)return e;let o=s.substring(0,i).trim();if(r&&r!==o||!Bt.test(o))return e;let a=s.substring(i+1).trim();return a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),Ut.test(a)&&(e[o]=I(a)),e},{});var Wt=(t,r,n={})=>{let e=`${t}=${r}`;return n&&typeof n.maxAge=="number"&&n.maxAge>=0&&(e+=`; Max-Age=${Math.floor(n.maxAge)}`),n.domain&&(e+=`; Domain=${n.domain}`),n.path&&(e+=`; Path=${n.path}`),n.expires&&(e+=`; Expires=${n.expires.toUTCString()}`),n.httpOnly&&(e+="; HttpOnly"),n.secure&&(e+="; Secure"),n.sameSite&&(e+=`; SameSite=${n.sameSite}`),n.partitioned&&(e+="; Partitioned"),e},Ht=(t,r,n={})=>(r=encodeURIComponent(r),Wt(t,r,n));var Pt=class{constructor(t){this.writable=t,this.writer=t.getWriter(),this.encoder=new TextEncoder}async write(t){try{typeof t=="string"&&(t=this.encoder.encode(t)),await this.writer.write(t)}catch{}return this}async writeln(t){return await this.write(t+` `),this}sleep(t){return new Promise(r=>setTimeout(r,t))}async close(){try{await this.writer.close()}catch{}}async pipe(t){this.writer.releaseLock(),await t.pipeTo(this.writable,{preventClose:!0}),this.writer=this.writable.getWriter()}};var Ot="text/plain; charset=UTF-8",F=class{constructor(t,r){this.env={},this._var={},this.finalized=!1,this.error=void 0,this._status=200,this._h=void 0,this._pH=void 0,this._init=!0,this._renderer=n=>this.html(n),this.notFoundHandler=()=>new Response,this.render=(...n)=>this._renderer(...n),this.setRenderer=n=>{this._renderer=n},this.header=(n,e,s)=>{if(e===void 0){this._h?this._h.delete(n):this._pH&&delete this._pH[n.toLocaleLowerCase()],this.finalized&&this.res.headers.delete(n);return}s?.append?(this._h||(this._init=!1,this._h=new Headers(this._pH),this._pH={}),this._h.append(n,e)):this._h?this._h.set(n,e):(this._pH??(this._pH={}),this._pH[n.toLowerCase()]=e),this.finalized&&(s?.append?this.res.headers.append(n,e):this.res.headers.set(n,e))},this.status=n=>{this._init=!1,this._status=n},this.set=(n,e)=>{this._var??(this._var={}),this._var[n]=e},this.get=n=>this._var?this._var[n]:void 0,this.newResponse=(n,e,s)=>{if(this._init&&!s&&!e&&this._status===200)return new Response(n,{headers:this._pH});if(e&&typeof e!="number"){let o=new Response(n,e),a=this._pH?.["content-type"];return a&&o.headers.set("content-type",a),o}let i=e??this._status;this._pH??(this._pH={}),this._h??(this._h=new Headers);for(let[o,a]of Object.entries(this._pH))this._h.set(o,a);if(this._res){this._res.headers.forEach((o,a)=>{this._h?.set(a,o)});for(let[o,a]of Object.entries(this._pH))this._h.set(o,a)}s??(s={});for(let[o,a]of Object.entries(s))if(typeof a=="string")this._h.set(o,a);else{this._h.delete(o);for(let h of a)this._h.append(o,h)}return new Response(n,{status:i,headers:this._h})},this.body=(n,e,s)=>typeof e=="number"?this.newResponse(n,e,s):this.newResponse(n,e),this.text=(n,e,s)=>{if(!this._pH){if(this._init&&!s&&!e)return new Response(n);this._pH={}}return this._pH["content-type"]&&(this._pH["content-type"]=Ot),typeof e=="number"?this.newResponse(n,e,s):this.newResponse(n,e)},this.json=(n,e,s)=>{let i=JSON.stringify(n);return this._pH??(this._pH={}),this._pH["content-type"]="application/json; charset=UTF-8",typeof e=="number"?this.newResponse(i,e,s):this.newResponse(i,e)},this.jsonT=(n,e,s)=>{let i=typeof e=="number"?this.json(n,e,s):this.json(n,e);return{response:i,data:n,format:"json",status:i.status}},this.html=(n,e,s)=>(this._pH??(this._pH={}),this._pH["content-type"]="text/html; charset=UTF-8",typeof n=="object"&&(n instanceof Promise||(n=n.toString()),n instanceof Promise)?n.then(i=>typeof e=="number"?this.newResponse(i,e,s):this.newResponse(i,e)):typeof e=="number"?this.newResponse(n,e,s):this.newResponse(n,e)),this.redirect=(n,e=302)=>(this._h??(this._h=new Headers),this._h.set("Location",n),this.newResponse(null,e)),this.streamText=(n,e,s)=>(s??(s={}),this.header("content-type",Ot),this.header("x-content-type-options","nosniff"),this.header("transfer-encoding","chunked"),this.stream(n,e,s)),this.stream=(n,e,s)=>{let{readable:i,writable:o}=new TransformStream,a=new Pt(o);return n(a).finally(()=>a.close()),typeof e=="number"?this.newResponse(i,e,s):this.newResponse(i,e)},this.cookie=(n,e,s)=>{let i=Ht(n,e,s);this.header("set-cookie",i,{append:!0})},this.notFound=()=>this.notFoundHandler(this),this.req=t,r&&(this._exCtx=r.executionCtx,this.env=r.env,r.notFoundHandler&&(this.notFoundHandler=r.notFoundHandler))}get event(){if(this._exCtx&&"respondWith"in this._exCtx)return this._exCtx;throw Error("This context has no FetchEvent")}get executionCtx(){if(this._exCtx)return this._exCtx;throw Error("This context has no ExecutionContext")}get res(){return this._init=!1,this._res||(this._res=new Response("404 Not Found",{status:404}))}set res(t){this._init=!1,this._res&&t&&(this._res.headers.delete("content-type"),this._res.headers.forEach((r,n)=>{t.headers.set(n,r)})),this._res=t,this.finalized=!0}get var(){return{...this._var}}get runtime(){let t=globalThis;return t?.Deno!==void 0?"deno":t?.Bun!==void 0?"bun":typeof t?.WebSocketPair=="function"?"workerd":typeof t?.EdgeRuntime=="string"?"edge-light":t?.fastly!==void 0?"fastly":t?.__lagon__!==void 0?"lagon":t?.process?.release?.name==="node"?"node":"other"}};var st=(t,r,n)=>(e,s)=>{let i=-1;return o(0);async function o(a){if(a<=i)throw new Error("next() called multiple times");i=a;let h,c=!1,d;if(t[a]?(d=t[a][0],e instanceof F&&e.req.setParams(t[a][1])):d=a===t.length&&s||void 0,!d)e instanceof F&&e.finalized===!1&&n&&(h=n(e));else try{h=await d(e,()=>o(a+1))}catch(m){if(m instanceof Error&&e instanceof F&&r)e.error=m,h=r(m,e),c=!0;else throw m}return h!==void 0&&"response"in h&&(h=h.response),h&&(e.finalized===!1||c)&&(e.res=h),e}};var St=class extends Error{constructor(t=500,r){super(r?.message),this.res=r?.res,this.status=t}getResponse(){return this.res?this.res:new Response(this.message,{status:this.status})}};var Gt=t=>Array.isArray(t),Tt=async(t,r={all:!1})=>{let n={},e=t.headers.get("Content-Type");if(e&&(e.startsWith("multipart/form-data")||e.startsWith("application/x-www-form-urlencoded"))){let s=await t.formData();if(s){let i={};s.forEach((o,a)=>{if(!(r.all||a.slice(-2)==="[]")){i[a]=o;return}if(i[a]&&Gt(i[a])){i[a].push(o);return}if(i[a]){i[a]=[i[a],o];return}i[a]=o}),n=i}}return n};var Lt=class{constructor(t,r="/",n=[]){this._p={},this.bodyCache={},this.cachedBody=e=>{let{bodyCache:s,raw:i}=this,o=s[e];return o||(s.arrayBuffer?(async()=>await new Response(s.arrayBuffer)[e]())():s[e]=i[e]())},this.raw=t,this.path=r,this._s=n,this.vData={}}setParams(t){this._p=t}param(t){if(this._s)if(t){let r=this._s[this._p[t]]??this._p[t];return r?/\%/.test(r)?I(r):r:void 0}else{let r={},n=Object.keys(this._p);for(let e=0,s=n.length;e<s;e++){let i=n[e],o=this._s[this._p[i]]??this._p[i];o&&typeof o=="string"&&(r[i]=/\%/.test(o)?I(o):o)}return r}return null}query(t){return Et(this.url,t)}queries(t){return bt(this.url,t)}header(t){if(t)return this.raw.headers.get(t.toLowerCase())??void 0;let r={};return this.raw.headers.forEach((n,e)=>{r[e]=n}),r}cookie(t){let r=this.raw.headers.get("Cookie");if(!r)return;let n=Rt(r);return t?n[t]:n}async parseBody(t){if(this.bodyCache.parsedBody)return this.bodyCache.parsedBody;let r=await Tt(this,t);return this.bodyCache.parsedBody=r,r}json(){return this.cachedBody("json")}text(){return this.cachedBody("text")}arrayBuffer(){return this.cachedBody("arrayBuffer")}blob(){return this.cachedBody("blob")}formData(){return this.cachedBody("formData")}addValidatedData(t,r){this.vData[t]=r}valid(t){return this.vData[t]}get url(){return this.raw.url}get method(){return this.raw.method}get headers(){return this.raw.headers}get body(){return this.raw.body}get bodyUsed(){return this.raw.bodyUsed}get integrity(){return this.raw.integrity}get keepalive(){return this.raw.keepalive}get referrer(){return this.raw.referrer}get signal(){return this.raw.signal}};var _="ALL",jt="all",Q=["get","post","put","delete","options","patch"],V=class extends Error{};function zt(){return class{}}var Kt=t=>t.text("404 Not Found",404),At=(t,r)=>{if(t instanceof St)return t.getResponse();console.error(t);let n="Internal Server Error";return r.text(n,500)},it=class extends zt(){constructor(t={}){super(),this._basePath="/",this.path="/",this.routes=[],this.notFoundHandler=Kt,this.errorHandler=At,this.head=()=>(console.warn("`app.head()` is no longer used. `app.get()` implicitly handles the HEAD method."),this),this.handleEvent=e=>this.dispatch(e.request,e,void 0,e.request.method),this.fetch=(e,s,i)=>this.dispatch(e,i,s,e.method),this.request=(e,s,i,o)=>{if(e instanceof Request)return s!==void 0&&(e=new Request(e,s)),this.fetch(e,i,o);e=e.toString();let a=/^https?:\/\//.test(e)?e:`http://localhost${M("/",e)}`,h=new Request(a,s);return this.fetch(h,i,o)},this.fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.dispatch(e.request,e,void 0,e.request.method))})},[...Q,jt].map(e=>{this[e]=(s,...i)=>(typeof s=="string"?this.path=s:this.addRoute(e,this.path,s),i.map(o=>{typeof o!="string"&&this.addRoute(e,this.path,o)}),this)}),this.on=(e,s,...i)=>{if(!e)return this;this.path=s;for(let o of[e].flat())i.map(a=>{this.addRoute(o.toUpperCase(),this.path,a)});return this},this.use=(e,...s)=>(typeof e=="string"?this.path=e:s.unshift(e),s.map(i=>{this.addRoute(_,this.path,i)}),this);let n=t.strict??!0;delete t.strict,Object.assign(this,t),this.getPath=n?t.getPath??nt:xt}clone(){let t=new it({router:this.router,getPath:this.getPath});return t.routes=this.routes,t}route(t,r){let n=this.basePath(t);return r?(r.routes.map(e=>{let s=r.errorHandler===At?e.handler:async(i,o)=>(await st([],r.errorHandler)(i,()=>e.handler(i,o))).res;n.addRoute(e.method,e.path,s)}),this):n}basePath(t){let r=this.clone();return r._basePath=M(this._basePath,t),r}onError(t){return this.errorHandler=t,this}notFound(t){return this.notFoundHandler=t,this}showRoutes(){this.routes.map(r=>{console.log(`\x1B[32m${r.method}\x1B[0m ${" ".repeat(8-r.method.length)} ${r.path}`)})}mount(t,r,n){let e=M(this._basePath,t),s=e==="/"?0:e.length,i=async(o,a)=>{let h;try{h=o.executionCtx}catch{}let c=n?n(o):[o.env,h],d=Array.isArray(c)?c:[c],m=wt(o.req.url),v=await r(new Request(new URL((o.req.path.slice(s)||"/")+m,o.req.url),o.req.raw),...d);if(v)return v;await a()};return this.addRoute(_,M(t,"*"),i),this}get routerName(){return this.matchRoute("GET","/"),this.router.name}addRoute(t,r,n){t=t.toUpperCase(),r=M(this._basePath,r),this.router.add(t,r,n);let e={path:r,method:t,handler:n};this.routes.push(e)}matchRoute(t,r){return this.router.match(t,r)}handleError(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}dispatch(t,r,n,e){if(e==="HEAD")return(async()=>new Response(null,await this.dispatch(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),[i,o]=this.matchRoute(e,s),a=new F(new Lt(t,s,o||[]),{env:n,executionCtx:r,notFoundHandler:this.notFoundHandler});if(i.length===1){let c;a.req.setParams(i[0][1]);try{if(c=i[0][0](a,async()=>{}),!c)return this.notFoundHandler(a)}catch(d){return this.handleError(d,a)}return c instanceof Response||("response"in c&&(c=c.response),c instanceof Response)?c:(async()=>{let d;try{if(d=await c,d!==void 0&&"response"in d&&(d=d.response),!d)return this.notFoundHandler(a)}catch(m){return this.handleError(m,a)}return d})()}let h=st(i,this.errorHandler,this.notFoundHandler);return(async()=>{try{let c=await h(a);if(!c.finalized)throw new Error("Context is not finalized. You may forget returning Response object or `await next()`");return c.res}catch(c){return this.handleError(c,a)}})()}};var X="[^/]+",W=".*",G="(?:|/.*)",D=Symbol();function Qt(t,r){return t.length===1?r.length===1?t<r?-1:1:-1:r.length===1||t===W||t===G?1:r===W||r===G?-1:t===X?1:r===X?-1:t.length===r.length?t<r?-1:1:r.length-t.length}var Y=class{constructor(){this.children={}}insert(t,r,n,e,s){if(t.length===0){if(this.index!==void 0)throw D;if(s)return;this.index=r;return}let[i,...o]=t,a=i==="*"?o.length===0?["","",W]:["","",X]:i==="/*"?["","",G]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),h;if(a){let c=a[1],d=a[2]||X;if(c&&a[2]&&(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d)))throw D;if(h=this.children[d],!h){if(Object.keys(this.children).some(m=>m!==W&&m!==G))throw D;if(s)return;h=this.children[d]=new Y,c!==""&&(h.varIndex=e.varIndex++)}!s&&c!==""&&n.push([c,h.varIndex])}else if(h=this.children[i],!h){if(Object.keys(this.children).some(c=>c.length>1&&c!==W&&c!==G))throw D;if(s)return;h=this.children[i]=new Y}h.insert(o,r,n,e,s)}buildRegExpStr(){let r=Object.keys(this.children).sort(Qt).map(n=>{let e=this.children[n];return(typeof e.varIndex=="number"?`(${n})@${e.varIndex}`:n)+e.buildRegExpStr()});return typeof this.index=="number"&&r.unshift(`#${this.index}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var $t=class{constructor(){this.context={varIndex:0},this.root=new Y}insert(t,r,n){let e=[],s=[];for(let o=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,h=>{let c=`@\\${o}`;return s[o]=[c,h],o++,a=!0,c}),!a)break}let i=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=s.length-1;o>=0;o--){let[a]=s[o];for(let h=i.length-1;h>=0;h--)if(i[h].indexOf(a)!==-1){i[h]=i[h].replace(a,s[o][1]);break}}return this.root.insert(i,r,e,this.context,n),e}buildRegExp(){let t=this.root.buildRegExpStr();if(t==="")return[/^$/,[],[]];let r=0,n=[],e=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,i,o)=>typeof i<"u"?(n[++r]=Number(i),"$()"):(typeof o<"u"&&(e[Number(o)]=++r),"")),[new RegExp(`^${t}`),n,e]}};var ot=[_,...Q].map(t=>t.toUpperCase()),Ct=[],Vt=[/^$/,[],{}],at={};function kt(t){return at[t]??(at[t]=new RegExp(t==="*"?"":`^${t.replace(/\/\*/,"(?:|/.*)")}$`))}function Xt(){at={}}function Yt(t){let r=new $t,n=[];if(t.length===0)return Vt;let e=t.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,d],[m,v])=>c?1:m?-1:d.length-v.length),s={};for(let c=0,d=-1,m=e.length;c<m;c++){let[v,b,T]=e[c];v?s[b]=[T.map(([w])=>[w,{}]),Ct]:d++;let x;try{x=r.insert(b,d,v)}catch(w){throw w===D?new V(b):w}v||(n[d]=T.map(([w,O])=>{let j={};for(O-=1;O>=0;O--){let[S,A]=x[O];j[S]=A}return[w,j]}))}let[i,o,a]=r.buildRegExp();for(let c=0,d=n.length;c<d;c++)for(let m=0,v=n[c].length;m<v;m++){let b=n[c][m]?.[1];if(!b)continue;let T=Object.keys(b);for(let x=0,w=T.length;x<w;x++)b[T[x]]=a[b[T[x]]]}let h=[];for(let c in o)h[c]=n[o[c]];return[i,h,s]}function q(t,r){if(t){for(let n of Object.keys(t).sort((e,s)=>s.length-e.length))if(kt(n).test(r))return[...t[n]]}}var ht=class{constructor(){this.name="RegExpRouter",this.middleware={[_]:{}},this.routes={[_]:{}}}add(t,r,n){var e;let{middleware:s,routes:i}=this;if(!s||!i)throw new Error("Can not add a route since the matcher is already built.");ot.indexOf(t)===-1&&ot.push(t),s[t]||[s,i].forEach(h=>{h[t]={},Object.keys(h[_]).forEach(c=>{h[t][c]=[...h[_][c]]})}),r==="/*"&&(r="*");let o=(r.match(/\/:/g)||[]).length;if(/\*$/.test(r)){let h=kt(r);t===_?Object.keys(s).forEach(c=>{var d;(d=s[c])[r]||(d[r]=q(s[c],r)||q(s[_],r)||[])}):(e=s[t])[r]||(e[r]=q(s[t],r)||q(s[_],r)||[]),Object.keys(s).forEach(c=>{(t===_||t===c)&&Object.keys(s[c]).forEach(d=>{h.test(d)&&s[c][d].push([n,o])})}),Object.keys(i).forEach(c=>{(t===_||t===c)&&Object.keys(i[c]).forEach(d=>h.test(d)&&i[c][d].push([n,o]))});return}let a=K(r)||[r];for(let h=0,c=a.length;h<c;h++){let d=a[h];Object.keys(i).forEach(m=>{var v;(t===_||t===m)&&((v=i[m])[d]||(v[d]=[...q(s[m],d)||q(s[_],d)||[]]),i[m][d].push([n,a.length===2&&h===0?o-1:o]))})}}match(t,r){Xt();let n=this.buildAllMatchers();return this.match=(e,s)=>{let i=n[e],o=i[2][s];if(o)return o;let a=s.match(i[0]);if(!a)return[[],Ct];let h=a.indexOf("",1);return[i[1][h],a]},this.match(t,r)}buildAllMatchers(){let t={};return ot.forEach(r=>{t[r]=this.buildMatcher(r)||t[_]}),this.middleware=this.routes=void 0,t}buildMatcher(t){let r=[],n=t===_;return[this.middleware,this.routes].forEach(e=>{let s=e[t]?Object.keys(e[t]).map(i=>[i,e[t][i]]):[];s.length!==0?(n||(n=!0),r.push(...s)):t!==_&&r.push(...Object.keys(e[_]).map(i=>[i,e[_][i]]))}),n?Yt(r):null}};var ct=class{constructor(t){this.name="SmartRouter",this.routers=[],this.routes=[],Object.assign(this,t)}add(t,r,n){if(!this.routes)throw new Error("Can not add a route since the matcher is already built.");this.routes.push([t,r,n])}match(t,r){if(!this.routes)throw new Error("Fatal error");let{routers:n,routes:e}=this,s=n.length,i=0,o;for(;i<s;i++){let a=n[i];try{e.forEach(h=>{a.add(...h)}),o=a.match(t,r)}catch(h){if(h instanceof V)continue;throw h}this.match=a.match.bind(a),this.routers=[a],this.routes=void 0;break}if(i===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.routes||this.routers.length!==1)throw new Error("No active router has been determined yet.");return this.routers[0]}};var ut=class{constructor(t,r,n){if(this.order=0,this.params={},this.children=n||{},this.methods=[],this.name="",t&&r){let e={};e[t]={handler:r,params:{},possibleKeys:[],score:0,name:this.name},this.methods=[e]}this.patterns=[]}insert(t,r,n){this.name=`${t} ${r}`,this.order=++this.order;let e=this,s=vt(r),i=[],o=[];for(let c=0,d=s.length;c<d;c++){let m=s[c];if(Object.keys(e.children).includes(m)){o.push(...e.patterns),e=e.children[m];let b=rt(m);b&&i.push(b[1]);continue}e.children[m]=new ut;let v=rt(m);v&&(e.patterns.push(v),o.push(...e.patterns),i.push(v[1])),o.push(...e.patterns),e=e.children[m]}e.methods.length||(e.methods=[]);let a={},h={handler:n,params:{},possibleKeys:i,name:this.name,score:this.order};return a[t]=h,e.methods.push(a),e}gHSets(t,r,n){let e=[];for(let s=0,i=t.methods.length;s<i;s++){let o=t.methods[s],a=o[r]||o[_];a!==void 0&&(a.possibleKeys.map(h=>{a.params[h]=n[h]}),e.push(a))}return e}search(t,r){let n=[],e={};this.params={};let i=[this],o=yt(r);for(let h=0,c=o.length;h<c;h++){let d=o[h],m=h===c-1,v=[];for(let b=0,T=i.length;b<T;b++){let x=i[b],w=x.children[d];w&&(m===!0?(w.children["*"]&&n.push(...this.gHSets(w.children["*"],t,{...e,...x.params})),n.push(...this.gHSets(w,t,{...e,...x.params}))):v.push(w));for(let O=0,j=x.patterns.length;O<j;O++){let S=x.patterns[O];if(S==="*"){let $=x.children["*"];$&&(n.push(...this.gHSets($,t,{...e,...x.params})),v.push($));continue}if(d==="")continue;let[A,k,L]=S,R=x.children[A],B=o.slice(h).join("/");if(L instanceof RegExp&&L.test(B)){e[k]=B,n.push(...this.gHSets(R,t,{...e,...x.params}));continue}(L===!0||L instanceof RegExp&&L.test(d))&&typeof A=="string"&&(e[k]=d,m===!0?(n.push(...this.gHSets(R,t,{...e,...x.params})),R.children["*"]&&n.push(...this.gHSets(R.children["*"],t,{...e,...x.params}))):(R.params={...e},v.push(R)))}}i=v}return[n.sort((h,c)=>h.score-c.score).map(({handler:h,params:c})=>[h,c])]}};var lt=class{constructor(){this.name="TrieRouter",this.node=new ut}add(t,r,n){let e=K(r);if(e){for(let s of e)this.node.insert(t,s,n);return}this.node.insert(t,r,n)}match(t,r){return this.node.search(t,r)}};var ft=class extends it{constructor(t={}){super(t),this.router=t.router??new ct({routers:[new ht,new lt]})}};function dt(){dt=function(){return r};var t,r={},n=Object.prototype,e=n.hasOwnProperty,s=Object.defineProperty||function(l,u,f){l[u]=f.value},i=typeof Symbol=="function"?Symbol:{},o=i.iterator||"@@iterator",a=i.asyncIterator||"@@asyncIterator",h=i.toStringTag||"@@toStringTag";function c(l,u,f){return Object.defineProperty(l,u,{value:f,enumerable:!0,configurable:!0,writable:!0}),l[u]}try{c({},"")}catch{c=function(u,f,g){return u[f]=g}}function d(l,u,f,g){var p=u&&u.prototype instanceof O?u:O,y=Object.create(p.prototype),E=new Z(g||[]);return s(y,"_invoke",{value:Dt(l,f,E)}),y}function m(l,u,f){try{return{type:"normal",arg:l.call(u,f)}}catch(g){return{type:"throw",arg:g}}}r.wrap=d;var v="suspendedStart",b="suspendedYield",T="executing",x="completed",w={};function O(){}function j(){}function S(){}var A={};c(A,o,function(){return this});var k=Object.getPrototypeOf,L=k&&k(k(tt([])));L&&L!==n&&e.call(L,o)&&(A=L);var R=S.prototype=O.prototype=Object.create(A);function B(l){["next","throw","return"].forEach(function(u){c(l,u,function(f){return this._invoke(u,f)})})}function $(l,u){function f(p,y,E,H){var P=m(l[p],l,y);if(P.type!=="throw"){var N=P.arg,U=N.value;return U&&typeof U=="object"&&e.call(U,"__await")?u.resolve(U.__await).then(function(C){f("next",C,E,H)},function(C){f("throw",C,E,H)}):u.resolve(U).then(function(C){N.value=C,E(N)},function(C){return f("throw",C,E,H)})}H(P.arg)}var g;s(this,"_invoke",{value:function(p,y){function E(){return new u(function(H,P){f(p,y,H,P)})}return g=g?g.then(E,E):E()}})}function Dt(l,u,f){var g=v;return function(p,y){if(g===T)throw new Error("Generator is already running");if(g===x){if(p==="throw")throw y;return{value:t,done:!0}}for(f.method=p,f.arg=y;;){var E=f.delegate;if(E){var H=gt(E,f);if(H){if(H===w)continue;return H}}if(f.method==="next")f.sent=f._sent=f.arg;else if(f.method==="throw"){if(g===v)throw g=x,f.arg;f.dispatchException(f.arg)}else f.method==="return"&&f.abrupt("return",f.arg);g=T;var P=m(l,u,f);if(P.type==="normal"){if(g=f.done?x:b,P.arg===w)continue;return{value:P.arg,done:f.done}}P.type==="throw"&&(g=x,f.method="throw",f.arg=P.arg)}}}function gt(l,u){var f=u.method,g=l.iterator[f];if(g===t)return u.delegate=null,f==="throw"&&l.iterator.return&&(u.method="return",u.arg=t,gt(l,u),u.method==="throw")||f!=="return"&&(u.method="throw",u.arg=new TypeError("The iterator does not provide a '"+f+"' method")),w;var p=m(g,l.iterator,u.arg);if(p.type==="throw")return u.method="throw",u.arg=p.arg,u.delegate=null,w;var y=p.arg;return y?y.done?(u[l.resultName]=y.value,u.next=l.nextLoc,u.method!=="return"&&(u.method="next",u.arg=t),u.delegate=null,w):y:(u.method="throw",u.arg=new TypeError("iterator result is not an object"),u.delegate=null,w)}function qt(l){var u={tryLoc:l[0]};1 in l&&(u.catchLoc=l[1]),2 in l&&(u.finallyLoc=l[2],u.afterLoc=l[3]),this.tryEntries.push(u)}function J(l){var u=l.completion||{};u.type="normal",delete u.arg,l.completion=u}function Z(l){this.tryEntries=[{tryLoc:"root"}],l.forEach(qt,this),this.reset(!0)}function tt(l){if(l||l===""){var u=l[o];if(u)return u.call(l);if(typeof l.next=="function")return l;if(!isNaN(l.length)){var f=-1,g=function p(){for(;++f<l.length;)if(e.call(l,f))return p.value=l[f],p.done=!1,p;return p.value=t,p.done=!0,p};return g.next=g}}throw new TypeError(typeof l+" is not iterable")}return j.prototype=S,s(R,"constructor",{value:S,configurable:!0}),s(S,"constructor",{value:j,configurable:!0}),j.displayName=c(S,h,"GeneratorFunction"),r.isGeneratorFunction=function(l){var u=typeof l=="function"&&l.constructor;return!!u&&(u===j||(u.displayName||u.name)==="GeneratorFunction")},r.mark=function(l){return Object.setPrototypeOf?Object.setPrototypeOf(l,S):(l.__proto__=S,c(l,h,"GeneratorFunction")),l.prototype=Object.create(R),l},r.awrap=function(l){return{__await:l}},B($.prototype),c($.prototype,a,function(){return this}),r.AsyncIterator=$,r.async=function(l,u,f,g,p){p===void 0&&(p=Promise);var y=new $(d(l,u,f,g),p);return r.isGeneratorFunction(u)?y:y.next().then(function(E){return E.done?E.value:y.next()})},B(R),c(R,h,"Generator"),c(R,o,function(){return this}),c(R,"toString",function(){return"[object Generator]"}),r.keys=function(l){var u=Object(l),f=[];for(var g in u)f.push(g);return f.reverse(),function p(){for(;f.length;){var y=f.pop();if(y in u)return p.value=y,p.done=!1,p}return p.done=!0,p}},r.values=tt,Z.prototype={constructor:Z,reset:function(l){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(J),!l)for(var u in this)u.charAt(0)==="t"&&e.call(this,u)&&!isNaN(+u.slice(1))&&(this[u]=t)},stop:function(){this.done=!0;var l=this.tryEntries[0].completion;if(l.type==="throw")throw l.arg;return this.rval},dispatchException:function(l){if(this.done)throw l;var u=this;function f(P,N){return y.type="throw",y.arg=l,u.next=P,N&&(u.method="next",u.arg=t),!!N}for(var g=this.tryEntries.length-1;g>=0;--g){var p=this.tryEntries[g],y=p.completion;if(p.tryLoc==="root")return f("end");if(p.tryLoc<=this.prev){var E=e.call(p,"catchLoc"),H=e.call(p,"finallyLoc");if(E&&H){if(this.prev<p.catchLoc)return f(p.catchLoc,!0);if(this.prev<p.finallyLoc)return f(p.finallyLoc)}else if(E){if(this.prev<p.catchLoc)return f(p.catchLoc,!0)}else{if(!H)throw new Error("try statement without catch or finally");if(this.prev<p.finallyLoc)return f(p.finallyLoc)}}}},abrupt:function(l,u){for(var f=this.tryEntries.length-1;f>=0;--f){var g=this.tryEntries[f];if(g.tryLoc<=this.prev&&e.call(g,"finallyLoc")&&this.prev<g.finallyLoc){var p=g;break}}p&&(l==="break"||l==="continue")&&p.tryLoc<=u&&u<=p.finallyLoc&&(p=null);var y=p?p.completion:{};return y.type=l,y.arg=u,p?(this.method="next",this.next=p.finallyLoc,w):this.complete(y)},complete:function(l,u){if(l.type==="throw")throw l.arg;return l.type==="break"||l.type==="continue"?this.next=l.arg:l.type==="return"?(this.rval=this.arg=l.arg,this.method="return",this.next="end"):l.type==="normal"&&u&&(this.next=u),w},finish:function(l){for(var u=this.tryEntries.length-1;u>=0;--u){var f=this.tryEntries[u];if(f.finallyLoc===l)return this.complete(f.completion,f.afterLoc),J(f),w}},catch:function(l){for(var u=this.tryEntries.length-1;u>=0;--u){var f=this.tryEntries[u];if(f.tryLoc===l){var g=f.completion;if(g.type==="throw"){var p=g.arg;J(f)}return p}}throw new Error("illegal catch attempt")},delegateYield:function(l,u,f){return this.delegate={iterator:tt(l),resultName:u,nextLoc:f},this.method==="next"&&(this.arg=t),w}},r}function Nt(t,r,n,e,s,i,o){try{var a=t[i](o),h=a.value}catch(c){n(c);return}a.done?r(h):Promise.resolve(h).then(e,s)}function Jt(t){return function(){var r=this,n=arguments;return new Promise(function(e,s){var i=t.apply(r,n);function o(h){Nt(i,e,s,o,a,"next",h)}function a(h){Nt(i,e,s,o,a,"throw",h)}o(void 0)})}}function pt(){return pt=Object.assign?Object.assign.bind():function(t){for(var r=1;r<arguments.length;r++){var n=arguments[r];for(var e in n)Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=n[e])}return t},pt.apply(this,arguments)}var Zt="https://www2.deepl.com/jsonrpc",Mt=3;function te(t,r){var n,e;return t===void 0&&(t="auto"),r===void 0&&(r="en"),{jsonrpc:"2.0",method:"LMT_handle_texts",id:Math.floor(Math.random()*1e5+1e5)*1e3,params:{texts:[{text:"",requestAlternatives:Mt}],timestamp:0,splitting:"newlines",lang:{source_lang_user_selected:(n=t)==null?void 0:n.toUpperCase(),target_lang:(e=r)==null?void 0:e.toUpperCase()}}}}function ee(t){return(t||"").split("i").length-1}function re(t){var r=new Date().getTime();return t!==0?r-r%(t+1)+(t+1):r}function ne(t){var r=te(t.source_lang,t.target_lang);r.params.texts=[{text:t.text,requestAlternatives:Mt}],r.params.timestamp=re(ee(t.text));var n=JSON.stringify(r);return[0,3].includes((r.id+5)%29)||(r.id+3)%13===0?n=n.replace('"method":"','"method" : "'):n=n.replace('"method":"','"method": "'),n}function It(t,r){return mt.apply(this,arguments)}function mt(){return mt=Jt(dt().mark(function t(r,n){var e,s,i,o,a,h;return dt().wrap(function(d){for(;;)switch(d.prev=d.next){case 0:if(r!=null&&r.text){d.next=2;break}return d.abrupt("return",{code:404,message:"No Translate Text Found",data:null});case 2:return d.next=4,fetch((e=n?.proxyEndpoint)!=null?e:Zt,{headers:pt({"Content-Type":"application/json; charset=utf-8"},n?.customHeader),method:"POST",body:ne(r)});case 4:if(s=d.sent,!s.ok){d.next=13;break}return d.next=8,s.json();case 8:return a=d.sent,h=a.result,d.abrupt("return",{code:200,message:"success",data:h==null||(i=h.texts)==null||(i=i[0])==null?void 0:i.text,source_lang:r?.source_lang||"auto",target_lang:r?.target_lang||"en",alternatives:(o=h.texts)==null||(o=o[0])==null||(o=o.alternatives)==null||o.map==null?void 0:o.map(function(m){return m.text})});case 13:return d.abrupt("return",{code:s.status,data:null,message:s.status===429?"Too many requests, please try again later.":"Unknown error."});case 14:case"end":return d.stop()}},t)})),mt.apply(this,arguments)}var Ft=new ft,se="https://cors.mingming.dev/https://www2.deepl.com/jsonrpc";Ft.get("/",t=>t.redirect("/translate")).get("/translate",t=>t.text("Please use POST method :)")).post("/translate",async t=>{let r=await t.req.json().catch(()=>({})),n=await It(r,{proxyEndpoint:se});return t.json(n,n.code)});var Wr=Ft;export{Wr as default};
/* * https://github.com/netnr/workers * * 2019-10-12 - 2022-05-05 * netnr * * https://github.com/Rongronggg9/rsstt-img-relay * * 2021-09-13 - 2022-05-29 * modified by Rongronggg9 * * 2023-4-21 * modified by papersman */ export default { async fetch(request, _env) { return await handleRequest(request); } } /** * Configurations */ const yourDomain = 'your.workers.dev'; const config = { // 是否丢弃请求中的 Referer,在目标网站应用防盗链时有用 dropReferer: true, }; /** * Respond to the request * @param {Request} request */ async function handleRequest(request) { //请求头部、返回对象 let reqHeaders = new Headers(request.headers), outBody, outStatus = 200, outStatusText = 'OK', outCt = null, outHeaders = new Headers({ "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS", "Access-Control-Allow-Headers": reqHeaders.get('Access-Control-Allow-Headers') || "Accept, Authorization, Cache-Control, Content-Type, DNT, If-Modified-Since, Keep-Alive, Origin, User-Agent, X-Requested-With, Token, x-access-token" }); try { //取域名第一个斜杠后的所有信息为代理链接 let url = request.url.substr(8); url = decodeURIComponent(url.substr(url.indexOf('/') + 1)); //需要忽略的代理 if (request.method == "OPTIONS" || url.length < 3 || url.indexOf('.') == -1 || url == "favicon.ico" || url == "robots.txt") { //输出提示 const invalid = !(request.method == "OPTIONS" || url.length === 0) outBody = JSON.stringify({ code: invalid ? 400 : 0, usage: 'https://'+yourDomain+'/https://mikanani.me/...', source: '将 your.workers.dev 换成自己的workers的地址.使用的时候, RSS地址位置填入 '+'https://'+yourDomain+'/https://mikanani.me/RSS/...' }); outCt = "application/json"; outStatus = invalid ? 400 : 200; } else { url = fixUrl(url); //构建 fetch 参数 let fp = { method: request.method, headers: {} } // 发起 fetch let fr = (await fetch(url, fp)); outCt = fr.headers.get('content-type'); //保留头部其它信息 const dropHeaders = ['content-length', 'content-type', 'host']; if (config.dropReferer) dropHeaders.push('referer'); let he = reqHeaders.entries(); for (let h of he) { const key = h[0], value = h[1]; if (!dropHeaders.includes(key)) { fp.headers[key] = value; } } if (config.dropReferer && url.includes('.sinaimg.cn/')) fp.headers['referer'] = 'https://weibo.com/'; // 当访问mikanani.me/RSS的时候,将返回的xml中的mikanani.me替换 if (url.includes('mikanani.me/RSS')) { const response = await fetch(url, fp); const text = await response.text(); outBody = text.replace(/mikanani.me\/Download\//g, yourDomain+'/https://mikanani.me/Download/'); outCt = response.headers.get('content-type'); outStatus = response.status; outStatusText = response.statusText; } else if (url.includes('acg.rip/.xml')) { //当访问acg.rip/.xml的时候,将返回的xml中的acg.rip/t/替换 const response = await fetch(url, fp); const text = await response.text(); outBody = text.replace(/acg.rip\/t\//g, yourDomain+'/https://acg.rip/t/'); outCt = response.headers.get('content-type'); outStatus = response.status; outStatusText = response.statusText; } else if (url.includes('bangumi.moe/rss')) { //当访问bangumi.moe/rss的时候,将返回的xml中的bangumi.moe/download替换 const response = await fetch(url, fp); const text = await response.text(); outBody = text.replace(/bangumi.moe\/download\//g, yourDomain+'/https://bangumi.moe/download/'); outCt = response.headers.get('content-type'); outStatus = response.status; outStatusText = response.statusText; } else { outBody = fr.body; outStatus = fr.status; outStatusText = fr.statusText; }; if (["POST", "PUT", "PATCH", "DELETE"].indexOf(request.method) >= 0) { const ct = (reqHeaders.get('content-type') || "").toLowerCase(); fp.headers['content-type'] = ct if (ct.includes('application/json')) { fp.body = JSON.stringify(await request.json()); } else if (ct.includes('application/text') || ct.includes('text/html')) { fp.body = await request.text(); } else if (ct.includes('form')) { fp.body = await request.formData(); } else { fp.body = await request.blob(); } }; } } catch (err) { outBody = err.stack; outCt = "text/plain;charset=UTF-8"; outStatus = 500; outStatusText = "Internal Server Error"; } //设置类型 if (outCt && outCt != "") { outHeaders.set("content-type", outCt); } let response = new Response(outBody, { status: outStatus, statusText: outStatusText, headers: outHeaders }) return response; } /** * Fix URL * @param {string} url */ function fixUrl(url) { if (url.startsWith('http://') || url.startsWith('https://')) { return url; } else { return 'https://' + url; } }
  • cloudflare
  • 自动化脚本测试
    Catalog