"use strict";(()=>{var a={};a.id=8273,a.ids=[8273],a.modules={261:a=>{a.exports=require("next/dist/shared/lib/router/utils/app-paths")},1932:a=>{a.exports=require("url")},3295:a=>{a.exports=require("next/dist/server/app-render/after-task-async-storage.external.js")},4573:a=>{a.exports=require("node:buffer")},10846:a=>{a.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},19771:a=>{a.exports=require("process")},21820:a=>{a.exports=require("os")},27910:a=>{a.exports=require("stream")},28354:a=>{a.exports=require("util")},29021:a=>{a.exports=require("fs")},29294:a=>{a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},33873:a=>{a.exports=require("path")},34631:a=>{a.exports=require("tls")},41204:a=>{a.exports=require("string_decoder")},44870:a=>{a.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},46293:a=>{a.exports=require("sql.js")},53053:a=>{a.exports=require("node:diagnostics_channel")},55511:a=>{a.exports=require("crypto")},63033:a=>{a.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},64939:a=>{a.exports=import("pg")},66136:a=>{a.exports=require("timers")},73024:a=>{a.exports=require("node:fs")},74075:a=>{a.exports=require("zlib")},76760:a=>{a.exports=require("node:path")},77598:a=>{a.exports=require("node:crypto")},79428:a=>{a.exports=require("buffer")},80099:a=>{a.exports=require("node:sqlite")},81787:a=>{a.exports=require("bun:sqlite")},86439:a=>{a.exports=require("next/dist/shared/lib/no-fallback-error.external")},87550:a=>{a.exports=require("better-sqlite3")},91645:a=>{a.exports=require("net")},94735:a=>{a.exports=require("events")},97242:(a,b,c)=>{c.d(b,{Ws:()=>q,_3:()=>s,nv:()=>r});var d=c(29021),e=c.n(d),f=c(33873),g=c.n(f),h=c(45903);function i(a,b,c=null){let d=Number(a);if(!Number.isFinite(d)||d<0)return b;let e=Math.floor(d);return c?Math.min(e,c):e}function j(a){return String(a||"").trim()}async function k(){let a=(0,h.I6)(await (0,h.L7)());return a.sqlitePath||(a.sqlitePath=g().join(process.env.DATA_DIR||"/var/lib/9router","logs","promptLogs.sqlite")),a}async function l(a){try{let b=await Promise.resolve().then(c.t.bind(c,87550,23)),d=new(b.default||b)(a);return d.pragma("busy_timeout = 5000"),{all:(a,b={})=>d.prepare(a).all(b),get:(a,b={})=>d.prepare(a).get(b),run:(a,b={})=>d.prepare(a).run(b),close:()=>d.close()}}catch{let b=new(await Promise.resolve().then(c.t.bind(c,80099,23))).DatabaseSync(a);return b.exec("PRAGMA busy_timeout = 5000"),{all:(a,c={})=>b.prepare(a).all(c),get:(a,c={})=>b.prepare(a).get(c),run:(a,c={})=>b.prepare(a).run(c),close:()=>b.close()}}}async function m(a){let b=new(await Promise.resolve().then(c.bind(c,64939))).Client({host:a.host,port:Number(a.port||5432),database:a.database,user:a.username,password:a.password,ssl:!!a.ssl&&{rejectUnauthorized:!1}});return await b.connect(),{query:async(a,c=[])=>(await b.query(a,c)).rows,queryOne:async(a,c=[])=>(await b.query(a,c)).rows[0]||null,async exec(a,c=[]){await b.query(a,c)},async close(){await b.end()}}}async function n(a){let b=await c.e(8491).then(c.t.bind(c,38491,19)),d=await b.createConnection({host:a.host,port:Number(a.port||3306),database:a.database,user:a.username,password:a.password,ssl:a.ssl?{}:void 0,dateStrings:!0});return{async query(a,b=[]){let[c]=await d.query(a,b);return c},async queryOne(a,b=[]){let[c]=await d.query(a,b);return c[0]||null},async exec(a,b=[]){await d.query(a,b)},async close(){await d.end()}}}async function o(a,b){if(!e().existsSync(a.sqlitePath))return{rows:[],total:0,models:[],stages:[],missing:!0,dbInfo:{type:"sqlite",sqlitePath:a.sqlitePath}};let c=await l(a.sqlitePath);try{let d,e,{clause:f,params:g}=(d=[],e={limit:b.limit,offset:b.offset},b.keyword&&(d.push(`(
      prompt_text LIKE @keyword
      OR response_text LIKE @keyword
      OR error_text LIKE @keyword
      OR model LIKE @keyword
      OR endpoint LIKE @keyword
      OR provider_url LIKE @keyword
      OR provider LIKE @keyword
      OR account_name LIKE @keyword
      OR connection_id LIKE @keyword
      OR display_model LIKE @keyword
      OR session_id LIKE @keyword
      OR client_ip LIKE @keyword
      OR client_host LIKE @keyword
      OR client_user_agent LIKE @keyword
      OR source_tool LIKE @keyword
      OR source_tool_label LIKE @keyword
      OR source_host LIKE @keyword
    )`),e.keyword=`%${b.keyword}%`),b.model&&(d.push("(model = @model OR display_model = @model)"),e.model=b.model),b.stage&&(d.push("stage = @stage"),e.stage=b.stage),b.sessionId&&(d.push("session_id = @sessionId"),e.sessionId=b.sessionId),b.clientIp&&(d.push("client_ip LIKE @clientIp"),e.clientIp=`%${b.clientIp}%`),b.sourceTool&&(d.push("(source_tool LIKE @sourceTool OR source_tool_label LIKE @sourceTool OR source_host LIKE @sourceTool)"),e.sourceTool=`%${b.sourceTool}%`),b.dateFrom&&(d.push("created_at >= @dateFrom"),e.dateFrom=b.dateFrom),b.dateTo&&(d.push("created_at <= @dateTo"),e.dateTo=b.dateTo),{clause:d.length?`WHERE ${d.join(" AND ")}`:"",params:e}),h=c.get(`SELECT COUNT(*) AS count FROM prompt_logs ${f}`,g)?.count||0,i=c.all(`
      SELECT
        id,
        created_at,
        session_id,
        source_format,
        target_format,
        model,
        endpoint,
        stage,
        provider_url,
        provider,
        account_name,
        connection_id,
        display_model,
        client_ip,
        client_port,
        client_user_agent,
        client_host,
        source_tool,
        source_tool_label,
        source_host,
        substr(coalesce(prompt_text,''), 1, 900) AS prompt_preview,
        length(coalesce(prompt_text,'')) AS prompt_length,
        substr(coalesce(response_text,''), 1, 400) AS response_preview,
        status_code,
        error_text
      FROM prompt_logs
      ${f}
      ORDER BY created_at DESC
      LIMIT @limit OFFSET @offset
      `,g),j=c.all("SELECT DISTINCT COALESCE(NULLIF(display_model, ''), model) AS model FROM prompt_logs WHERE model IS NOT NULL AND model <> '' ORDER BY model LIMIT 300").map(a=>a.model),k=c.all("SELECT DISTINCT stage FROM prompt_logs WHERE stage IS NOT NULL AND stage <> '' ORDER BY stage LIMIT 100").map(a=>a.stage);return{rows:i,total:h,models:j,stages:k,dbInfo:{type:"sqlite",sqlitePath:a.sqlitePath}}}finally{c.close()}}async function p(a,b){let c=a.type,d="postgres"===c?await m(a):await n(a);try{let e=function(a,b){let c=[],d=[],e=a=>(d.push(a),"postgres"===b)?`$${d.length}`:"?",f="postgres"===b?"ILIKE":"LIKE";if(a.keyword){let b=e(`%${a.keyword}%`);c.push(`(
      prompt_text ${f} ${b}
      OR response_text ${f} ${b}
      OR error_text ${f} ${b}
      OR model ${f} ${b}
      OR endpoint ${f} ${b}
      OR provider_url ${f} ${b}
      OR provider ${f} ${b}
      OR account_name ${f} ${b}
      OR connection_id ${f} ${b}
      OR display_model ${f} ${b}
      OR session_id ${f} ${b}
      OR client_ip ${f} ${b}
      OR client_host ${f} ${b}
      OR client_user_agent ${f} ${b}
      OR source_tool ${f} ${b}
      OR source_tool_label ${f} ${b}
      OR source_host ${f} ${b}
    )`)}if(a.model&&c.push(`(model = ${e(a.model)} OR display_model = ${e(a.model)})`),a.stage&&c.push(`stage = ${e(a.stage)}`),a.sessionId&&c.push(`session_id = ${e(a.sessionId)}`),a.clientIp&&c.push(`client_ip ${f} ${e(`%${a.clientIp}%`)}`),a.sourceTool){let b=e(`%${a.sourceTool}%`);c.push(`(source_tool ${f} ${b} OR source_tool_label ${f} ${b} OR source_host ${f} ${b})`)}return a.dateFrom&&c.push(`created_at >= ${e(a.dateFrom)}`),a.dateTo&&c.push(`created_at <= ${e(a.dateTo)}`),{clause:c.length?`WHERE ${c.join(" AND ")}`:"",params:d,add:e}}(b,c),f=[...e.params],g=await d.queryOne(`SELECT COUNT(*) AS count FROM prompt_logs ${e.clause}`,f),h=e.add(b.limit),i=e.add(b.offset),j="postgres"===c?"LEFT(coalesce(prompt_text,''), 900)":"SUBSTRING(coalesce(prompt_text,''), 1, 900)",k="postgres"===c?"char_length(coalesce(prompt_text,''))":"CHAR_LENGTH(coalesce(prompt_text,''))",l="postgres"===c?"LEFT(coalesce(response_text,''), 400)":"SUBSTRING(coalesce(response_text,''), 1, 400)",m=await d.query(`
      SELECT
        id,
        created_at,
        session_id,
        source_format,
        target_format,
        model,
        endpoint,
        stage,
        provider_url,
        provider,
        account_name,
        connection_id,
        display_model,
        client_ip,
        client_port,
        client_user_agent,
        client_host,
        source_tool,
        source_tool_label,
        source_host,
        ${j} AS prompt_preview,
        ${k} AS prompt_length,
        ${l} AS response_preview,
        status_code,
        error_text
      FROM prompt_logs
      ${e.clause}
      ORDER BY created_at DESC
      LIMIT ${h} OFFSET ${i}
      `,e.params),n=(await d.query("SELECT DISTINCT COALESCE(NULLIF(display_model, ''), model) AS model FROM prompt_logs WHERE model IS NOT NULL AND model <> '' ORDER BY model LIMIT 300")).map(a=>a.model),o=(await d.query("SELECT DISTINCT stage FROM prompt_logs WHERE stage IS NOT NULL AND stage <> '' ORDER BY stage LIMIT 100")).map(a=>a.stage);return{rows:m,total:Number(g?.count||0),models:n,stages:o,dbInfo:{type:a.type,host:a.host,database:a.database}}}finally{await d.close()}}async function q(a={}){let b=await k(),c=function(a={}){return{keyword:j(a.keyword),model:j(a.model),stage:j(a.stage),sessionId:j(a.sessionId),clientIp:j(a.clientIp),sourceTool:j(a.sourceTool),dateFrom:j(a.dateFrom),dateTo:j(a.dateTo),limit:i(a.limit,50,200),offset:i(a.offset,0)}}(a);if(!b.enabled)return{disabled:!0,rows:[],total:0,models:[],stages:[],dbInfo:{type:b.type}};if("sqlite"===b.type)return o(b,c);if("postgres"===b.type||"mysql"===b.type)return p(b,c);throw Error(`Unsupported prompt log database type: ${b.type}`)}async function r(a){let b=await k();if("sqlite"===b.type){if(!e().existsSync(b.sqlitePath))return null;let c=await l(b.sqlitePath);try{return c.get("SELECT * FROM prompt_logs WHERE id = @id",{id:a})||null}finally{c.close()}}if("postgres"===b.type){let c=await m(b);try{return await c.queryOne("SELECT * FROM prompt_logs WHERE id = $1",[a])}finally{await c.close()}}if("mysql"===b.type){let c=await n(b);try{return await c.queryOne("SELECT * FROM prompt_logs WHERE id = ?",[a])}finally{await c.close()}}throw Error(`Unsupported prompt log database type: ${b.type}`)}async function s(a){let b=await k();if("sqlite"===b.type){if(!e().existsSync(b.sqlitePath))return{changed:0};let c=await l(b.sqlitePath);try{return{changed:c.run("DELETE FROM prompt_logs WHERE id = @id",{id:a}).changes||0}}finally{c.close()}}if("postgres"===b.type){let c=await m(b);try{let b=await c.queryOne("SELECT COUNT(*) AS count FROM prompt_logs WHERE id = $1",[a]);return await c.exec("DELETE FROM prompt_logs WHERE id = $1",[a]),{changed:Number(b?.count||0)}}finally{await c.close()}}if("mysql"===b.type){let c=await n(b);try{return await c.exec("DELETE FROM prompt_logs WHERE id = ?",[a]),{changed:1}}finally{await c.close()}}throw Error(`Unsupported prompt log database type: ${b.type}`)}},97742:(a,b,c)=>{c.r(b),c.d(b,{handler:()=>D,patchFetch:()=>C,routeModule:()=>y,serverHooks:()=>B,workAsyncStorage:()=>z,workUnitAsyncStorage:()=>A});var d={};c.r(d),c.d(d,{GET:()=>x});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(97242);async function x(a){try{let b=new URL(a.url).searchParams,c=await (0,w.Ws)({keyword:b.get("keyword")||"",model:b.get("model")||"",stage:b.get("stage")||"",sourceTool:b.get("sourceTool")||"",clientIp:b.get("clientIp")||"",sessionId:b.get("sessionId")||"",dateFrom:b.get("dateFrom")||"",dateTo:b.get("dateTo")||"",limit:b.get("limit")||"50",offset:b.get("offset")||"0"});return v.NextResponse.json(c)}catch(a){return console.log("Failed to list prompt logs:",a.message),v.NextResponse.json({error:a.message||"Failed to list prompt logs"},{status:500})}}let y=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/dashboard/prompt-logs/route",pathname:"/api/dashboard/prompt-logs",filename:"route",bundlePath:"app/api/dashboard/prompt-logs/route"},distDir:".next-cli-build",relativeProjectDir:"",resolvedPagePath:"D:\\OneDrive - homeviet\\9router\\src\\app\\api\\dashboard\\prompt-logs\\route.js",nextConfigOutput:"standalone",userland:d,...{}}),{workAsyncStorage:z,workUnitAsyncStorage:A,serverHooks:B}=y;function C(){return(0,g.patchFetch)({workAsyncStorage:z,workUnitAsyncStorage:A})}async function D(a,b,c){c.requestMeta&&(0,h.setRequestMeta)(a,c.requestMeta),y.isDev&&(0,h.addRequestMeta)(a,"devRequestTimingInternalsEnd",process.hrtime.bigint());let d="/api/dashboard/prompt-logs/route";"/index"===d&&(d="/");let e=await y.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:z,isDraftMode:A,prerenderManifest:B,routerServerContext:C,isOnDemandRevalidate:D,revalidateOnlyGenerated:E,resolvedPathname:F,clientReferenceManifest:G,serverActionsManifest:H}=e,I=(0,k.normalizeAppPath)(d),J=!!(B.dynamicRoutes[I]||B.routes[F]),K=async()=>((null==C?void 0:C.render404)?await C.render404(a,b,z,!1):b.end("This page could not be found"),null);if(J&&!A){let a=!!B.routes[F],b=B.dynamicRoutes[I];if(b&&!1===b.fallback&&!a){if(x.adapterPath)return await K();throw new t.NoFallbackError}}let L=null;!J||y.isDev||A||(L="/index"===(L=F)?"/":L);let M=!0===y.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 y.getIncrementalCache(a,x,B,S);null==T||T.resetRequestCache(),globalThis.__incrementalCache=T;let U={params:w,previewProps:B.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)=>y.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=>y.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 y.onRequestError(a,b,{routerKind:"App Router",routePath:d,routeType:"route",revalidateReason:(0,o.c)({isStaticGeneration:N,isOnDemandRevalidate:D})},!1,C),b}},k=await y.handleResponse({req:a,nextConfig:x,cacheKey:L,routeKind:f.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:B,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"),A&&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 y.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}}}};var b=require("../../../../webpack-runtime.js");b.C(a);var c=b.X(0,[4741,1813,4884,7197],()=>b(b.s=97742));module.exports=c})();