(()=>{var a={};a.id=6594,a.ids=[6594],a.modules={261:a=>{"use strict";a.exports=require("next/dist/shared/lib/router/utils/app-paths")},3295:a=>{"use strict";a.exports=require("next/dist/server/app-render/after-task-async-storage.external.js")},10846:a=>{"use strict";a.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},11259:(a,b,c)=>{"use strict";c.d(b,{Pv:()=>k}),c(73024);var d=c(51455),e=c(76760),f=c(73136);async function g(a,b,c){for(let d=0;d<b;d++)try{return await a()}catch(a){if(d<b-1)await new Promise(a=>setTimeout(a,c));else throw a}}class h{#a;#b;#c=!1;#d=null;#e=null;#f=null;#g=null;#h(a){return this.#g=a,this.#f||=new Promise((a,b)=>{this.#e=[a,b]}),new Promise((a,b)=>{this.#f?.then(a).catch(b)})}async #i(a){this.#c=!0;try{await (0,d.writeFile)(this.#b,a,"utf-8"),await g(async()=>{await (0,d.rename)(this.#b,this.#a)},10,100),this.#d?.[0]()}catch(a){throw a instanceof Error&&this.#d?.[1](a),a}finally{if(this.#c=!1,this.#d=this.#e,this.#e=this.#f=null,null!==this.#g){let a=this.#g;this.#g=null,await this.write(a)}}}constructor(a){this.#a=a,this.#b=function(a){let b=a instanceof URL?(0,f.fileURLToPath)(a):a.toString();return(0,e.join)((0,e.dirname)(b),`.${(0,e.basename)(b)}.tmp`)}(a)}async write(a){return this.#c?this.#h(a):this.#i(a)}}class i{#a;#j;constructor(a){this.#a=a,this.#j=new h(a)}async read(){let a;try{a=await (0,d.readFile)(this.#a,"utf-8")}catch(a){if("ENOENT"===a.code)return null;throw a}return a}write(a){return this.#j.write(a)}}class j{#k;#l;#m;constructor(a,{parse:b,stringify:c}){this.#k=new i(a),this.#l=b,this.#m=c}async read(){let a=await this.#k.read();return null===a?null:this.#l(a)}write(a){return this.#k.write(this.#m(a))}}class k extends j{constructor(a){super(a,{parse:JSON.parse,stringify:a=>JSON.stringify(a,null,2)})}}},12412:a=>{"use strict";a.exports=require("assert")},21820:a=>{"use strict";a.exports=require("os")},27910:a=>{"use strict";a.exports=require("stream")},28354:a=>{"use strict";a.exports=require("util")},29021:a=>{"use strict";a.exports=require("fs")},29294:a=>{"use strict";a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},33873:a=>{"use strict";a.exports=require("path")},44870:a=>{"use strict";a.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},49120:(a,b,c)=>{"use strict";c.r(b),c.d(b,{APP_NAME:()=>j,DATA_DIR:()=>p,DB_FILE:()=>q,LEGACY_APP_NAME:()=>k,getDataDir:()=>o,getLegacyDataDir:()=>n,migrateLegacyDataFilesIfNeeded:()=>r});var d=c(29021),e=c.n(d),f=c(33873),g=c.n(f),h=c(21820),i=c.n(h);let j="openrouterx",k="9router",l=["db.json","usage.json","log.txt","disabledModels.json","request-details.json"];function m(a){return"win32"===process.platform?g().join(process.env.APPDATA||g().join(i().homedir(),"AppData","Roaming"),a):g().join(i().homedir(),`.${a}`)}function n(){return m(k)}function o(){let a=process.env.DATA_DIR;if(!a)return m(j);try{return e().mkdirSync(a,{recursive:!0}),a}catch(b){if(b?.code==="EACCES"||b?.code==="EPERM")return console.warn(`[DATA_DIR] '${a}' not writable -> fallback ~/.${j}`),m(j);throw b}}let p=o(),q=g().join(p,"db.json");function r(){if(process.env.DATA_DIR)return!1;let a=n();if(a===p||!e().existsSync(a))return!1;let b=!1;for(let c of(e().existsSync(p)||e().mkdirSync(p,{recursive:!0}),l)){let d=g().join(a,c),f=g().join(p,c);e().existsSync(d)&&!e().existsSync(f)&&(e().copyFileSync(d,f),b=!0)}return b}r()},51455:a=>{"use strict";a.exports=require("node:fs/promises")},55511:a=>{"use strict";a.exports=require("crypto")},63033:a=>{"use strict";a.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},71998:(a,b,c)=>{"use strict";c.d(b,{Fh:()=>d.getProviderNodes,L9:()=>d.L9,Mc:()=>d.Mc,OM:()=>d.OM,P:()=>d.getProviderConnections,Pc:()=>d.Pc,Q_:()=>d.Q_,Qu:()=>d.Qu,S8:()=>d.S8,Yd:()=>d.Yd,ZO:()=>d.ZO,c:()=>d.getMitmAlias,createProviderConnection:()=>d.iE,fK:()=>d.fK,fv:()=>d.fv,ho:()=>d.ho,hr:()=>d.hr,i0:()=>d.i0,o5:()=>d.o5,op:()=>d.op,rj:()=>d.updateProviderConnection,uL:()=>d.uL,ui:()=>d.ui,uv:()=>d.uv});var d=c(89718)},73024:a=>{"use strict";a.exports=require("node:fs")},73136:a=>{"use strict";a.exports=require("node:url")},74600:(a,b,c)=>{"use strict";c.r(b),c.d(b,{handler:()=>G,patchFetch:()=>F,routeModule:()=>B,serverHooks:()=>E,workAsyncStorage:()=>C,workUnitAsyncStorage:()=>D});var d={};c.r(d),c.d(d,{POST:()=>A});var e=c(19225),f=c(84006),g=c(8317),h=c(99373),i=c(34775),j=c(24235),k=c(261),l=c(54365),m=c(90771),n=c(73461),o=c(67798),p=c(92280),q=c(62018),r=c(45696),s=c(47929),t=c(86439),u=c(37527),v=c(23211),w=c(71998);let x="https://api.vercel.com",y=`
export const config = { runtime: "edge" };

export default async function handler(req) {
  const target = req.headers.get("x-relay-target");
  const relayPath = req.headers.get("x-relay-path") || "/";
  if (!target) {
    return new Response(JSON.stringify({ error: "Missing x-relay-target header" }), {
      status: 400,
      headers: { "content-type": "application/json" },
    });
  }

  const targetUrl = target.replace(/\\/$/, "") + relayPath;

  const headers = new Headers(req.headers);
  headers.delete("x-relay-target");
  headers.delete("x-relay-path");
  headers.delete("host");

  const response = await fetch(targetUrl, {
    method: req.method,
    headers,
    body: req.method !== "GET" && req.method !== "HEAD" ? req.body : undefined,
    duplex: "half",
  });

  return new Response(response.body, {
    status: response.status,
    headers: response.headers,
  });
}
`;async function z(a,b,c=12e4){let d=Date.now();for(;Date.now()-d<c;){let c=await fetch(`${x}/v13/deployments/${a}`,{headers:{Authorization:`Bearer ${b}`}}),d=await c.json();if("READY"===d.readyState)return d;if("ERROR"===d.readyState||"CANCELED"===d.readyState)throw Error(`Deployment failed: ${d.readyState}`);await new Promise(a=>setTimeout(a,3e3))}throw Error("Deployment timed out")}async function A(a){try{let b=await a.json(),c=b.vercelToken,d=b.projectName?.trim()||`relay-${Date.now().toString(36)}`;if(!c)return v.NextResponse.json({error:"Vercel API token is required"},{status:400});let e=await fetch(`${x}/v13/deployments`,{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify({name:d,files:[{file:"api/relay.js",data:y},{file:"package.json",data:JSON.stringify({name:d,version:"1.0.0"})},{file:"vercel.json",data:JSON.stringify({rewrites:[{source:"/(.*)",destination:"/api/relay"}]})}],projectSettings:{framework:null},target:"production"})});if(!e.ok){let a=await e.json().catch(()=>({}));return v.NextResponse.json({error:a.error?.message||"Failed to create Vercel deployment"},{status:e.status})}let f=await e.json(),g=f.id||f.uid,h=f.projectId||d;await fetch(`${x}/v9/projects/${h}`,{method:"PATCH",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify({ssoProtection:null})});let i=await z(g,c),j=`https://${i.url}`,k=await (0,w.ZO)({name:d,proxyUrl:j,type:"vercel",noProxy:"",isActive:!0,strictProxy:!1});return v.NextResponse.json({proxyPool:k,deployUrl:j},{status:201})}catch(a){return console.log("Error deploying Vercel relay:",a),v.NextResponse.json({error:a.message||"Deploy failed"},{status:500})}}let B=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/proxy-pools/vercel-deploy/route",pathname:"/api/proxy-pools/vercel-deploy",filename:"route",bundlePath:"app/api/proxy-pools/vercel-deploy/route"},distDir:".next",relativeProjectDir:"",resolvedPagePath:"/Users/bytedance/Documents/Projects/9router/src/app/api/proxy-pools/vercel-deploy/route.js",nextConfigOutput:"standalone",userland:d,...{}}),{workAsyncStorage:C,workUnitAsyncStorage:D,serverHooks:E}=B;function F(){return(0,g.patchFetch)({workAsyncStorage:C,workUnitAsyncStorage:D})}async function G(a,b,c){c.requestMeta&&(0,h.setRequestMeta)(a,c.requestMeta),B.isDev&&(0,h.addRequestMeta)(a,"devRequestTimingInternalsEnd",process.hrtime.bigint());let d="/api/proxy-pools/vercel-deploy/route";"/index"===d&&(d="/");let e=await B.prepare(a,b,{srcPage:d,multiZoneDraftMode:!1});if(!e)return b.statusCode=400,b.end("Bad Request"),null==c.waitUntil||c.waitUntil.call(c,Promise.resolve()),null;let{buildId:g,deploymentId:v,params:w,nextConfig:x,parsedUrl:y,isDraftMode:z,prerenderManifest:A,routerServerContext:C,isOnDemandRevalidate:D,revalidateOnlyGenerated:E,resolvedPathname:F,clientReferenceManifest:G,serverActionsManifest:H}=e,I=(0,k.normalizeAppPath)(d),J=!!(A.dynamicRoutes[I]||A.routes[F]),K=async()=>((null==C?void 0:C.render404)?await C.render404(a,b,y,!1):b.end("This page could not be found"),null);if(J&&!z){let a=!!A.routes[F],b=A.dynamicRoutes[I];if(b&&!1===b.fallback&&!a){if(x.adapterPath)return await K();throw new t.NoFallbackError}}let L=null;!J||B.isDev||z||(L="/index"===(L=F)?"/":L);let M=!0===B.isDev||!J,N=J&&!M;H&&G&&(0,j.setManifestsSingleton)({page:d,clientReferenceManifest:G,serverActionsManifest:H});let O=a.method||"GET",P=(0,i.getTracer)(),Q=P.getActiveScopeSpan(),R=!!(null==C?void 0:C.isWrappedByNextServer),S=!!(0,h.getRequestMeta)(a,"minimalMode"),T=(0,h.getRequestMeta)(a,"incrementalCache")||await B.getIncrementalCache(a,x,A,S);null==T||T.resetRequestCache(),globalThis.__incrementalCache=T;let U={params:w,previewProps:A.preview,renderOpts:{experimental:{authInterrupts:!!x.experimental.authInterrupts},cacheComponents:!!x.cacheComponents,supportsDynamicResponse:M,incrementalCache:T,cacheLifeProfiles:x.cacheLife,waitUntil:c.waitUntil,onClose:a=>{b.on("close",a)},onAfterTaskError:void 0,onInstrumentationRequestError:(b,c,d,e)=>B.onRequestError(a,b,d,e,C)},sharedContext:{buildId:g,deploymentId:v}},V=new l.NodeNextRequest(a),W=new l.NodeNextResponse(b),X=m.NextRequestAdapter.fromNodeNextRequest(V,(0,m.signalFromNodeResponse)(b));try{let e,g=async a=>B.handle(X,U).finally(()=>{if(!a)return;a.setAttributes({"http.status_code":b.statusCode,"next.rsc":!1});let c=P.getRootSpanAttributes();if(!c)return;if(c.get("next.span_type")!==n.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${c.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let f=c.get("next.route");if(f){let b=`${O} ${f}`;a.setAttributes({"next.route":f,"http.route":f,"next.span_name":b}),a.updateName(b),e&&e!==a&&(e.setAttribute("http.route",f),e.updateName(b))}else a.updateName(`${O} ${d}`)}),h=async e=>{var h,i;let j=async({previousCacheEntry:f})=>{try{if(!S&&D&&E&&!f)return b.statusCode=404,b.setHeader("x-nextjs-cache","REVALIDATED"),b.end("This page could not be found"),null;let d=await g(e);a.fetchMetrics=U.renderOpts.fetchMetrics;let h=U.renderOpts.pendingWaitUntil;h&&c.waitUntil&&(c.waitUntil(h),h=void 0);let i=U.renderOpts.collectedTags;if(!J)return await (0,p.I)(V,W,d,U.renderOpts.pendingWaitUntil),null;{let a=await d.blob(),b=(0,q.toNodeOutgoingHttpHeaders)(d.headers);i&&(b[s.NEXT_CACHE_TAGS_HEADER]=i),!b["content-type"]&&a.type&&(b["content-type"]=a.type);let c=void 0!==U.renderOpts.collectedRevalidate&&!(U.renderOpts.collectedRevalidate>=s.INFINITE_CACHE)&&U.renderOpts.collectedRevalidate,e=void 0===U.renderOpts.collectedExpire||U.renderOpts.collectedExpire>=s.INFINITE_CACHE?void 0:U.renderOpts.collectedExpire;return{value:{kind:u.CachedRouteKind.APP_ROUTE,status:d.status,body:Buffer.from(await a.arrayBuffer()),headers:b},cacheControl:{revalidate:c,expire:e}}}}catch(b){throw(null==f?void 0:f.isStale)&&await B.onRequestError(a,b,{routerKind:"App Router",routePath:d,routeType:"route",revalidateReason:(0,o.c)({isStaticGeneration:N,isOnDemandRevalidate:D})},!1,C),b}},k=await B.handleResponse({req:a,nextConfig:x,cacheKey:L,routeKind:f.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:A,isRoutePPREnabled:!1,isOnDemandRevalidate:D,revalidateOnlyGenerated:E,responseGenerator:j,waitUntil:c.waitUntil,isMinimalMode:S});if(!J)return null;if((null==k||null==(h=k.value)?void 0:h.kind)!==u.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==k||null==(i=k.value)?void 0:i.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});S||b.setHeader("x-nextjs-cache",D?"REVALIDATED":k.isMiss?"MISS":k.isStale?"STALE":"HIT"),z&&b.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let l=(0,q.fromNodeOutgoingHttpHeaders)(k.value.headers);return S&&J||l.delete(s.NEXT_CACHE_TAGS_HEADER),!k.cacheControl||b.getHeader("Cache-Control")||l.get("Cache-Control")||l.set("Cache-Control",(0,r.getCacheControlHeader)(k.cacheControl)),await (0,p.I)(V,W,new Response(k.value.body,{headers:l,status:k.value.status||200})),null};R&&Q?await h(Q):(e=P.getActiveScopeSpan(),await P.withPropagatedContext(a.headers,()=>P.trace(n.BaseServerSpan.handleRequest,{spanName:`${O} ${d}`,kind:i.SpanKind.SERVER,attributes:{"http.method":O,"http.target":a.url}},h),void 0,!R))}catch(b){if(b instanceof t.NoFallbackError||await B.onRequestError(a,b,{routerKind:"App Router",routePath:I,routeType:"route",revalidateReason:(0,o.c)({isStaticGeneration:N,isOnDemandRevalidate:D})},!1,C),J)throw b;return await (0,p.I)(V,W,new Response(null,{status:500})),null}}},76760:a=>{"use strict";a.exports=require("node:path")},77598:a=>{"use strict";a.exports=require("node:crypto")},78335:()=>{},81115:a=>{"use strict";a.exports=require("constants")},82996:(a,b,c)=>{"use strict";c.d(b,{t:()=>d});class d{adapter;data;constructor(a,b){!function(a,b){if(void 0===a)throw Error("lowdb: missing adapter");if(void 0===b)throw Error("lowdb: missing default data")}(a,b),this.adapter=a,this.data=b}async read(){let a=await this.adapter.read();a&&(this.data=a)}async write(){this.data&&await this.adapter.write(this.data)}async update(a){a(this.data),await this.write()}}},86439:a=>{"use strict";a.exports=require("next/dist/shared/lib/no-fallback-error.external")},94735:a=>{"use strict";a.exports=require("events")},96487:()=>{}};var b=require("../../../../webpack-runtime.js");b.C(a);var c=b.X(0,[4741,1813,7502,9718],()=>b(b.s=74600));module.exports=c})();