import{AsyncApiRealmAPI as y}from"@redocly/realm-asyncapi-sdk";import{envConfig as o}from"../../../config/env-config.js";import{getClientIp as R}from"../../utils/get-client-ip.js";import{getAttributesStringValue as I,mergeAttributes as h,toAttribute as O}from"./otlp.js";const C=o.OTEL_TRACES_URL||"https://otel.cloud.redocly.com/v1/traces",A="cloudevents.event_session_id";class w extends y.OtelClient{initTracer(){}}let d=null;function E(){return d||(d=new w,d.init({collectorTraceUrl:void 0,serviceName:"realm-ui",serviceVersion:"1.0",isProd:o.isProductionEnv,version:"1.0",tracerName:"attribute-processor"})),d}async function $(e){const t=await e.req.json();return t.resourceSpans?.length&&(N(t,j(e)),await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})),e.newResponse(null,200)}function N(e,t){for(const s of e.resourceSpans){const r=s.resource.attributes.find(u=>u.key==="session_id");if(!r)continue;const i=I(r);if(!i)continue;const l=L(t.userId,i),_=new Date,v={organizationId:o.ORGANIZATION_ID||"",organizationSlug:o.ORGANIZATION_SLUG||"",projectId:o.PROJECT_ID||"",projectSlug:o.PROJECT_SLUG||"",env:o.REDOCLY_ENV||"",source:"urn:redocly:realm:ui",actor:{id:l.id,object:l.object,uri:l.uri},clientIp:t.clientIp,userAgent:t.userAgent},c=(u,n)=>{const a=u.attributes.find(f=>f.key===n);return a?I(a):""};for(const u of s.scopeSpans)for(const n of u.spans){if(!n.name.startsWith("event.")||n.name==="event.undefined")continue;const a=c(n,"cloudevents.event_spec_version"),f=c(n,"cloudevents.event_object"),g=c(n,"cloudevents.event_data_content_type"),b=c(n,"cloudevents.event_origin"),p=c(n,"cloudevents.event_time"),m=p?new Date(p):_,S={...v,id:c(n,"cloudevents.event_id"),specversion:a,type:n.name.slice(6),object:f,datacontenttype:g,time:m,origin:b},T=E().processAttributes(S,m);h(n,T,{overwrite:!0}),P(n,t.sessionId)}}}function P(e,t){const s=e.attributes.findIndex(i=>i.key===A),r=O(A,t);r?s===-1?e.attributes.push(r):e.attributes[s]=r:s!==-1&&e.attributes.splice(s,1)}function j(e){const t=e.get("auth")?.claims?.id||e.get("auth")?.claims?.sub,s=e.get("auth")?.claims?.sessionId,r=R(e.req.raw)||e.req.raw.context?.remoteAddr?.hostname,i=e.req.raw.headers.get("user-agent");return{userId:t,sessionId:s||void 0,clientIp:r??void 0,userAgent:i??void 0}}function L(e,t){if(e)return{id:e,object:"user",uri:`${o.MAIN_API_URL}/users/${e}`};const s=t.replace("ses_","ann_");return{id:s,object:"anonymous",uri:`${o.MAIN_API_URL}/anonymous/${s}`}}export{$ as otelTracesHandler,L as toActor};
