@stackone/olap 3.3.1 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,17 +1,17 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.defineProperty,__name=(t,n)=>e(t,`name`,{value:n,configurable:!0});let t=require("@stackone/storage"),n=require("@stackone/utils"),r=require("@stackone/redaction"),i=require("@opentelemetry/exporter-trace-otlp-proto"),a=require("@opentelemetry/resources"),o=require("@opentelemetry/sdk-trace-base"),s=require("@opentelemetry/semantic-conventions"),c=require("crypto"),l=require("zod"),u=require("@clickhouse/client");function toArray(e){return e==null?[]:Array.isArray(e)?e:[e]}function toCsvArray(e){return toArray(e).flatMap(e=>e.split(`,`)).map(e=>e.trim()).filter(e=>e.length>0)}function toStatusCodes(e){let t=toArray(e);if(t.length===0)return[];let n=t.map(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length===0?NaN:Number(t)}).filter(e=>Number.isInteger(e)&&e>=-32768&&e<=32767);return n.length>0?n:[-1]}function toClickHouseDate(e){return e?(typeof e==`string`?new Date(e):e).toISOString().replace(`T`,` `).replace(`Z`,``):null}function buildPaginationParams(e,t){let n=Math.min(t??100,1e3);return{limit:n,offset:(Math.max(e??1,1)-1)*n}}function sanitizeOrderDirection(e){return e?.toLowerCase()===`asc`?`ASC`:`DESC`}function sanitizeOrderBy(e,t,n){return e?t[e]??n:n}function buildArrayFilter(e,t,n=`String`){return`({${t}:Array(${n})} = [] OR ${e} IN {${t}:Array(${n})})`}const d=`({authPairsApplied:UInt8} = 0 OR concat(authType, ':', authId) IN {authKeys:Array(String)})`;var InvalidAuthPairError=class extends Error{constructor(e){super(e),this.name=`InvalidAuthPairError`}};const toAuthKey=({authType:e,authId:t})=>{if(e.length===0||t.length===0)throw new InvalidAuthPairError(`Cannot filter on an auth pair with an empty type or id`);if(e.includes(`:`))throw new InvalidAuthPairError(`Cannot filter on auth type "${e}": it contains ":"`);return`${e}:${t}`},toAuthPairParams=e=>({authPairsApplied:e===void 0?0:1,authKeys:(e??[]).map(toAuthKey)}),f={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),p={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},m={Asc:`asc`,Desc:`desc`},h={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},ee={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,AuthType:`authType`,AuthId:`authId`,IsBackground:`isBackground`,PolicyResult:`policyResult`,RiskLevel:`riskLevel`},te={EventType:`eventType`,Action:`action`,Resource:`resource`,Service:`service`,SourceType:`sourceType`,SourceId:`sourceId`,AuthType:`authType`,UserEmail:`userEmail`,StatusCode:`statusCode`,Success:`success`,IsRead:`isRead`,AgentId:`agentId`,TransportType:`transportType`,StreamType:`streamType`},g={actions:[`internal`],steps:[`internal`],unified_requests:[`internal`],provider_requests:[`internal`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===f.Platform,_={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},ne={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},re={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},ie={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},ae=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],oe=[_.Scheduler,_.DataSync,_.DataSyncV2,_.Internal],se=[`data_sync`],ce=[_.DataSync,_.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&ae.includes(e)||t&&oe.includes(t))}function isDataSync(e,t){return!!(e&&se.includes(e)||t&&ce.includes(t))}const le=[`content-type`,`contenttype`],contentTypeOf=e=>String(Object.entries(e??{}).find(([e])=>le.includes(e.toLowerCase()))?.[1]??``).toLowerCase(),parseJson=e=>{try{return{parsed:JSON.parse(e)}}catch{return}},redactBody=(e,t)=>{if(!(0,n.isString)(e))return(0,r.redactFields)(e,r.CensorType.PARTIAL,!0);let i=parseJson(e);return i?redactBody(i.parsed,t):contentTypeOf(t).includes(`application/x-www-form-urlencoded`)?(0,r.redactFormBody)(e,r.CensorType.PARTIAL):e},safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},safeObject=e=>{try{return JSON.stringify(e),e}catch{return{error:`Unserializable payload`}}},hasErrorEntries=e=>(0,n.isMissing)(e)?!1:Array.isArray(e)||(0,n.isString)(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,readStoredLog=async({bucket:e,key:t,description:n,errorCode:r,category:i,logger:a})=>{try{let r=await e.readText(t);if(r===void 0){a?.debug({message:`No ${n} in storage`,category:i});return}return a?.debug({message:`Retrieved ${n} from storage`,category:i}),JSON.parse(r)}catch(e){throw a?.error({message:`Error when getting ${n} from storage`,error:e,code:r,category:i}),e}},writeStoredLog=async({bucket:e,key:t,body:n,ttlTag:r,expiresAt:i,description:a,errorCode:o,category:s,logger:c})=>{try{await e.write(t,n,{contentType:`application/json`,tags:{ttl:r},expiresAt:i})}catch(e){throw c?.error({message:`Failed to write ${a} to storage at ${t}`,error:e,code:o,category:s}),e}},statStoredLog=async({bucket:e,key:t,description:n,errorCode:r,category:i,logger:a})=>{try{let n=await e.stat(t);return n===void 0?{exists:!1}:{exists:!0,expiresAt:n.expiresAt}}catch(e){throw a?.error({message:`Error when checking ${n} in storage`,error:e,code:r,category:i}),e}},v=64*1024,y=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],b=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>(0,n.isObject)(e)?e[t]:void 0,e),withPath=(e,t,r)=>{let[i,...a]=t.split(`.`);if(a.length===0)return{...e,[i]:r};let o=e[i];return(0,n.isObject)(o)?{...e,[i]:withPath(o,a.join(`.`),r)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,t)=>{let{kept:r,total:i}=e.reduce((e,r)=>{if(e.total>t)return e;let i=e.total+(0,n.calculateSize)(r);return i>t?{kept:e.kept,total:i}:{kept:e.kept+1,total:i}},{kept:0,total:0});return i>t?e.slice(0,r):e},fitObject=(e,t)=>{let r=Object.entries(e).map(([e,t])=>({key:e,value:t,size:e.length*2+(0,n.calculateSize)(t)})).sort((e,t)=>e.size-t.size),{kept:i,remaining:a}=r.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:t}),o=r.filter(e=>!i.includes(e.key)),s=o.length===0?0:Math.floor(a/o.length);return Object.fromEntries(r.map(e=>[e.key,i.includes(e.key)?e.value:fitValue(e.value,s)]))},fitValue=(e,t)=>{let r=(0,n.calculateSize)(e);return r<=t?e:((0,n.isString)(e)||Array.isArray(e)||(0,n.isObject)(e)&&!(0,n.isDate)(e))&&t<=0?marker(r):(0,n.isString)(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):(0,n.isObject)(e)&&!(0,n.isDate)(e)?fitObject(e,t):e},payloadFields=e=>y.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!(0,n.isMissing)(e)).map(e=>({...e,size:(0,n.calculateSize)(e.value)})),byRetentionPriority=e=>[...e.filter(e=>b.includes(e.path)),...e.filter(e=>!b.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*v;return n.size<=t.remaining-i?{paths:[...t.paths,n.path],remaining:t.remaining-n.size}:t},{paths:[],remaining:t}).paths,truncateToLimit=(e,t)=>{let n=byRetentionPriority(payloadFields(e)),r=keptWholePaths(n,t),i=n.filter(e=>r.includes(e.path)).reduce((e,t)=>e+t.size,0),a=n.filter(e=>!r.includes(e.path)),o=a.length===0?0:Math.max(v,Math.floor((t-i)/a.length)),s=a.map(e=>({...e,fitted:fitValue(e.value,o)})).filter(e=>e.fitted!==e.value);return{data:s.reduce((e,t)=>withPath(e,t.path,t.fitted),e),truncatedPaths:s.map(e=>e.path)}},withoutPayloads=e=>y.reduce((e,t)=>readPath(e,t)===void 0?e:withPath(e,t,void 0),e),isErrorResult=e=>e.success===!1||e.hasStepErrors===!0||(e.statusCode??0)>=400||hasErrorEntries(e.errors),ue=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],de=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],fe=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],parseActionUrl=e=>e.startsWith(`/`)?new URL(e,`http://path.invalid`):new URL(e),platformKey=(e,t)=>`${e}/platform/${t}.json`,x=`AdvancedSink`,errorName=e=>e instanceof Error?e.name:`non-Error thrown`;var AdvancedSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n,this.#a=t?.piiRedaction}async initialize(){if(this.#t){this.#i?.warning({message:`No storage provided, advanced sink will not function`,category:x});return}try{await this.#a?.warmupTier2()}catch(e){this.#i?.warning({message:`PII Tier 2 warmup failed (${errorName(e)}), content scrub will fall back to structural redaction only`,category:`AdvancedSink`,code:`AdvancedSinkPiiWarmupError`})}}async scrubPii(e,t){if(!t?.piiRedactionEnabled||!this.#a||this.truncationMode(t)===`drop`&&(0,n.calculateSize)(e)>this.#n)return e;try{return await this.#a.scrubObject(e)}catch(t){return this.#i?.warning({message:`PII content scrub failed (${errorName(t)}), storing structurally-redacted body only`,category:`AdvancedSink`,code:`AdvancedSinkPiiScrubError`}),e}}requireBucket(){if(!this.#e)throw Error(`Advanced sink bucket is not configured`);return this.#e}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:i,result:a}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(i.mode,i.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&a.success&&!a.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${i.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(i.mode,i.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${i.mode}`,category:`AdvancedSink`}),n.push(null);continue}let[e,o,s]=await Promise.all([this.scrubPii(redactBody(i.body,i.headers),t),this.scrubPii((0,r.redactFields)(i.queryParams,r.CensorType.PARTIAL,!0),t),this.scrubPii((0,r.redactFields)(i.pathParams,r.CensorType.PARTIAL,!0),t)]),c={...i,body:e,queryParams:o,pathParams:s},l={...a,body:await this.scrubPii(redactBody(a.body??a.refusal,a.headers),t)},u=this.createActionItem(c,l,t),d=await this.send(u,t?.ttl);n.push(d)}return n}async sendStep(e,t,n){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode,e.actionSourceType))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0&&t.success!==!1&&!hasErrorEntries(t.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let i={...e,inputs:await this.scrubPii((0,r.redactFields)(e.inputs,r.CensorType.PARTIAL,!0),n)},a={...t,outputs:await this.scrubPii((0,r.redactFields)(t.outputs,r.CensorType.PARTIAL,!0),n),errors:await this.scrubPii((0,r.redactFields)(t.errors,r.CensorType.PARTIAL,!0),n)},o=this.createStepItem(i,a,n);try{return await this.send(o,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(redactBody(e.body,e.headers),n)},i={...t,body:await this.scrubPii(redactBody(t.body,t.headers),n)},a=this.createUnifiedItem(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(redactBody(e.body,e.headers),n)},i={...t,body:await this.scrubPii(redactBody(t.body,t.headers),n)},a=this.createProviderItem(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){return this.read(`${e}/${t}/${n}/${n}.json`,`advanced log for actionRunId ${n}`)}async getStep(e,t,n,r){return this.read(`${e}/${t}/${n}/steps/${r}.json`,`step log for actionRunId ${n} stepIndex ${r}`)}async getUnified(e,t,n){return this.read(`${e}/${t}/${n}/${n}.json`,`advanced log for requestId ${n}`)}async getProvider(e,t,n,r){return this.read(`${e}/${t}/${n}/provider/${r}.json`,`provider log for requestId ${n} id ${r}`)}async read(e,t){if(this.#t){this.#i?.warning({message:`No storage available, cannot get ${t} from advanced sink`,category:x});return}return readStoredLog({bucket:this.requireBucket(),key:e,description:t,errorCode:`AdvancedLogReadError`,category:x,logger:this.#i})}async send(e,t){if(this.#t)throw Error(`No storage available, cannot send to advanced sink`);let n=this.requireBucket(),r=t===1?`1d`:t===7?`7d`:`30d`,i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);return this.#i?.debug({message:`Storing advanced log in bucket ${n.name} with ttl of ${r}`,category:x,context:{bucket:n.name,key:e.key,ttlTag:r,expiresAt:a.toISOString()}}),await writeStoredLog({bucket:n,key:e.key,body:e.body,ttlTag:r,expiresAt:a,description:`advanced logs`,errorCode:`AdvancedLogWriteError`,category:x,logger:this.#i}),{expiresAt:a}}async getObjectExpiry(e){return this.#t?(this.#i?.warning({message:`No storage available, cannot check object expiry`,category:x}),{exists:!1}):statStoredLog({bucket:this.requireBucket(),key:e,description:`advanced log at ${e}`,errorCode:`AdvancedLogHeadError`,category:x,logger:this.#i})}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async sendPlatform(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;if(e.organizationId===void 0)return this.#i?.warning({message:`Skipping platform advanced log: no organization to key it under`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType}}),null;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformItem(e,t,e.organizationId,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send platform to advanced sink`,error:t,code:`AdvancedPlatformWriteError`,category:`AdvancedSink`,context:{eventId:e.eventId}}),null}}async getPlatform(e,t){return this.read(platformKey(e,t),`platform advanced log for eventId ${t}`)}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeActionResult(e,t,i,this.#n,this.truncationMode(n))}}createStepItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeStepResult(e,t,i,this.#n,this.truncationMode(n))}}createPlatformItem(e,t,n,r){let i=platformKey(n,e.eventId),a=Math.floor(Date.now()/1e3)+(r??30)*24*60*60;return{key:i,body:this.serializePlatformAdvanced(t,a)}}serializePlatformAdvanced(e,t){let i=(0,r.redactFields)(e.data,r.CensorType.PARTIAL,!0),a={...e.metadata,expirationTime:t,sizeBytes:(0,n.calculateSize)(i)};return this.stringifyPlatform({data:i,metadata:a},a)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeUnifiedResult(e,t,i,this.#n,this.truncationMode(n))}}createProviderItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeProviderResult(e,t,i,this.#n,this.truncationMode(n))}}serializeActionResult(e,t,i,a,o){let s=(0,r.redactHeaders)(e.headers,r.CensorType.PARTIAL),c=(0,r.redactHeaders)(t.headers,r.CensorType.PARTIAL),l=this.processContent(s,e.body,`upload`),u=this.processContent(c,t.body,`download`),d=e.isBackground??isBackgroundLog(e.mode,e.sourceType),f=e.url,p={};if(e.url)try{f=(0,r.redactUrl)(e.url,r.CensorType.PARTIAL);let t=parseActionUrl(f);p=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let m={...p,...(0,n.isObject)(e.queryParams)?e.queryParams:{}},h={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(s),url:{url:f,path:e.pathParams,queryParams:m},body:l},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(c),body:u},...d?{isBackgroundLog:!0}:{}},metadata:{...d?{isBackgroundLog:!0}:{},expirationTime:i}};return this.serializeAndLimit(h,a,isErrorResult(t),o)}serializeStepResult(e,t,n,r,i){let a={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,t,n,i,a){let o=(0,r.redactHeaders)(e.headers,r.CensorType.PARTIAL),s=(0,r.redactHeaders)(t.headers,r.CensorType.PARTIAL),c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),d=`/`,f=e.url,p={};if(e.url)try{f=(0,r.redactUrl)(e.url,r.CensorType.PARTIAL);let t=new URL(f);d=t.pathname,p=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let m={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:f,path:d,queryParams:p},body:c},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:l}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(m,i,isErrorResult(t),a)}serializeProviderResult(e,t,n,i,a){let o=(0,r.redactHeaders)(e.headers,r.CensorType.PARTIAL),s=(0,r.redactHeaders)(t.headers,r.CensorType.PARTIAL),c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u,d=``,f=`/`,p={};if(e.url)try{u=(0,r.redactUrl)(e.url,r.CensorType.PARTIAL);let t=new URL(u);d=t.hostname,f=t.pathname,p=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let m={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:u,hostname:d,path:f,queryParams:p},body:c},response:{statusCode:t.statusCode,headers:this.filterHeaders(s),body:l}},metadata:{expirationTime:n}};return this.serializeAndLimit(m,i,isErrorResult(t),a)}serializeAndLimit(e,t,r,i){let a=(0,n.calculateSize)(e);if(i===`complete`)return this.stringifyLog(e,{sizeBytes:a});let o=r&&i===`truncate`?t*this.#r:t;if(a<=o)return this.stringifyLog(e,{sizeBytes:a});if(i===`drop`)return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, dropping payload`,category:`AdvancedSink`,code:`AdvancedLogTooLarge`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r}}),this.stringifyLog({...e,data:{outputs:{error:`Error.TOO_LARGE`}}},{sizeBytes:a,maxSizeBytes:o,truncated:!0});let{data:s,truncatedPaths:c}=truncateToLimit(e,o);return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, storing truncated payload`,category:`AdvancedSink`,code:`AdvancedLogTruncated`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r,truncatedPaths:c}}),this.stringifyLog(s,{sizeBytes:a,maxSizeBytes:o,truncated:!0})}stringifyLog(e,t){let n={...e,metadata:{...e.metadata,...t}};try{return JSON.stringify(n)}catch{return this.#i?.warning({message:`Advanced log payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedLogUnserializable`}),JSON.stringify(withoutPayloads(n))}}filterHeaders(e){if(!e)return;let t={},n=ue.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return de.includes(i)||fe.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!(0,n.isMissing)(e)){if(!(0,n.isString)(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};const S=2e3,settleWithin=(e,t,n)=>new Promise(r=>{let i=setTimeout(()=>r(n),t);i.unref?.(),e.then(e=>{clearTimeout(i),r(e)})});function defaultProviderFactory(e){let t=new i.OTLPTraceExporter({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`},timeoutMillis:S}),n={[s.ATTR_SERVICE_NAME]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new o.BasicTracerProvider({resource:(0,a.resourceFromAttributes)(n),spanProcessors:[new o.BatchSpanProcessor(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;#i=new Set;#a;#o=!1;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(!this.#r)return;if(this.#i.size>=4){this.#t?.debug({message:`Logfire exports at the limit, leaving spans queued for the next flush`,category:`DatasetsSink`,context:{maxExportsInFlight:4}});return}let e=this.#s()?S:50;await settleWithin(this.#c(this.#r).then(()=>!0),e,!1)||this.#t?.debug({message:`Logfire export still running, not waiting for it`,category:`DatasetsSink`,context:{flushTimeoutMs:e}})}async drain(e=4e3){if(!this.#r)return;let t=[...this.#i,this.#c(this.#r)];await settleWithin(Promise.all(t).then(()=>!0),e,!1)||this.#t?.warning({message:`Logfire exports still running at shutdown, their spans may be lost`,code:`LogfireDrainTimeout`,category:`DatasetsSink`,context:{timeoutMs:e}})}#s(){return this.#o?!1:this.#a===void 0||Date.now()-this.#a>3e5}#c(e){let t=Date.now(),n=!1,r=setTimeout(()=>{n=Date.now()-t>=2250},S);r.unref?.();let i=new Promise(t=>t(e.forceFlush())).then(()=>{this.#a=Date.now(),this.#o=!1},e=>this.#l(e,Date.now()-t,n));return this.#i.add(i),i.finally(()=>{clearTimeout(r),this.#i.delete(i)}),i}#l(e,t,n){if(n){this.#a=void 0,this.#o=!1,this.#t?.debug({message:`Logfire export failed after the process was frozen`,category:`DatasetsSink`,context:{elapsedMs:t,exportTimeoutMs:S,error:String(e)}});return}this.#o=!0,this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`,context:{elapsedMs:t}})}},DatasetsSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async close(e){this.#a??=this.#r.drain?.(e),await this.#a}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let r=0;for(let{input:i,result:a}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,includeBackground:t.includeBackground}}),(0,n.isMissing)(i.body)&&(0,n.isMissing)(a.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if(isBackgroundLog(i.mode,i.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${i.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(i,a);if((0,n.isMissing)(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if((0,n.exceedsSize)(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}this.send(i,e),r++}r>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${r} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let r=(0,n.isMissing)(e.body)?void 0:(0,n.extractSchema)(e.body),i=(0,n.isMissing)(t.body)?void 0:(0,n.extractSchema)(t.body);if(!((0,n.isMissing)(r)&&(0,n.isMissing)(i)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:r,result:i}}}};const C=`DefenderSink`;var DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#e)throw Error(`Defender sink bucket is not configured`);return this.#e}async initialize(){if(this.#t){this.#r?.warning({message:`No storage provided, defender sink will not function`,category:C});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let r=[];for(let{input:i,result:a}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:C,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:C}),r.push(null);continue}if((0,n.isMissing)(a.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:C,context:{actionRunId:i.actionRunId}}),r.push(null);continue}r.push(await this.send(i,a))}return r}async getAction(e,t,n){if(this.#t){this.#r?.warning({message:`No storage available, cannot get action log from defender sink`,category:C});return}return readStoredLog({bucket:this.requireBucket(),key:defenderKey(e,t,n),description:`defender log for actionRunId ${n}`,errorCode:`DefenderLogReadError`,category:C,logger:this.#r})}async send(e,t){if(this.#t)throw Error(`No storage available, cannot send to defender sink`);let n=this.requireBucket(),r=defenderKey(e.organizationId,e.projectSecureId,e.actionRunId),i=Math.floor(Date.now()/1e3)+this.#n*24*60*60,a=new Date(i*1e3),o=`${this.#n}d`;return this.#r?.debug({message:`Storing defender log in bucket ${n.name} with ${this.#n}-day TTL`,category:C,context:{bucket:n.name,key:r,ttlTag:o,expiresAt:a.toISOString()}}),await writeStoredLog({bucket:n,key:r,body:JSON.stringify(t.defenderContext),ttlTag:o,expiresAt:a,description:`defender log`,errorCode:`DefenderLogWriteError`,category:C,logger:this.#r}),{expiresAt:a}}};const defenderKey=(e,t,n)=>`${e}/${t}/${n}/defender.json`,pe={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},w=`action_logs_filtered`,T=`organizationId.projectSecureId.actionRunId.accountSecureId.actionId.connectorKey.connectorVersion.connectorOwner.connectorProfileId.actionType.mode.category.originOwnerId.originOwnerName.httpMethod.sourceType.sourceId.sourceValue.authType.authId.userAgent.ipAddress.sessionId.agentId.transportType.streamType.policyResult.riskLevel`.split(`.`),E=[...T.map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`isBackground = {isBackground:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),D=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.defineProperty,__name=(t,n)=>e(t,`name`,{value:n,configurable:!0});let t=require("@stackone/utils"),n=require("crypto"),r=require("zod"),i=require("@stackone/redaction"),a=require("@clickhouse/client"),o=require("@stackone/storage"),s=require("@opentelemetry/exporter-trace-otlp-proto"),c=require("@opentelemetry/resources"),l=require("@opentelemetry/sdk-trace-base"),u=require("@opentelemetry/semantic-conventions");function toArray(e){return e==null?[]:Array.isArray(e)?e:[e]}function toCsvArray(e){return toArray(e).flatMap(e=>e.split(`,`)).map(e=>e.trim()).filter(e=>e.length>0)}function toStatusCodes(e){let t=toArray(e);if(t.length===0)return[];let n=t.map(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length===0?NaN:Number(t)}).filter(e=>Number.isInteger(e)&&e>=-32768&&e<=32767);return n.length>0?n:[-1]}function toClickHouseDate(e){return e?(typeof e==`string`?new Date(e):e).toISOString().replace(`T`,` `).replace(`Z`,``):null}function buildPaginationParams(e,t){let n=Math.min(t??100,1e3);return{limit:n,offset:(Math.max(e??1,1)-1)*n}}function sanitizeOrderDirection(e){return e?.toLowerCase()===`asc`?`ASC`:`DESC`}function sanitizeOrderBy(e,t,n){return e?t[e]??n:n}function buildArrayFilter(e,t,n=`String`){return`({${t}:Array(${n})} = [] OR ${e} IN {${t}:Array(${n})})`}const narrowArrayFilter=(e,t)=>{let n=e.length===0?[...t]:t.filter(t=>e.includes(t));return n.length>0?n:void 0},d=`({authPairsApplied:UInt8} = 0 OR concat(authType, ':', authId) IN {authKeys:Array(String)})`;var InvalidAuthPairError=class extends Error{constructor(e){super(e),this.name=`InvalidAuthPairError`}};const toAuthKey=({authType:e,authId:t})=>{if(e.length===0||t.length===0)throw new InvalidAuthPairError(`Cannot filter on an auth pair with an empty type or id`);if(e.includes(`:`))throw new InvalidAuthPairError(`Cannot filter on auth type "${e}": it contains ":"`);return`${e}:${t}`},toAuthPairParams=e=>({authPairsApplied:e===void 0?0:1,authKeys:(e??[]).map(toAuthKey)}),f={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},p={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},m={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},ee={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},te=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],ne=[f.Scheduler,f.DataSync,f.DataSyncV2,f.Internal],re=[`data_sync`],ie=[f.DataSync,f.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&te.includes(e)||t&&ne.includes(t))}function isDataSync(e,t){return!!(e&&re.includes(e)||t&&ie.includes(t))}const ae=[`content-type`,`contenttype`],contentTypeOf=e=>String(Object.entries(e??{}).find(([e])=>ae.includes(e.toLowerCase()))?.[1]??``).toLowerCase(),parseJson=e=>{try{return{parsed:JSON.parse(e)}}catch{return}},redactBody=(e,n)=>{if(!(0,t.isString)(e))return(0,i.redactFields)(e,i.CensorType.PARTIAL,!0);let r=parseJson(e);return r?redactBody(r.parsed,n):contentTypeOf(n).includes(`application/x-www-form-urlencoded`)?(0,i.redactFormBody)(e,i.CensorType.PARTIAL):e},safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},safeObject=e=>{try{return JSON.stringify(e),e}catch{return{error:`Unserializable payload`}}},hasErrorEntries=e=>(0,t.isMissing)(e)?!1:Array.isArray(e)||(0,t.isString)(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,oe={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},se=`action_logs_filtered`,ce=`organizationId.projectSecureId.actionRunId.accountSecureId.actionId.connectorKey.connectorVersion.connectorOwner.connectorProfileId.actionType.mode.category.originOwnerId.originOwnerName.httpMethod.sourceType.sourceId.sourceValue.authType.authId.userAgent.ipAddress.sessionId.agentId.transportType.streamType.policyResult.riskLevel`.split(`.`),le=[...ce.map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`isBackground = {isBackground:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),ue=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
2
2
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}
3
- AND ${d}`,toNullableFlag=e=>e===void 0?null:Number(e),buildViewParams=e=>({...Object.fromEntries(T.map(t=>[t,toArray(e[t])])),...toAuthPairParams(e.authPairs),statusCode:toStatusCodes(e.statusCode),isBackground:toNullableFlag(e.isBackground),success:toNullableFlag(e.success),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}),buildActionLogsQuery=e=>{let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
3
+ AND ${d}`,toNullableFlag=e=>e===void 0?null:Number(e),buildViewParams=e=>({...Object.fromEntries(ce.map(t=>[t,toArray(e[t])])),...toAuthPairParams(e.authPairs),statusCode:toStatusCodes(e.statusCode),isBackground:toNullableFlag(e.isBackground),success:toNullableFlag(e.success),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}),buildActionLogsQuery=e=>{let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
4
4
  SELECT *
5
- FROM ${w}(${E})
6
- ${D}
7
- ORDER BY ${sanitizeOrderBy(e.orderBy,pe,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
5
+ FROM ${se}(${le})
6
+ ${ue}
7
+ ORDER BY ${sanitizeOrderBy(e.orderBy,oe,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
8
8
  LIMIT {limit:UInt32}
9
9
  OFFSET {offset:UInt32}
10
10
  `,params:{...buildViewParams(e),limit:t,offset:n}}},buildActionLogsCountQuery=e=>({sql:`
11
11
  SELECT count() as total
12
- FROM ${w}(${E})
13
- ${D}
14
- `,params:buildViewParams(e)}),me={id:`project_action_logs`,buildQuery:buildActionLogsQuery,buildCountQuery:buildActionLogsCountQuery},he=[`synced_field_listing`,`test_actions`];function buildActionsCountQuery(e){return{sql:`
12
+ FROM ${se}(${le})
13
+ ${ue}
14
+ `,params:buildViewParams(e)}),de={id:`project_action_logs`,buildQuery:buildActionLogsQuery,buildCountQuery:buildActionLogsCountQuery},fe=[`synced_field_listing`,`test_actions`];function buildActionsCountQuery(e){return{sql:`
15
15
  SELECT count() AS actions_count
16
16
  FROM actions FINAL
17
17
  WHERE ({organizationId:Nullable(String)} IS NULL OR organizationId = {organizationId:Nullable(String)})
@@ -21,27 +21,25 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
21
21
  AND isBackground = 0
22
22
  AND ifNull(sourceType, '') != {dataSyncV2:String}
23
23
  AND ifNull(mode, '') NOT IN {nonBillableModes:Array(String)}
24
- `,params:{organizationId:e.organizationId??null,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),dataSyncV2:_.DataSyncV2,nonBillableModes:he}}}const ge={id:`actions_count`,buildQuery:buildActionsCountQuery},_e={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},untypedFilter=(e,t)=>e[t];function buildCommonLogParams(e){return{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),...toAuthPairParams(e.authPairs),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),logId:toArray(e.logId),requestId:toArray(e.requestId),resource:toArray(e.resource),service:toArray(e.service),subResource:toArray(e.subResource),childResource:toArray(e.childResource),action:toArray(e.action),actionRunId:toArray(e.actionRunId),actionId:toArray(e.actionId),actionType:toArray(e.actionType),category:toArray(e.category),path:toArray(untypedFilter(e,`path`)),accountId:toArray(untypedFilter(e,`accountId`)),riskLevel:toArray(untypedFilter(e,`riskLevel`)),policyResult:toArray(untypedFilter(e,`policyResult`)),status:toStatusCodes(untypedFilter(e,`status`))}}const ve=[...`organizationId.projectSecureId.accountSecureId.connectorKey.connectorVersion.connectorOwner.connectorProfileId.sourceType.sourceId.sourceValue.authType.authId.mode.httpMethod.originOwnerId.originOwnerName.logId.requestId.resource.service.subResource.childResource.action.actionRunId.actionId.actionType.category.path.accountId.riskLevel.policyResult.logType`.split(`.`).map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`status = {status:Array(Int16)}`,`isBackground = {isBackground:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),ye=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
24
+ `,params:{organizationId:e.organizationId??null,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),dataSyncV2:f.DataSyncV2,nonBillableModes:fe}}}const pe={id:`actions_count`,buildQuery:buildActionsCountQuery},h={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),me={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},he={Asc:`asc`,Desc:`desc`},g={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},ge={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,AuthType:`authType`,AuthId:`authId`,IsBackground:`isBackground`,PolicyResult:`policyResult`,RiskLevel:`riskLevel`},_e={EventType:`eventType`,Action:`action`,Resource:`resource`,Service:`service`,SourceType:`sourceType`,SourceId:`sourceId`,AuthType:`authType`,UserEmail:`userEmail`,StatusCode:`statusCode`,Success:`success`,IsRead:`isRead`,AgentId:`agentId`,TransportType:`transportType`,StreamType:`streamType`},_={actions:[`internal`],steps:[`internal`],unified_requests:[`internal`],provider_requests:[`internal`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===h.Platform,v={account_secure_id:`accountSecureId`,connector_key:`connectorKey`,connector_version:`connectorVersion`,connector_owner:`connectorOwner`,connector_profile_id:`connectorProfileId`,action_id:`actionId`,action_run_id:`actionRunId`,action_type:`actionType`,source_type:`sourceType`,source_id:`sourceId`,mode:`mode`,origin_owner_id:`originOwnerId`,origin_owner_name:`originOwnerName`,auth_type:`authType`,auth_id:`authId`,user_agent:`userAgent`,ip_address:`ipAddress`,session_id:`sessionId`,agent_id:`agentId`,transport_type:`transportType`,stream_type:`streamType`,http_method:`httpMethod`,service:`service`,resource:`resource`,risk_level:`riskLevel`,policy_result:`policyResult`,success:`success`,is_background:`isBackground`,status_code:`statusCode`,duration_ms:`durationMs`,log_id:`logId`,request_id:`requestId`,session_auth_id:`if(authType = 'SESSION_TOKEN', authId, NULL)`},y=Object.keys(v),b=new Set([`status_code`,`duration_ms`]),x=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`],S=new Set([`gt`,`gte`,`lt`,`lte`]),isFiniteNumber=e=>!!e.trim()&&Number.isFinite(Number(e)),isInt16=e=>{let t=Number(e);return isFiniteNumber(e)&&Number.isInteger(t)&&t>=-32768&&t<=32767},C=new Set([`status_code`]),w=new Set([`success`,`is_background`]),ve=r.z.object({field:r.z.enum(y),operator:r.z.enum(x),values:r.z.array(r.z.string().min(1).max(2048)).min(1).max(500)}).refine(({field:e,operator:t,values:n})=>{let r=b.has(e);return S.has(t)&&(!r||n.length!==1)?!1:C.has(e)?n.every(isInt16):r?n.every(isFiniteNumber):w.has(e)?n.every(e=>e===`true`||e===`false`):!0},{message:`Invalid log comparison values`}),ye=r.z.array(ve).max(50);var InvalidLogQueryConditionsError=class extends Error{constructor(e){super(`Invalid log query conditions`),this.name=`InvalidLogQueryConditionsError`,this.cause=e,this.issues=e.issues.map(({path:e,message:t})=>({path:e.filter(e=>typeof e!=`symbol`),message:t}))}};const parseLogQueryConditions=(e=[])=>{let t=ye.safeParse(e);if(!t.success)throw new InvalidLogQueryConditionsError(t.error);return t.data},be={type:`Int16`,cast:Number},xe={type:`Float64`,cast:Number},Se={type:`UInt8`,cast:e=>+(e===`true`)},Ce={type:`String`,cast:e=>e},valueKind=e=>C.has(e)?be:b.has(e)?xe:w.has(e)?Se:Ce,we={eq:{operator:`IN`,whenMissing:0},ne:{operator:`NOT IN`,whenMissing:1}},Te={gt:`>`,gte:`>=`,lt:`<`,lte:`<=`},isComparison=e=>S.has(e),buildCondition=({field:e,operator:t,values:n},r)=>{let i=`logCondition${r}`,a=v[e],{type:o,cast:s}=valueKind(e);if(isComparison(t))return{sql:`${a} ${Te[t]} {${i}:${o}}`,params:{[i]:s(n[0])}};let{operator:c,whenMissing:l}=we[t];return{sql:`ifNull(${a} ${c} {${i}:Array(${o})}, ${l})`,params:{[i]:n.map(e=>s(e))}}},and=e=>({sql:e.map(({sql:e})=>`(${e})`).join(` AND `),params:Object.assign({},...e.map(({params:e})=>e))}),buildLogConditions=e=>and(parseLogQueryConditions(e).map(buildCondition)),Ee={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},untypedFilter=(e,t)=>e[t];function buildCommonLogParams(e){return{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),...toAuthPairParams(e.authPairs),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),transportType:toArray(e.transportType),streamType:toArray(e.streamType),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),logId:toArray(e.logId),requestId:toArray(e.requestId),resource:toArray(e.resource),service:toArray(e.service),subResource:toArray(e.subResource),childResource:toArray(e.childResource),action:toArray(e.action),actionRunId:toArray(e.actionRunId),actionId:toArray(e.actionId),actionType:toArray(e.actionType),category:toArray(e.category),path:toArray(untypedFilter(e,`path`)),accountId:toArray(untypedFilter(e,`accountId`)),riskLevel:toArray(untypedFilter(e,`riskLevel`)),policyResult:toArray(untypedFilter(e,`policyResult`)),status:toStatusCodes(untypedFilter(e,`status`))}}const De=[...`organizationId.projectSecureId.accountSecureId.connectorKey.connectorVersion.connectorOwner.connectorProfileId.sourceType.sourceId.sourceValue.authType.authId.sessionId.agentId.userAgent.ipAddress.transportType.streamType.mode.httpMethod.originOwnerId.originOwnerName.logId.requestId.resource.service.subResource.childResource.action.actionRunId.actionId.actionType.category.path.accountId.riskLevel.policyResult.logType`.split(`.`).map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`status = {status:Array(Int16)}`,`isBackground = {isBackground:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),Oe=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
25
25
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}
26
- AND ${d}`,buildLogsViewSource=()=>`SELECT *
27
- FROM logs_filtered(${ve})
28
- ${ye}`,buildLogsViewParams=e=>({...buildCommonLogParams(e),logType:toArray(e.logType)});function buildLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize),r=sanitizeOrderBy(e.orderBy,_e,`eventTime`),i=sanitizeOrderDirection(e.orderDirection);return{sql:`
29
- ${buildLogsViewSource()}
26
+ AND ${d}`,buildLogsViewParams=e=>({...buildCommonLogParams(e),logType:toArray(e.logType)}),ke={action_id:`actionId`,action_run_id:`actionRunId`,action_type:`actionType`,policy_result:`policyResult`,request_id:`requestId`,resource:`resource`,risk_level:`riskLevel`,service:`service`},bindSingleTableMatches=(e,t)=>t.reduce((e,{field:t,operator:n,values:r})=>{let i=ke[t];if(!i||n!==`eq`)return e;let a=narrowArrayFilter(e[i],r);return a?{...e,[i]:a}:e},e),buildLogsView=e=>{let t=buildLogConditions(e.conditions);return{sql:`SELECT * FROM logs_filtered(${De}) ${Oe}${t.sql?` AND ${t.sql}`:``}`,params:{...bindSingleTableMatches(buildLogsViewParams(e),parseLogQueryConditions(e.conditions)),...t.params}}};function buildLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize),r=sanitizeOrderBy(e.orderBy,Ee,`eventTime`),i=sanitizeOrderDirection(e.orderDirection),a=buildLogsView(e);return{sql:`
27
+ ${a.sql}
30
28
  ORDER BY ${r} ${i}
31
29
  LIMIT {limit:UInt32}
32
30
  OFFSET {offset:UInt32}
33
- `,params:{...buildLogsViewParams(e),limit:t,offset:n}}}function buildLogsCountQuery(e){return{sql:`
34
- SELECT count() as total FROM (${buildLogsViewSource()})
35
- `,params:buildLogsViewParams(e)}}const be={id:`project_logs`,buildQuery:buildLogsQuery,buildCountQuery:buildLogsCountQuery},O={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},k={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},A={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(k,e)?k[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(A,e)?A[e]:3600);return`toDateTime(intDiv(toUnixTimestamp(${n}(eventTime)), ${r}) * ${r})`}function buildAggregationQuery(e){let t=toCsvArray(e.dimensions).map(n.snakeToCamel),r=e.intervalType??`hour`,i=Math.floor(Number(e.intervalPeriod??1)),a=Number.isFinite(i)&&i>0?i:1,o=t.filter(e=>Object.prototype.hasOwnProperty.call(O,e)).map(e=>O[e]),s=r===h.None?void 0:buildTimeBucket(r,a),c=[...s?[`${s} as startTime`]:[],`count() as count`,...o].join(`, `),l=[...s?[`startTime`]:[],...o],u=l.length>0?`GROUP BY ${l.join(`, `)}`:``,d=s?`ORDER BY startTime ASC`:``;return{sql:`
31
+ `,params:{...a.params,limit:t,offset:n}}}function buildLogsCountQuery(e){let t=buildLogsView(e);return{sql:`
32
+ SELECT count() as total FROM (${t.sql})
33
+ `,params:t.params}}const Ae={id:`project_logs`,buildQuery:buildLogsQuery,buildCountQuery:buildLogsCountQuery},T={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},E={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},D={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(E,e)?E[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(D,e)?D[e]:3600);return`toDateTime(intDiv(toUnixTimestamp(${n}(eventTime)), ${r}) * ${r})`}function buildAggregationQuery(e){let n=buildLogsView(e),r=toCsvArray(e.dimensions).map(t.snakeToCamel),i=e.intervalType??`hour`,a=Math.floor(Number(e.intervalPeriod??1)),o=Number.isFinite(a)&&a>0?a:1,s=r.filter(e=>Object.prototype.hasOwnProperty.call(T,e)).map(e=>T[e]),c=i===g.None?void 0:buildTimeBucket(i,o),l=[...c?[`${c} as startTime`]:[],`count() as count`,...s].join(`, `),u=[...c?[`startTime`]:[],...s],d=u.length>0?`GROUP BY ${u.join(`, `)}`:``,f=c?`ORDER BY startTime ASC`:``;return{sql:`
36
34
  WITH logs AS (
37
- ${buildLogsViewSource()}
35
+ ${n.sql}
38
36
  )
39
37
  SELECT
40
- ${c}
38
+ ${l}
41
39
  FROM logs
42
- ${u}
43
40
  ${d}
44
- `,params:buildLogsViewParams(e)}}const xe={id:`project_logs_aggregation`,buildQuery:buildAggregationQuery},j={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},M=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`,`authType`,`authId`,`policyResult`,`riskLevel`]);function buildDimensionsQuery(e){let t=toCsvArray(e.dimensions).map(n.snakeToCamel),r=e.maxValues??100,i=t.filter(e=>Object.prototype.hasOwnProperty.call(j,e));if(i.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let a=buildLogsViewSource();return{sql:i.map(e=>{let t=j[e];return`
41
+ ${f}
42
+ `,params:n.params}}const je={id:`project_logs_aggregation`,buildQuery:buildAggregationQuery},O={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},k=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`,`authType`,`authId`,`policyResult`,`riskLevel`]);function buildDimensionsQuery(e){let n=toCsvArray(e.dimensions).map(t.snakeToCamel),r=e.maxValues??100,i=n.filter(e=>Object.prototype.hasOwnProperty.call(O,e));if(i.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let a=buildLogsView(e),o=a.sql;return{sql:i.map(e=>{let t=O[e];return`
45
43
  SELECT
46
44
  '${e}' as dimension,
47
45
  arrayReverseSort(
@@ -53,28 +51,28 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
53
51
  toString(${t}) as value,
54
52
  count() as count
55
53
  FROM (
56
- ${a}
54
+ ${o}
57
55
  ) AS logs
58
56
  WHERE ${t} IS NOT NULL
59
- ${M.has(e)?`AND ${t} != ''`:``}
57
+ ${k.has(e)?`AND ${t} != ''`:``}
60
58
  GROUP BY ${t}
61
59
  ORDER BY count DESC
62
60
  LIMIT {maxValues:UInt32}
63
61
  ) AS facets
64
62
  `}).join(`
65
63
  UNION ALL
66
- `),params:{...buildLogsViewParams(e),maxValues:r}}}const Se={id:`project_logs_dimensions`,buildQuery:buildDimensionsQuery},narrowScanFilter=(e,t,n)=>{if(!(t in e))return{};let r=e[t],i=r.length===0?n:n.filter(e=>r.includes(e));return i.length===0?{}:{[t]:i}},buildLastLogsQuery=e=>{let t=e.entities?.field;if(!t||!M.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=`
64
+ `),params:{...a.params,maxValues:r}}}const Me={id:`project_logs_dimensions`,buildQuery:buildDimensionsQuery},narrowScanFilter=(e,t,n)=>{if(!(t in e))return{};let r=narrowArrayFilter(e[t],n);return r?{[t]:r}:{}},buildLastLogsQuery=e=>{let t=e.entities?.field;if(!t||!k.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=buildLogsView(e),r=`
67
65
  WITH logs AS (
68
- ${buildLogsViewSource()}
66
+ ${n.sql}
69
67
  )
70
68
  SELECT * FROM logs
71
69
  WHERE ${t} IN {entityIds:Array(String)}
72
70
  ORDER BY eventTime DESC
73
71
  LIMIT 1 BY ${t}
74
- `,r=toArray(e.entities?.ids),i=buildLogsViewParams(e);return{sql:n,params:{...i,...narrowScanFilter(i,t,r),entityIds:r}}},Ce={id:`project_last_logs`,buildQuery:buildLastLogsQuery},we=[...[`organizationId`,`projectSecureId`,`eventId`,`eventType`,`service`,`userId`,`userEmail`,`action`,`resource`,`resourceId`,`sourceType`,`sourceId`,`authType`,`authId`,`userAgent`,`ipAddress`,`sessionId`,`agentId`,`transportType`,`streamType`].map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`isRead = {isRead:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),N={eventType:`eventType`,action:`action`,resource:`resource`,service:`service`,sourceType:`sourceType`,sourceId:`sourceId`,authType:`authType`,userEmail:`userEmail`,statusCode:`statusCode`,success:`success`,isRead:`isRead`,agentId:`agentId`,transportType:`transportType`,streamType:`streamType`},Te=new Set([`statusCode`,`success`,`isRead`]),Ee=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
72
+ `,i=toArray(e.entities?.ids),a=n.params;return{sql:r,params:{...a,...narrowScanFilter(a,t,i),entityIds:i}}},Ne={id:`project_last_logs`,buildQuery:buildLastLogsQuery},Pe=[...[`organizationId`,`projectSecureId`,`eventId`,`eventType`,`service`,`userId`,`userEmail`,`action`,`resource`,`resourceId`,`sourceType`,`sourceId`,`authType`,`authId`,`userAgent`,`ipAddress`,`sessionId`,`agentId`,`transportType`,`streamType`].map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`isRead = {isRead:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),A={eventType:`eventType`,action:`action`,resource:`resource`,service:`service`,sourceType:`sourceType`,sourceId:`sourceId`,authType:`authType`,userEmail:`userEmail`,statusCode:`statusCode`,success:`success`,isRead:`isRead`,agentId:`agentId`,transportType:`transportType`,streamType:`streamType`},Fe=new Set([`statusCode`,`success`,`isRead`]),Ie=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
75
73
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`,buildPlatformViewSource=()=>`SELECT *
76
- FROM platform_filtered(${we})
77
- ${Ee}`,buildPlatformViewParams=e=>({organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)});function buildPlatformDimensionsQuery(e){let t=toArray(e.dimensions).map(n.snakeToCamel),r=e.maxValues??100,i=t.filter(e=>Object.prototype.hasOwnProperty.call(N,e));if(i.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let a=buildPlatformViewSource();return{sql:i.map(e=>{let t=N[e];return`
74
+ FROM platform_filtered(${Pe})
75
+ ${Ie}`,buildPlatformViewParams=e=>({organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)});function buildPlatformDimensionsQuery(e){let n=toArray(e.dimensions).map(t.snakeToCamel),r=e.maxValues??100,i=n.filter(e=>Object.prototype.hasOwnProperty.call(A,e));if(i.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let a=buildPlatformViewSource();return{sql:i.map(e=>{let t=A[e];return`
78
76
  SELECT
79
77
  '${e}' as dimension,
80
78
  arrayReverseSort(
@@ -89,14 +87,14 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
89
87
  ${a}
90
88
  ) AS platformLogs
91
89
  WHERE ${t} IS NOT NULL
92
- ${Te.has(e)?``:`AND ${t} != ''`}
90
+ ${Fe.has(e)?``:`AND ${t} != ''`}
93
91
  GROUP BY ${t}
94
92
  ORDER BY count DESC
95
93
  LIMIT {maxValues:UInt32}
96
94
  ) AS facets
97
95
  `}).join(`
98
96
  UNION ALL
99
- `),params:{...buildPlatformViewParams(e),maxValues:r}}}const De={id:`organization_platform_dimensions`,buildQuery:buildPlatformDimensionsQuery},Oe={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
97
+ `),params:{...buildPlatformViewParams(e),maxValues:r}}}const Le={id:`organization_platform_dimensions`,buildQuery:buildPlatformDimensionsQuery},Re={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
100
98
  SELECT
101
99
  eventTime,
102
100
  startTime,
@@ -154,7 +152,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
154
152
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
155
153
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
156
154
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
157
- ORDER BY ${sanitizeOrderBy(e.orderBy,Oe,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
155
+ ORDER BY ${sanitizeOrderBy(e.orderBy,Re,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
158
156
  LIMIT {limit:UInt32}
159
157
  OFFSET {offset:UInt32}
160
158
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildPlatformLogsCountQuery(e){return{sql:`
@@ -186,19 +184,19 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
186
184
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
187
185
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
188
186
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
189
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const ke={id:`organization_platform_logs`,buildQuery:buildPlatformLogsQuery,buildCountQuery:buildPlatformLogsCountQuery},Ae={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},P=`provider_logs_filtered`,F=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`requestId = {requestId:Array(String)}`,`id = {id:Array(String)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),I=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
187
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const ze={id:`organization_platform_logs`,buildQuery:buildPlatformLogsQuery,buildCountQuery:buildPlatformLogsCountQuery},Be={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},j=`provider_logs_filtered`,M=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`requestId = {requestId:Array(String)}`,`id = {id:Array(String)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),N=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
190
188
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`;function buildProviderLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
191
189
  SELECT *
192
- FROM ${P}(${F})
193
- ${I}
194
- ORDER BY ${sanitizeOrderBy(e.orderBy,Ae,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
190
+ FROM ${j}(${M})
191
+ ${N}
192
+ ORDER BY ${sanitizeOrderBy(e.orderBy,Be,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
195
193
  LIMIT {limit:UInt32}
196
194
  OFFSET {offset:UInt32}
197
195
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildProviderLogsCountQuery(e){return{sql:`
198
196
  SELECT count() as total
199
- FROM ${P}(${F})
200
- ${I}
201
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const je={id:`project_provider_logs`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery};function buildSourceUsageQuery(e){return{sql:`
197
+ FROM ${j}(${M})
198
+ ${N}
199
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const Ve={id:`project_provider_logs`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery};function buildSourceUsageQuery(e){return{sql:`
202
200
  SELECT
203
201
  sourceId,
204
202
  sourceType,
@@ -215,29 +213,29 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
215
213
  AND sourceId != ''
216
214
  GROUP BY sourceId, sourceType
217
215
  ORDER BY request_count DESC
218
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const Me={id:`project_source_usage`,buildQuery:buildSourceUsageQuery},Ne={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},L=`step_logs_filtered`,R=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`actionRunId = {actionRunId:Array(String)}`,`stepId = {stepId:Array(String)}`,`stepIndex = {stepIndex:Array(Int32)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),z=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
216
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const He={id:`project_source_usage`,buildQuery:buildSourceUsageQuery},Ue={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},P=`step_logs_filtered`,F=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`actionRunId = {actionRunId:Array(String)}`,`stepId = {stepId:Array(String)}`,`stepIndex = {stepIndex:Array(Int32)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),I=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
219
217
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`;function buildStepLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
220
218
  SELECT *
221
- FROM ${L}(${R})
222
- ${z}
223
- ORDER BY ${sanitizeOrderBy(e.orderBy,Ne,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
219
+ FROM ${P}(${F})
220
+ ${I}
221
+ ORDER BY ${sanitizeOrderBy(e.orderBy,Ue,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
224
222
  LIMIT {limit:UInt32}
225
223
  OFFSET {offset:UInt32}
226
224
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildStepLogsCountQuery(e){return{sql:`
227
225
  SELECT count() as total
228
- FROM ${L}(${R})
229
- ${z}
230
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const Pe={id:`project_step_logs`,buildQuery:buildStepLogsQuery,buildCountQuery:buildStepLogsCountQuery},Fe={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},B=`unified_logs_filtered`,V=`organizationId = {organizationId:Array(String)}.projectSecureId = {projectSecureId:Array(String)}.accountSecureId = {accountSecureId:Array(String)}.requestId = {requestId:Array(String)}.connectorKey = {connectorKey:Array(String)}.connectorVersion = {connectorVersion:Array(String)}.connectorOwner = {connectorOwner:Array(String)}.connectorProfileId = {connectorProfileId:Array(String)}.mode = {mode:Array(String)}.httpMethod = {httpMethod:Array(String)}.resource = {resource:Array(String)}.subResource = {subResource:Array(String)}.childResource = {childResource:Array(String)}.service = {service:Array(String)}.action = {action:Array(String)}.sourceType = {sourceType:Array(String)}.sourceId = {sourceId:Array(String)}.sourceValue = {sourceValue:Array(String)}.authType = {authType:Array(String)}.authId = {authId:Array(String)}.userAgent = {userAgent:Array(String)}.ipAddress = {ipAddress:Array(String)}.sessionId = {sessionId:Array(String)}.agentId = {agentId:Array(String)}.transportType = {transportType:Array(String)}.streamType = {streamType:Array(String)}.originOwnerId = {originOwnerId:Array(String)}.originOwnerName = {originOwnerName:Array(String)}.statusCode = {statusCode:Array(Int16)}.isBackground = {isBackground:Nullable(UInt8)}.success = {success:Nullable(UInt8)}.startTime = {startTime:Nullable(DateTime64(3))}.endTime = {endTime:Nullable(DateTime64(3))}`.split(`.`).join(`, `),H=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
226
+ FROM ${P}(${F})
227
+ ${I}
228
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const We={id:`project_step_logs`,buildQuery:buildStepLogsQuery,buildCountQuery:buildStepLogsCountQuery},Ge={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},L=`unified_logs_filtered`,R=`organizationId = {organizationId:Array(String)}.projectSecureId = {projectSecureId:Array(String)}.accountSecureId = {accountSecureId:Array(String)}.requestId = {requestId:Array(String)}.connectorKey = {connectorKey:Array(String)}.connectorVersion = {connectorVersion:Array(String)}.connectorOwner = {connectorOwner:Array(String)}.connectorProfileId = {connectorProfileId:Array(String)}.mode = {mode:Array(String)}.httpMethod = {httpMethod:Array(String)}.resource = {resource:Array(String)}.subResource = {subResource:Array(String)}.childResource = {childResource:Array(String)}.service = {service:Array(String)}.action = {action:Array(String)}.sourceType = {sourceType:Array(String)}.sourceId = {sourceId:Array(String)}.sourceValue = {sourceValue:Array(String)}.authType = {authType:Array(String)}.authId = {authId:Array(String)}.userAgent = {userAgent:Array(String)}.ipAddress = {ipAddress:Array(String)}.sessionId = {sessionId:Array(String)}.agentId = {agentId:Array(String)}.transportType = {transportType:Array(String)}.streamType = {streamType:Array(String)}.originOwnerId = {originOwnerId:Array(String)}.originOwnerName = {originOwnerName:Array(String)}.statusCode = {statusCode:Array(Int16)}.isBackground = {isBackground:Nullable(UInt8)}.success = {success:Nullable(UInt8)}.startTime = {startTime:Nullable(DateTime64(3))}.endTime = {endTime:Nullable(DateTime64(3))}`.split(`.`).join(`, `),z=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
231
229
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}
232
230
  AND ${d}`;function buildUnifiedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
233
231
  SELECT *
234
- FROM ${B}(${V})
235
- ${H}
236
- ORDER BY ${sanitizeOrderBy(e.orderBy,Fe,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
232
+ FROM ${L}(${R})
233
+ ${z}
234
+ ORDER BY ${sanitizeOrderBy(e.orderBy,Ge,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
237
235
  LIMIT {limit:UInt32}
238
236
  OFFSET {offset:UInt32}
239
237
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),...toAuthPairParams(e.authPairs),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildUnifiedLogsCountQuery(e){return{sql:`
240
238
  SELECT count() as total
241
- FROM ${B}(${V})
242
- ${H}
243
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),...toAuthPairParams(e.authPairs),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const Ie={id:`project_unified_logs`,buildQuery:buildUnifiedLogsQuery,buildCountQuery:buildUnifiedLogsCountQuery};var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,t){this.#t=e,this.#n=t,e?.url&&(this.#e=(0,u.createClient)({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){let{data:t}=await this.#a(e);return t}async queryWithPagination(e){let{data:t,total:n}=await this.#a(e);return{data:t,total:n??t.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??t.length}}isReady(){return!!(this.#e&&this.#t?.url)}async close(){await this.#e?.close()}#r(){if(!this.#e)throw this.#n?.error({message:`ClickHouse client not initialized`,category:`ClickHouseClient`,code:`ClientNotReady`}),Error(`ClickHouse client is not initialized`);if(!this.#t?.url)throw this.#n?.warning({message:`Missing ClickHouse URL`,category:`ClickHouseClient`}),Error(`ClickHouseClient - Missing URL`);return this.#e}#i(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`ClickHouseClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`ClickHouseClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#a(e){try{let{data:t,total:n}=await this.#o(e.query,e.params);return{data:this.#i(t,e.schema),total:n}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error running clickhouse query ${e.query.id}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async#o(e,t){let n=this.#r(),{sql:r,params:i}=e.buildQuery(t);this.#n?.debug({message:`Running clickhouse query: ${e.id}`,category:`ClickHouseClient`,context:{query:e.id,params:t}});let a=Date.now(),o=await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json(),s=(Date.now()-a)/1e3,c;if(e.buildCountQuery){let{sql:r,params:i}=e.buildCountQuery(t);c=(await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${o.length} rows`,category:`ClickHouseClient`,context:{query:e.id,rows:o.length,elapsed:s}}),{data:o,total:c}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},U=l.z.preprocess(e=>{if(e instanceof Date)return e;if(typeof e==`string`&&e.length>0)try{return new Date(utcDateTransform(e))}catch(e){throw new l.z.ZodError([{code:l.z.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},l.z.coerce.date()),W=l.z.object({logType:l.z.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:U,startTime:U,endTime:U.optional().nullable().transform(e=>e??void 0),durationMs:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:l.z.coerce.string(),projectSecureId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),G=W.extend({logType:l.z.literal(`action`),actionRunId:l.z.coerce.string(),actionId:l.z.coerce.string(),connectorKey:l.z.coerce.string(),connectorVersion:l.z.coerce.string(),connectorOwner:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:l.z.coerce.string(),accountSecureId:l.z.coerce.string(),actionType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),mode:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),category:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),actingUserId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),policyResult:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),isBackground:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:U.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:U.optional().nullable().transform(e=>e??void 0)}),K=W.extend({logType:l.z.literal(`step`),actionRunId:l.z.coerce.string(),stepIndex:l.z.coerce.number(),stepId:l.z.coerce.string(),projectSecureId:l.z.coerce.string(),accountSecureId:l.z.coerce.string(),skipped:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),message:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:l.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),q=W.extend({logType:l.z.literal(`unified`),requestId:l.z.coerce.string(),connectorKey:l.z.coerce.string(),connectorVersion:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:l.z.coerce.string(),accountSecureId:l.z.coerce.string(),mode:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),path:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),actingUserId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:U.optional().nullable().transform(e=>e??void 0),duration:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:U.optional().nullable().transform(e=>e??void 0)}),J=W.extend({logType:l.z.literal(`provider`),requestId:l.z.coerce.string(),id:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:l.z.coerce.string(),mode:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:l.z.coerce.string(),originOwnerId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:l.z.coerce.string(),path:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:l.z.coerce.string(),connectorVersion:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:l.z.coerce.string(),accountSecureId:l.z.coerce.string(),status:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:U.optional().nullable().transform(e=>e??void 0),duration:l.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),Y=W.extend({logType:l.z.literal(`platform`),eventId:l.z.coerce.string(),eventType:l.z.coerce.string(),service:l.z.coerce.string(),organizationId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:l.z.undefined().optional(),userId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:l.z.record(l.z.string(),l.z.unknown()).optional().nullable().transform(e=>e??void 0)}),Le=l.z.discriminatedUnion(`logType`,[G,K,q,J]),Re=new Set([`success`,`isRead`]),foldTimeBuckets=e=>{let t=new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},X=[`success`,`isWorker`,`isBackground`,`skipped`],ze=15e3;var LogsSink=class{#e;#t;#n;#r;#i;#a(){return this.#r?.isReady()?this.#r:void 0}constructor(e,t,n,r,i){this.#e=e,this.#t=r,this.#n=i,this.#i=t,n&&(this.#r=new ClickHouseClient(n,t),this.#i?.debug({message:`LogsSink initialized with the ClickHouse query client`,category:`LogsSink`}))}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#i?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}this.#r?.isReady()?this.#i?.info({message:`Logs sink query client ready: clickhouse`,category:`LogsSink`}):this.#i?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}),this.#i?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#l()}async close(e=3e4){return this.#o??=this.#s(e),this.#o}#o;async#s(e){let t=[];if(this.#e?.producer){let e=this.#e.producer;t.push([`external kafka producer`,()=>e.close()])}if(this.#t?.producer){let e=this.#t.producer;t.push([`internal kafka producer`,()=>e.close()])}if(this.#r){let e=this.#r;t.push([`clickhouse client`,()=>e.close()])}(await Promise.allSettled(t.map(([,t])=>this.#c(t,e)))).forEach((n,r)=>{if(n.status===`rejected`){let i=n.reason instanceof Error?n.reason:Error(String(n.reason)),a=i.name===`LogsSinkCloseTimeout`,o=t[r]?.[0]??`resource`,s=o.includes(`producer`),c={message:a?s?`Timed out closing ${o} after ${e}ms; buffered records may have been lost`:`Timed out releasing ${o} after ${e}ms`:`Error closing ${o}: ${i.message}`,error:i,code:`LogsSinkCloseError`,category:`LogsSink`};a&&s?this.#i?.error(c):this.#i?.warning(c)}})}async#c(e,t){let n,r=new Promise((e,r)=>{n=setTimeout(()=>{let e=Error(`timed out after ${t}ms`);e.name=`LogsSinkCloseTimeout`,r(e)},t),n.unref?.()});try{return await Promise.race([Promise.resolve().then(e),r])}finally{n&&clearTimeout(n)}}async#l(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{let n;try{await Promise.race([t?.connectToBrokers(),new Promise((e,t)=>{n=setTimeout(()=>t(Error(`connectivity probe timed out after ${ze}ms`)),ze),n.unref?.()})]),this.#i?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#i?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}finally{n&&clearTimeout(n)}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t,metadata:n})=>this.buildActionLog(e,t,n));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n,r){if(!r?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async sendPlatform(e,t,n){let r=isPlatformLog(e);if(!(r?t:n)?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending platform to log sink (topic: platform)`,category:`LogsSink`});let i=r?e:this.buildPlatformLog(e,t??{});await this.send(`platform`,[i])}async getLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({query:be,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} logs (${n.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(n.data),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getLastLogs(e,t){let n=e?.ids??[];if(n.length===0)return emptyQueryResult();let r=this.#r;if(!r?.isReady())return this.#i?.warning({message:`ClickHouse client not available, returning empty results`,category:`LogsSink`}),emptyQueryResult();try{this.#i?.info({message:`Querying last logs for ${n.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await r.queryWithPagination({query:Ce,params:{...t,entities:e}});return this.#i?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){return this.#i?.warning({message:`Failed to query for last logs, returning empty results`,category:`LogsSink`,error:e}),emptyQueryResult()}}async getActions(e){let t=this.#a();try{this.#i?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({query:me,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} action logs (${n.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(n.data,G),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n})).actionLogs[0]}async getSteps(e){let t=this.#a();try{this.#i?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({query:Pe,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} step logs (${n.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(n.data,K),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r})).stepLogs[0]}async getUnifiedLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({query:Ie,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} unified logs (${n.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(n.data,q),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n})).unifiedLogs[0]}async getProviderLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({query:je,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} provider logs (${n.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(n.data,J),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.error({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,code:`ProviderLogsQueryFailed`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogDimensions(e){let t=this.#a();try{this.#i?.info({message:`Querying platform log dimensions`,category:`LogsSink`,context:{query:e}});let n=await t?.query({query:De,params:e});if(!n)return this.#i?.warning({message:`Platform log dimensions were requested but the ClickHouse client is not available`,category:`LogsSink`}),{};this.#i?.info({message:`Successfully retrieved ${n.length} platform dimension facets`,category:`LogsSink`});let r={};for(let e of n)r[e.dimension]=Re.has(e.dimension)?e.values.map(e=>({value:e.value===`1`?`true`:`false`,count:e.count})):e.values;return r}catch(e){return this.#i?.error({message:`Failed to query platform log dimensions: ${e instanceof Error?e.message:String(e)}`,category:`LogsSink`,code:`PlatformDimensionsQueryFailed`}),{}}}async getPlatformLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({query:ke,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} platform logs (${n.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(n.data,Y),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Platform logs were requested but the ClickHouse client is not available`,category:`LogsSink`}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r})).providerLogs[0]}async getAggregate(e,t,r){let i=this.#a();try{this.#i?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:r}});let{dimensions:a,startTime:o,endTime:s,...c}=r,l=r.intervalType===h.None,u={organizationId:e,projectSecureId:t,...c,...a&&a.length>0&&{dimensions:a.join(`,`)},...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...l&&{pageSize:void 0,pageNumber:void 0}},d=await i?.query({query:xe,params:u});if(!d)return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#i?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>(0,n.convertKeysToCamelCase)(e,!0)).map(e=>{let t={...e};for(let e of X)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:l?foldTimeBuckets(f):f}}catch(e){return i?.isReady()?this.#i?.warning({message:`Failed to query for logs stats aggregate, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{data:[]}}}async getDimensions(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n}});let{dimensions:i,startTime:a,endTime:o,...s}=n,c={organizationId:e,projectSecureId:t,...s,dimensions:i.join(`,`),...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await r?.query({query:Se,params:c});if(!l)return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{};this.#i?.info({message:`Successfully retrieved ${l.length} dimension facets`,category:`LogsSink`});let u={};for(let e of l)X.includes(e.dimension)?u[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):u[e.dimension]=e.values;return u}catch(e){return r?.isReady()?this.#i?.warning({message:`Failed to query for logs stats dimensions, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{}}}async getActionsCount(e){let t=this.#a();if(!t)throw Error(`Cannot count actions: no ClickHouse query client is configured and ready`);let[n]=await t.query({query:ge,params:e});return Number(n?.actions_count??0)}async getSourceUsage(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n}});let{startTime:i,endTime:a,sourceType:o}=n,s={organizationId:e,projectSecureId:t,sourceType:o||void 0,...i&&{startTime:i.toISOString()},...a&&{endTime:a.toISOString()}},c=await r?.query({query:Me,params:s});return c?(this.#i?.info({message:`Successfully retrieved ${c.length} source usage records`,category:`LogsSink`}),c.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),[])}catch(e){return r?.isReady()?this.#i?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),[]}}#u(e){return(this.#n??g)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#u(e);if(!n)throw this.#i?.error({message:`No cluster routing configured for topic ${e}, dropping ${t.length} log(s)`,category:`KafkaSink`,code:`TopicNotRouted`}),Error(`No cluster routing configured for topic ${e}`);if(n.length===0){this.#i?.debug({message:`Topic ${e} is muted by the topic cluster map, dropping ${t.length} log(s)`,category:`KafkaSink`});return}let r=this.validateLogsBeforeSend(t);if(r.length===0){this.#i?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}r.length<t.length&&this.#i?.warning({message:`${t.length-r.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let i=r.map(t=>({topic:e,value:safeSerialize(t)})),a=await Promise.allSettled(n.map(({cluster:t,producer:n})=>this.#d(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#d(e,t,n,r){if(!t)throw this.#i?.error({message:`Kafka not initialized, dropping message for topic ${n}`,category:`KafkaSink`,code:`KafkaNotReady`,context:{cluster:e}}),Error(`Kafka producer is not initialized`);let i=Date.now();this.#i?.debug({message:`Sending ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{cluster:e}});try{let a=await t.send({messages:r,compression:`gzip`});this.#i?.debug({message:`Successfully sent ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{durationMs:Date.now()-i,topic:n,cluster:e,result:a}})}catch(t){throw this.#i?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.actingUserId&&{actingUserId:e.actingUserId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.allowed!==void 0&&{allowed:t.defenderContext.result.allowed},...t.defenderContext?.result?.tier2Decision!==void 0&&{tier2Decision:t.defenderContext.result.tier2Decision},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},...t.defenderContext?.result?.tier2LatencyMs!==void 0&&{tier2LatencyMs:t.defenderContext.result.tier2LatencyMs},...t.defenderContext?.result?.tier3Decision!==void 0&&{tier3Decision:t.defenderContext.result.tier3Decision},...t.defenderContext?.result?.tier3PromptTokens!==void 0&&{tier3PromptTokens:t.defenderContext.result.tier3PromptTokens},...t.defenderContext?.result?.tier3CompletionTokens!==void 0&&{tier3CompletionTokens:t.defenderContext.result.tier3CompletionTokens},...t.defenderContext?.result?.tier3LatencyMs!==void 0&&{tier3LatencyMs:t.defenderContext.result.tier3LatencyMs},...t.policyContext&&{policyResult:t.policyContext.result},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.actingUserId&&{actingUserId:e.actingUserId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}buildPlatformLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`platform`,eventId:e.eventId??(0,c.randomUUID)(),eventType:e.eventType,service:e.service,...e.organizationId!==void 0&&{organizationId:e.organizationId},...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.userId!==void 0&&{userId:e.userId},...e.userEmail!==void 0&&{userEmail:e.userEmail},...e.action!==void 0&&{action:e.action},...e.resource!==void 0&&{resource:e.resource},...e.resourceId!==void 0&&{resourceId:e.resourceId},...e.sourceType!==void 0&&{sourceType:e.sourceType},...e.sourceId!==void 0&&{sourceId:e.sourceId},...e.authType!==void 0&&{authType:e.authType},...e.authId!==void 0&&{authId:e.authId},...e.userAgent!==void 0&&{userAgent:e.userAgent},...e.ipAddress!==void 0&&{ipAddress:e.ipAddress},...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.agentId!==void 0&&{agentId:e.agentId},...e.transportType!==void 0&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...e.isRead!==void 0&&{isRead:e.isRead},...e.statusCode!==void 0&&{statusCode:e.statusCode},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeObject(e.details)},startTime:e.startTime??n,...t.endTime!==void 0&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},eventTime:n}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof l.ZodError){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#i?.error({message:`Failed to validate ${n} log from the query engine`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.issues,log:safeSerialize(e)}}),Error(`Log data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,Le)}validateLogsBeforeSend(e){let t=[];for(let n of e)try{let e=this.getSchemaForLogType(n.logType).parse(n);t.push(e)}catch(e){e instanceof l.ZodError?this.#i?.warning({message:`Log validation failed before sending to Kafka, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.issues,log:safeSerialize(n)}}):this.#i?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return G;case`step`:return K;case`unified`:return q;case`provider`:return J;case`platform`:return Y}}};const Z={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`,piiRedactionEnabled:!1},defender:{enabled:!0},policy:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...Z.logs,...e?.logs},advanced:{...Z.advanced,...e?.advanced},defender:{...Z.defender,...e?.defender},policy:{...Z.policy,...e?.policy},datasets:{...Z.datasets,...e?.datasets}}}function getPolicySink(e,t,n){return new PolicySink(e,t,n)}const Q=`PolicySink`;var PolicySink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.ttlDays??365,this.#r=n}async initialize(){if(this.#t){this.#r?.warning({message:`No storage provided, policy sink will not function`,category:Q});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let r=[];for(let{input:i,result:a}of e){if(!t?.enabled){r.push(null);continue}if(!this.#e&&!this.#t){r.push(null);continue}if((0,n.isMissing)(a.policyContext)){r.push(null);continue}if(!this.#e)throw Error(`No storage available, cannot send to policy sink`);r.push(await this.send(this.#e,i,a))}return r}async getAction(e,t,n,r){if(this.#t){this.#r?.warning({message:`No storage available, cannot get action log from policy sink`,category:Q});return}if(this.#e)return readStoredLog({bucket:this.#e,key:policyKey(e,t,n,r),description:`policy log for actionRunId ${r}`,errorCode:`PolicyLogReadError`,category:Q,logger:this.#r})}async send(e,t,n){let r=new Date(Date.now()+this.#n*24*60*60*1e3);return await writeStoredLog({bucket:e,key:policyKey(t.organizationId,t.projectSecureId,t.accountSecureId,t.actionRunId),body:JSON.stringify(n.policyContext),ttlTag:`${this.#n}d`,expiresAt:r,description:`policy log`,errorCode:`PolicyLogWriteError`,category:Q,logger:this.#r}),{expiresAt:r}}};const policyKey=(e,t,n,r)=>`${e}/${t}/${n}/${r}/policy.json`,Be=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${Be}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${Be}${e} failed with ${r.status}`);return r},fetchGoogleAccessToken=async e=>{let t=await(await requestMetadata(`/token`,e)).json();if(!t.access_token||typeof t.expires_in!=`number`)throw Error(`Google metadata token response missing access_token or expires_in`);return{accessToken:t.access_token,expiresInSeconds:t.expires_in}},fetchGoogleServiceAccountEmail=async e=>{let t=(await(await requestMetadata(`/email`,e)).text()).trim();if(!t)throw Error(`Google metadata returned an empty service account email`);return t},encodeSegment=e=>Buffer.from(e,`utf8`).toString(`base64url`),Ve=__name(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=Ve(n);return e?.logger?.warning({message:`Google Kafka token refresh failed, using cached token: ${t.message}`,error:t,code:`GoogleKafkaTokenRefreshFailed`,category:`googleKafkaToken`}),i}throw n}).finally(()=>{r.inflight=void 0}),r.inflight)};return async()=>{try{let[{accessToken:e,expiresAtSeconds:n},r]=await Promise.all([credential(),principal()]);return encodeGoogleKafkaToken(e,{principal:r,issuedAtSeconds:t(),expiresAtSeconds:n})}catch(t){let n=Ve(t);throw e?.logger?.error({message:`Failed to mint Google Kafka token: ${n.message}`,error:n,code:`GoogleKafkaTokenError`,category:`googleKafkaToken`}),n}}},resolveSasl=(e,t)=>e.mechanism!==`OAUTHBEARER`||e.token?e:{...e,token:createGoogleKafkaTokenProvider({logger:t})},failedOnClosedConnection=e=>{let{code:t,canRetry:n,errors:r}=e??{};return Array.isArray(r)&&r.length>0?r.every(failedOnClosedConnection):t===`PLT_KFK_NETWORK`&&n===!0},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,a,o,s=new Set,closeQuietly=async e=>{try{await e.close()}catch(e){let t=e instanceof Error?e:Error(String(e));n?.warning({message:`Error closing kafka producer: ${t.message}`,error:t,code:`KafkaProducerCloseError`,category:`buildKafkaClient`})}},dispose=e=>{let t=closeQuietly(e).finally(()=>{s.delete(t)});return s.add(t),t},reconstruct=async e=>{if(a||o)return;let s=Date.now();if(!(s-i<3e4)){i=s;try{let i=r;o=t();let s=await o;if(a){await dispose(s);return}r=s,dispose(i),n?.warning({message:`Kafka producer reconstructed after send failure: ${e.message}`,error:e,code:`KafkaProducerReconstructed`,category:`buildKafkaClient`})}catch(e){let t=e;n?.error({message:`Error reconstructing kafka producer: ${t.message}`,error:t,code:`KafkaProducerReconstructionError`,category:`buildKafkaClient`})}finally{o=void 0}}},close=async()=>(a??=(async()=>{let e=o;for(await closeQuietly(r),e&&await e.catch(()=>void 0);s.size>0;)await Promise.allSettled([...s])})(),a),send=async e=>{let t=r;try{return await t.send(e)}catch(n){if(await reconstruct(n),r!==t&&!a&&failedOnClosedConnection(n))return r.send(e);throw n}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;if(t===`close`)return close;let n=Reflect.get(r,t,r);return typeof n==`function`?n.bind(r):n}})},buildKafkaClient=async(e,t)=>{if(!e)return;let construct=async()=>{let{Producer:n,stringSerializers:r}=await import(`@platformatic/kafka`);return new n({retries:3,retryDelay:1e3,...e,...e.sasl&&{sasl:resolveSasl(e.sasl,t)},serializers:r})};try{return withLazyReconstruction(await construct(),construct,t)}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},toError=e=>e instanceof Error?e:Error(String(e)),createMskKafkaTokenProvider=({region:e,logger:t})=>async()=>{try{let{generateAuthToken:t}=await import(`aws-msk-iam-sasl-signer-js`),{token:n}=await t({region:e});return n}catch(e){let n=toError(e);throw t?.error({message:`Failed to mint MSK Kafka token: ${n.message}`,error:n,code:`MskKafkaTokenError`,category:`mskKafkaToken`}),n}},rotateBootstrapBrokers=(e,t=Math.random)=>{let n=Math.floor(t()*e.length);return[...e.slice(n),...e.slice(0,n)]},buildInternalKafkaClient=async(e,t,n=Math.random)=>{if(!e)return;let{bootstrapBrokers:r,region:i,clientId:a,...o}=e;return buildKafkaClient({bootstrapBrokers:rotateBootstrapBrokers(r,n),clientId:a??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:i,logger:t})},...o},t)},defaultStorage=e=>e?.advanced?.bucket||e?.defender?.bucket||e?.policy?.bucket?(0,t.createStorage)((0,t.storageConfigFromEnv)()):void 0;var $=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){this.name=`OlapClient`,this.#c=e,this.#l=i??r,this.#u=t,this.#d=a,this.#m=o,this.#f=s,this.#p=c,this.#t=n??defaultStorage(c),this.#n=l}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){let u=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});return await u.initialize(),u}async initialize(){this.#e=await this.#c(this.#l,this.#n);let e=this.#d?{producer:await this.#u(this.#d,this.#n)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#r=new LogsSink(t,this.#n,this.#f,e,this.#m),this.#i=new AdvancedSink(this.#t,this.#p?.advanced,this.#n),this.#a=new DefenderSink(this.#t,this.#p?.defender,this.#n),this.#o=new PolicySink(this.#t,this.#p?.policy,this.#n),this.#s=new DatasetsSink(this.#p?.datasets,this.#n),await this.#r?.initialize(),await this.#i?.initialize(),await this.#s?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async close(e){await Promise.all([this.#r?.close?.(e),this.#s?.close(e)])}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:r,advanced:i,defender:a,policy:o,datasets:s}=resolveOlapOptions(t);this.#n?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:r,advanced:i,defender:a,policy:o,datasets:s}}});for(let t of e)(0,n.isMissing)(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let c=o?.enabled&&this.#o?this.#o.sendActions(e,o).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to policy logs storage: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),l=s?.enabled&&this.#s?this.#s.sendActions(e,s).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[u,d]=await Promise.all([i?.enabled&&this.#i?this.#i.sendActions(e,i).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),a?.enabled&&this.#a?this.#a.sendActions(e,a).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to defender logs storage: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),f=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:u[t]?.expiresAt,defenderExpiresAt:d[t]?.expiresAt}})),p=r?.enabled&&this.#r?this.#r.sendActions(f,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([l,c,p])}async recordStep(e,t,n){await this.recordSteps([{input:e,result:t}],n)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#r&&i.push(this.#r.sendSteps(e,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,r).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to storage: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,r){let{logs:i,advanced:a}=resolveOlapOptions(r);this.#n?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:r,resolvedOptions:{logs:i,advanced:a}}}),(0,n.isMissing)(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let o={advancedExpiresAt:(a?.enabled&&this.#i?await this.#i.sendUnified(e,t,a).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};i?.enabled&&this.#r&&await this.#r.sendUnified(e,t,o,i).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#r&&a.push(this.#r.sendProvider(e,t,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to storage: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordPlatform(e,t,n){let r=isPlatformLog(e),i=r&&t&&`data`in t?t:void 0,{logs:a,advanced:o}=resolveOlapOptions(r&&!i?t:n),s=a?.enabled&&this.#r?(r?this.#r.sendPlatform(e,a):this.#r.sendPlatform(e,t??{},a)).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#i?this.#i.sendPlatform(e,i,o).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n){return this.#n?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getLastLogs(e,t,n,r={}){let i={...r,organizationId:e,projectSecureId:t};return this.#n?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#r?.getLastLogs(n,i)||(this.#n?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n){return this.#n?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,r){let i=await this.#r?.getAction(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve action log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getLog(e,t,n){this.#n?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n}});let r=await this.getLogs(e,t,{logId:n,pageSize:1});if(!r||r.logs.length===0){this.#n?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let i=r.logs[0];if(i.logType===`action`||i.logType===`unified`)return i}async getStepLogs(e,t,n){return this.#n?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,r,i){let a=await this.#r?.getStep(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve step log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});return}return a}async getUnifiedLogs(e,t,n){return this.#n?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,r){let i=await this.#r?.getUnifiedLog(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve unified log for requestId ${r}`,category:`OlapClient`});return}return i}async getProviderLogs(e,t,n){return this.#n?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getPlatformLogs(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogs(n)||(this.#n?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getPlatformLogDimensions(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform log dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogDimensions(n)||(this.#n?.warning({message:`Failed to query platform log dimensions, returning empty result`,category:`OlapClient`}),{})}async getProviderLog(e,t,r,i){let a=await this.#r?.getProviderLog(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve provider log for requestId ${r} id ${i}`,category:`OlapClient`});return}return a}async getActionAdvancedLog(e,t,r){let i=await this.#i?.getAction(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve action advanced log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getStepAdvancedLog(e,t,r,i){let a=await this.#i?.getStep(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve step advanced log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});return}return a}async getUnifiedAdvancedLog(e,t,r){let i=await this.#i?.getUnified(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve unified advanced log for requestId ${r}`,category:`OlapClient`});return}return i}async getProviderAdvancedLog(e,t,r,i){let a=await this.#i?.getProvider(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve provider advanced log for requestId ${r} id ${i}`,category:`OlapClient`});return}return a}async getPlatformAdvancedLog(e,t){let r=await this.#i?.getPlatform(e,t);if((0,n.isMissing)(r)){this.#n?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});return}return r}async getPolicyLog(e,t,r,i){let a=await this.#o?.getAction(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve policy log for actionRunId ${i}`,category:`OlapClient`});return}return a}async getDefenderLog(e,t,r){let i=await this.#a?.getAction(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve defender log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getLogsStatsAggregate(e,t,n){return this.#n?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n}}),await this.#r?.getAggregate(e,t,n)??{data:[]}}async getLogsStatsDimensions(e,t,n){return this.#n?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getDimensions(e,t,n)??{}}async getSourceUsage(e,t,n){return this.#n?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSourceUsage(e,t,n)??[]}async getActionsCount(e){if(!this.#r)throw Error(`Cannot count actions: the logs sink is not configured`);return this.#r.getActionsCount(e)}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l})=>$.create({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});var OlapClientManager=class{static{this.olapClientPromise=null}static{this.closingPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l,getOlapClient:u=buildOlapClientInstance}){return this.olapClientPromise||=u({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null,this.closingPromise=null}static async close(e){let t=this.olapClientPromise;if(this.olapClientPromise=null,!t)return this.closingPromise??void 0;let n=this.closingPromise,r=(async()=>{await n?.catch(()=>void 0),await this.drain(t,e)})().finally(()=>{this.closingPromise===r&&(this.closingPromise=null)});return this.closingPromise=r,r}static async drain(e,t){let n,r=!1;try{let i=await Promise.race([e,new Promise((e,t)=>{n=setTimeout(()=>{r=!0,t(Error(`timed out waiting for olap initialisation`))},6e4),n.unref?.()})]);n&&=(clearTimeout(n),void 0),await i.close?.(t)}catch{}finally{n&&clearTimeout(n),r&&e.then(e=>e.close?.(t)).catch(()=>void 0)}}};exports.AuthType=ie,exports.DEFAULT_TOPIC_CLUSTER_MAP=g,exports.Dimension=ee,exports.IntervalType=h,exports.InvalidAuthPairError=InvalidAuthPairError,exports.LogType=f,exports.OlapClient=$,exports.OlapClientManager=OlapClientManager,exports.OrderBy=p,exports.OrderDirection=m,exports.PlatformDimension=te,exports.PolicySink=PolicySink,exports.SourceType=_,exports.StreamType=re,exports.TransportType=ne,exports.getPolicySink=getPolicySink,exports.hasErrorEntries=hasErrorEntries;
239
+ FROM ${L}(${R})
240
+ ${z}
241
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),...toAuthPairParams(e.authPairs),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const Ke={id:`project_unified_logs`,buildQuery:buildUnifiedLogsQuery,buildCountQuery:buildUnifiedLogsCountQuery};var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,t){this.#t=e,this.#n=t,e?.url&&(this.#e=(0,a.createClient)({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){let{data:t}=await this.#a(e);return t}async queryWithPagination(e){let{data:t,total:n}=await this.#a(e);return{data:t,total:n??t.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??t.length}}isReady(){return!!(this.#e&&this.#t?.url)}async close(){await this.#e?.close()}#r(){if(!this.#e)throw this.#n?.error({message:`ClickHouse client not initialized`,category:`ClickHouseClient`,code:`ClientNotReady`}),Error(`ClickHouse client is not initialized`);if(!this.#t?.url)throw this.#n?.warning({message:`Missing ClickHouse URL`,category:`ClickHouseClient`}),Error(`ClickHouseClient - Missing URL`);return this.#e}#i(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`ClickHouseClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`ClickHouseClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#a(e){try{let{data:t,total:n}=await this.#o(e.query,e.params);return{data:this.#i(t,e.schema),total:n}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error running clickhouse query ${e.query.id}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async#o(e,t){let n=this.#r(),{sql:r,params:i}=e.buildQuery(t);this.#n?.debug({message:`Running clickhouse query: ${e.id}`,category:`ClickHouseClient`,context:{query:e.id,params:t}});let a=Date.now(),o=await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json(),s=(Date.now()-a)/1e3,c;if(e.buildCountQuery){let{sql:r,params:i}=e.buildCountQuery(t);c=(await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${o.length} rows`,category:`ClickHouseClient`,context:{query:e.id,rows:o.length,elapsed:s}}),{data:o,total:c}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},B=r.z.preprocess(e=>{if(e instanceof Date)return e;if(typeof e==`string`&&e.length>0)try{return new Date(utcDateTransform(e))}catch(e){throw new r.z.ZodError([{code:r.z.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},r.z.coerce.date()),V=r.z.object({logType:r.z.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:B,startTime:B,endTime:B.optional().nullable().transform(e=>e??void 0),durationMs:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:r.z.coerce.string(),projectSecureId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),H=V.extend({logType:r.z.literal(`action`),actionRunId:r.z.coerce.string(),actionId:r.z.coerce.string(),connectorKey:r.z.coerce.string(),connectorVersion:r.z.coerce.string(),connectorOwner:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:r.z.coerce.string(),accountSecureId:r.z.coerce.string(),actionType:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),mode:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),category:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),actingUserId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:r.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:r.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),policyResult:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),isBackground:r.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:B.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:B.optional().nullable().transform(e=>e??void 0)}),U=V.extend({logType:r.z.literal(`step`),actionRunId:r.z.coerce.string(),stepIndex:r.z.coerce.number(),stepId:r.z.coerce.string(),projectSecureId:r.z.coerce.string(),accountSecureId:r.z.coerce.string(),skipped:r.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:r.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),message:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:r.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),W=V.extend({logType:r.z.literal(`unified`),requestId:r.z.coerce.string(),connectorKey:r.z.coerce.string(),connectorVersion:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:r.z.coerce.string(),accountSecureId:r.z.coerce.string(),mode:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),path:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),actingUserId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:r.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:r.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:r.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:B.optional().nullable().transform(e=>e??void 0),duration:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:B.optional().nullable().transform(e=>e??void 0)}),G=V.extend({logType:r.z.literal(`provider`),requestId:r.z.coerce.string(),id:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:r.z.coerce.string(),mode:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:r.z.coerce.string(),originOwnerId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:r.z.coerce.string(),path:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:r.z.coerce.string(),connectorVersion:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:r.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:r.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:r.z.coerce.string(),accountSecureId:r.z.coerce.string(),status:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:B.optional().nullable().transform(e=>e??void 0),duration:r.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),K=V.extend({logType:r.z.literal(`platform`),eventId:r.z.coerce.string(),eventType:r.z.coerce.string(),service:r.z.coerce.string(),organizationId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:r.z.undefined().optional(),userId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:r.z.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:r.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:r.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:r.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:r.z.record(r.z.string(),r.z.unknown()).optional().nullable().transform(e=>e??void 0)}),qe=r.z.discriminatedUnion(`logType`,[H,U,W,G]),Je=new Set([`success`,`isRead`]),foldTimeBuckets=e=>{let t=new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},q=[`success`,`isWorker`,`isBackground`,`skipped`];var QueryClientNotConfiguredError=class extends Error{constructor(){super(`No ClickHouse query client is configured`),this.name=`QueryClientNotConfiguredError`}};const Ye=15e3;var LogsSink=class{#e;#t;#n;#r;#i;#a(){if(!this.#r?.isReady())throw new QueryClientNotConfiguredError;return this.#r}#o(e){parseLogQueryConditions(e.conditions)}constructor(e,t,n,r,i){this.#e=e,this.#t=r,this.#n=i,this.#i=t,n&&(this.#r=new ClickHouseClient(n,t),this.#i?.debug({message:`LogsSink initialized with the ClickHouse query client`,category:`LogsSink`}))}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#i?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}this.#r?.isReady()?this.#i?.info({message:`Logs sink query client ready: clickhouse`,category:`LogsSink`}):this.#i?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}),this.#i?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#u()}async close(e=3e4){return this.#s??=this.#c(e),this.#s}#s;async#c(e){let t=[];if(this.#e?.producer){let e=this.#e.producer;t.push([`external kafka producer`,()=>e.close()])}if(this.#t?.producer){let e=this.#t.producer;t.push([`internal kafka producer`,()=>e.close()])}if(this.#r){let e=this.#r;t.push([`clickhouse client`,()=>e.close()])}(await Promise.allSettled(t.map(([,t])=>this.#l(t,e)))).forEach((n,r)=>{if(n.status===`rejected`){let i=n.reason instanceof Error?n.reason:Error(String(n.reason)),a=i.name===`LogsSinkCloseTimeout`,o=t[r]?.[0]??`resource`,s=o.includes(`producer`),c={message:a?s?`Timed out closing ${o} after ${e}ms; buffered records may have been lost`:`Timed out releasing ${o} after ${e}ms`:`Error closing ${o}: ${i.message}`,error:i,code:`LogsSinkCloseError`,category:`LogsSink`};a&&s?this.#i?.error(c):this.#i?.warning(c)}})}async#l(e,t){let n,r=new Promise((e,r)=>{n=setTimeout(()=>{let e=Error(`timed out after ${t}ms`);e.name=`LogsSinkCloseTimeout`,r(e)},t),n.unref?.()});try{return await Promise.race([Promise.resolve().then(e),r])}finally{n&&clearTimeout(n)}}async#u(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{let n;try{await Promise.race([t?.connectToBrokers(),new Promise((e,t)=>{n=setTimeout(()=>t(Error(`connectivity probe timed out after ${Ye}ms`)),Ye),n.unref?.()})]),this.#i?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#i?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}finally{n&&clearTimeout(n)}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t,metadata:n})=>this.buildActionLog(e,t,n));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n,r){if(!r?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async sendPlatform(e,t,n){let r=isPlatformLog(e);if(!(r?t:n)?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending platform to log sink (topic: platform)`,category:`LogsSink`});let i=r?e:this.buildPlatformLog(e,t??{});await this.send(`platform`,[i])}async getLogs(e){this.#o(e);let t=this.#a();try{this.#i?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Ae,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} logs (${n.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(n.data),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(e){throw this.#i?.error({message:`Failed to query for logs`,category:`LogsSink`,code:`LogsQueryFailed`,error:e}),e}}async getLastLogs(e,t){this.#o(t);let n=this.#a(),r=e?.ids??[];if(r.length===0)return emptyQueryResult();try{this.#i?.info({message:`Querying last logs for ${r.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await n.queryWithPagination({query:Ne,params:{...t,entities:e}});return this.#i?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){throw this.#i?.error({message:`Failed to query for last logs`,category:`LogsSink`,code:`LastLogsQueryFailed`,error:e}),e}}async getActions(e){let t=this.#a();try{this.#i?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:de,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} action logs (${n.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(n.data,H),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n})).actionLogs[0]}async getSteps(e){let t=this.#a();try{this.#i?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:We,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} step logs (${n.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(n.data,U),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for step logs, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r})).stepLogs[0]}async getUnifiedLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Ke,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} unified logs (${n.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(n.data,W),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n})).unifiedLogs[0]}async getProviderLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Ve,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} provider logs (${n.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(n.data,G),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.error({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,code:`ProviderLogsQueryFailed`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogDimensions(e){let t=this.#a();try{this.#i?.info({message:`Querying platform log dimensions`,category:`LogsSink`,context:{query:e}});let n=await t.query({query:Le,params:e});this.#i?.info({message:`Successfully retrieved ${n.length} platform dimension facets`,category:`LogsSink`});let r={};for(let e of n)r[e.dimension]=Je.has(e.dimension)?e.values.map(e=>({value:e.value===`1`?`true`:`false`,count:e.count})):e.values;return r}catch(e){return this.#i?.error({message:`Failed to query platform log dimensions: ${e instanceof Error?e.message:String(e)}`,category:`LogsSink`,code:`PlatformDimensionsQueryFailed`}),{}}}async getPlatformLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:ze,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} platform logs (${n.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(n.data,K),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:t}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r})).providerLogs[0]}async getAggregate(e,n,r){this.#o(r);let i=this.#a();try{this.#i?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:r}});let{dimensions:a,startTime:o,endTime:s,...c}=r,l=r.intervalType===g.None,u={organizationId:e,projectSecureId:n,...c,...a&&a.length>0&&{dimensions:a.join(`,`)},...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...l&&{pageSize:void 0,pageNumber:void 0}},d=await i.query({query:je,params:u});this.#i?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>(0,t.convertKeysToCamelCase)(e,!0)).map(e=>{let t={...e};for(let e of q)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:l?foldTimeBuckets(f):f}}catch(e){throw this.#i?.error({message:`Failed to query for logs stats aggregate`,category:`LogsSink`,code:`LogsAggregateQueryFailed`,error:e}),e}}async getDimensions(e,t,n){this.#o(n);let r=this.#a();try{this.#i?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n}});let{dimensions:i,startTime:a,endTime:o,...s}=n,c={organizationId:e,projectSecureId:t,...s,dimensions:i.join(`,`),...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await r.query({query:Me,params:c});this.#i?.info({message:`Successfully retrieved ${l.length} dimension facets`,category:`LogsSink`});let u={};for(let e of l)q.includes(e.dimension)?u[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):u[e.dimension]=e.values;return u}catch(e){throw this.#i?.error({message:`Failed to query for logs stats dimensions`,category:`LogsSink`,code:`LogsDimensionsQueryFailed`,error:e}),e}}async getActionsCount(e){let[t]=await this.#a().query({query:pe,params:e});return Number(t?.actions_count??0)}async getSourceUsage(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n}});let{startTime:i,endTime:a,sourceType:o}=n,s={organizationId:e,projectSecureId:t,sourceType:o||void 0,...i&&{startTime:i.toISOString()},...a&&{endTime:a.toISOString()}},c=await r.query({query:He,params:s});return this.#i?.info({message:`Successfully retrieved ${c.length} source usage records`,category:`LogsSink`}),c.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))}catch(e){return this.#i?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}),[]}}#d(e){return(this.#n??_)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#d(e);if(!n)throw this.#i?.error({message:`No cluster routing configured for topic ${e}, dropping ${t.length} log(s)`,category:`KafkaSink`,code:`TopicNotRouted`}),Error(`No cluster routing configured for topic ${e}`);if(n.length===0){this.#i?.debug({message:`Topic ${e} is muted by the topic cluster map, dropping ${t.length} log(s)`,category:`KafkaSink`});return}let r=this.validateLogsBeforeSend(t);if(r.length===0){this.#i?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}r.length<t.length&&this.#i?.warning({message:`${t.length-r.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let i=r.map(t=>({topic:e,value:safeSerialize(t)})),a=await Promise.allSettled(n.map(({cluster:t,producer:n})=>this.#f(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#f(e,t,n,r){if(!t)throw this.#i?.error({message:`Kafka not initialized, dropping message for topic ${n}`,category:`KafkaSink`,code:`KafkaNotReady`,context:{cluster:e}}),Error(`Kafka producer is not initialized`);let i=Date.now();this.#i?.debug({message:`Sending ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{cluster:e}});try{let a=await t.send({messages:r,compression:`gzip`});this.#i?.debug({message:`Successfully sent ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{durationMs:Date.now()-i,topic:n,cluster:e,result:a}})}catch(t){throw this.#i?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.actingUserId&&{actingUserId:e.actingUserId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.allowed!==void 0&&{allowed:t.defenderContext.result.allowed},...t.defenderContext?.result?.tier2Decision!==void 0&&{tier2Decision:t.defenderContext.result.tier2Decision},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},...t.defenderContext?.result?.tier2LatencyMs!==void 0&&{tier2LatencyMs:t.defenderContext.result.tier2LatencyMs},...t.defenderContext?.result?.tier3Decision!==void 0&&{tier3Decision:t.defenderContext.result.tier3Decision},...t.defenderContext?.result?.tier3PromptTokens!==void 0&&{tier3PromptTokens:t.defenderContext.result.tier3PromptTokens},...t.defenderContext?.result?.tier3CompletionTokens!==void 0&&{tier3CompletionTokens:t.defenderContext.result.tier3CompletionTokens},...t.defenderContext?.result?.tier3LatencyMs!==void 0&&{tier3LatencyMs:t.defenderContext.result.tier3LatencyMs},...t.policyContext&&{policyResult:t.policyContext.result},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.actingUserId&&{actingUserId:e.actingUserId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}buildPlatformLog(e,t){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`platform`,eventId:e.eventId??(0,n.randomUUID)(),eventType:e.eventType,service:e.service,...e.organizationId!==void 0&&{organizationId:e.organizationId},...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.userId!==void 0&&{userId:e.userId},...e.userEmail!==void 0&&{userEmail:e.userEmail},...e.action!==void 0&&{action:e.action},...e.resource!==void 0&&{resource:e.resource},...e.resourceId!==void 0&&{resourceId:e.resourceId},...e.sourceType!==void 0&&{sourceType:e.sourceType},...e.sourceId!==void 0&&{sourceId:e.sourceId},...e.authType!==void 0&&{authType:e.authType},...e.authId!==void 0&&{authId:e.authId},...e.userAgent!==void 0&&{userAgent:e.userAgent},...e.ipAddress!==void 0&&{ipAddress:e.ipAddress},...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.agentId!==void 0&&{agentId:e.agentId},...e.transportType!==void 0&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...e.isRead!==void 0&&{isRead:e.isRead},...e.statusCode!==void 0&&{statusCode:e.statusCode},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeObject(e.details)},startTime:e.startTime??r,...t.endTime!==void 0&&{endTime:t.endTime},...i!==void 0&&{durationMs:i},eventTime:r}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof r.ZodError){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#i?.error({message:`Failed to validate ${n} log from the query engine`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.issues,log:safeSerialize(e)}}),Error(`Log data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,qe)}validateLogsBeforeSend(e){let t=[];for(let n of e)try{let e=this.getSchemaForLogType(n.logType).parse(n);t.push(e)}catch(e){e instanceof r.ZodError?this.#i?.warning({message:`Log validation failed before sending to Kafka, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.issues,log:safeSerialize(n)}}):this.#i?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return H;case`step`:return U;case`unified`:return W;case`provider`:return G;case`platform`:return K}}};const readStoredLog=async({bucket:e,key:t,description:n,errorCode:r,category:i,logger:a})=>{try{let r=await e.readText(t);if(r===void 0){a?.debug({message:`No ${n} in storage`,category:i});return}return a?.debug({message:`Retrieved ${n} from storage`,category:i}),JSON.parse(r)}catch(e){throw a?.error({message:`Error when getting ${n} from storage`,error:e,code:r,category:i}),e}},writeStoredLog=async({bucket:e,key:t,body:n,ttlTag:r,expiresAt:i,description:a,errorCode:o,category:s,logger:c})=>{try{await e.write(t,n,{contentType:`application/json`,tags:{ttl:r},expiresAt:i})}catch(e){throw c?.error({message:`Failed to write ${a} to storage at ${t}`,error:e,code:o,category:s}),e}},statStoredLog=async({bucket:e,key:t,description:n,errorCode:r,category:i,logger:a})=>{try{let n=await e.stat(t);return n===void 0?{exists:!1}:{exists:!0,expiresAt:n.expiresAt}}catch(e){throw a?.error({message:`Error when checking ${n} in storage`,error:e,code:r,category:i}),e}},J=64*1024,Xe=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],Ze=[`data.request.body`,`data.input`],readPath=(e,n)=>n.split(`.`).reduce((e,n)=>(0,t.isObject)(e)?e[n]:void 0,e),withPath=(e,n,r)=>{let[i,...a]=n.split(`.`);if(a.length===0)return{...e,[i]:r};let o=e[i];return(0,t.isObject)(o)?{...e,[i]:withPath(o,a.join(`.`),r)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,n)=>{let{kept:r,total:i}=e.reduce((e,r)=>{if(e.total>n)return e;let i=e.total+(0,t.calculateSize)(r);return i>n?{kept:e.kept,total:i}:{kept:e.kept+1,total:i}},{kept:0,total:0});return i>n?e.slice(0,r):e},fitObject=(e,n)=>{let r=Object.entries(e).map(([e,n])=>({key:e,value:n,size:e.length*2+(0,t.calculateSize)(n)})).sort((e,t)=>e.size-t.size),{kept:i,remaining:a}=r.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:n}),o=r.filter(e=>!i.includes(e.key)),s=o.length===0?0:Math.floor(a/o.length);return Object.fromEntries(r.map(e=>[e.key,i.includes(e.key)?e.value:fitValue(e.value,s)]))},fitValue=(e,n)=>{let r=(0,t.calculateSize)(e);return r<=n?e:((0,t.isString)(e)||Array.isArray(e)||(0,t.isObject)(e)&&!(0,t.isDate)(e))&&n<=0?marker(r):(0,t.isString)(e)?fitString(e,n):Array.isArray(e)?fitArray(e,n):(0,t.isObject)(e)&&!(0,t.isDate)(e)?fitObject(e,n):e},payloadFields=e=>Xe.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!(0,t.isMissing)(e)).map(e=>({...e,size:(0,t.calculateSize)(e.value)})),byRetentionPriority=e=>[...e.filter(e=>Ze.includes(e.path)),...e.filter(e=>!Ze.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*J;return n.size<=t.remaining-i?{paths:[...t.paths,n.path],remaining:t.remaining-n.size}:t},{paths:[],remaining:t}).paths,truncateToLimit=(e,t)=>{let n=byRetentionPriority(payloadFields(e)),r=keptWholePaths(n,t),i=n.filter(e=>r.includes(e.path)).reduce((e,t)=>e+t.size,0),a=n.filter(e=>!r.includes(e.path)),o=a.length===0?0:Math.max(J,Math.floor((t-i)/a.length)),s=a.map(e=>({...e,fitted:fitValue(e.value,o)})).filter(e=>e.fitted!==e.value);return{data:s.reduce((e,t)=>withPath(e,t.path,t.fitted),e),truncatedPaths:s.map(e=>e.path)}},withoutPayloads=e=>Xe.reduce((e,t)=>readPath(e,t)===void 0?e:withPath(e,t,void 0),e),isErrorResult=e=>e.success===!1||e.hasStepErrors===!0||(e.statusCode??0)>=400||hasErrorEntries(e.errors),Qe=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],$e=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],et=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],parseActionUrl=e=>e.startsWith(`/`)?new URL(e,`http://path.invalid`):new URL(e),platformKey=(e,t)=>`${e}/platform/${t}.json`,Y=`AdvancedSink`,errorName=e=>e instanceof Error?e.name:`non-Error thrown`;var AdvancedSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n,this.#a=t?.piiRedaction}async initialize(){if(this.#t){this.#i?.warning({message:`No storage provided, advanced sink will not function`,category:Y});return}try{await this.#a?.warmupTier2()}catch(e){this.#i?.warning({message:`PII Tier 2 warmup failed (${errorName(e)}), content scrub will fall back to structural redaction only`,category:`AdvancedSink`,code:`AdvancedSinkPiiWarmupError`})}}async scrubPii(e,n){if(!n?.piiRedactionEnabled||!this.#a||this.truncationMode(n)===`drop`&&(0,t.calculateSize)(e)>this.#n)return e;try{return await this.#a.scrubObject(e)}catch(t){return this.#i?.warning({message:`PII content scrub failed (${errorName(t)}), storing structurally-redacted body only`,category:`AdvancedSink`,code:`AdvancedSinkPiiScrubError`}),e}}requireBucket(){if(!this.#e)throw Error(`Advanced sink bucket is not configured`);return this.#e}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:a}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:a.success,statusCode:a.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(r.mode,r.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&a.success&&!a.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${r.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`AdvancedSink`}),n.push(null);continue}let[e,o,s]=await Promise.all([this.scrubPii(redactBody(r.body,r.headers),t),this.scrubPii((0,i.redactFields)(r.queryParams,i.CensorType.PARTIAL,!0),t),this.scrubPii((0,i.redactFields)(r.pathParams,i.CensorType.PARTIAL,!0),t)]),c={...r,body:e,queryParams:o,pathParams:s},l={...a,body:await this.scrubPii(redactBody(a.body??a.refusal,a.headers),t)},u=this.createActionItem(c,l,t),d=await this.send(u,t?.ttl);n.push(d)}return n}async sendStep(e,t,n){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode,e.actionSourceType))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0&&t.success!==!1&&!hasErrorEntries(t.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let r={...e,inputs:await this.scrubPii((0,i.redactFields)(e.inputs,i.CensorType.PARTIAL,!0),n)},a={...t,outputs:await this.scrubPii((0,i.redactFields)(t.outputs,i.CensorType.PARTIAL,!0),n),errors:await this.scrubPii((0,i.redactFields)(t.errors,i.CensorType.PARTIAL,!0),n)},o=this.createStepItem(r,a,n);try{return await this.send(o,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(redactBody(e.body,e.headers),n)},i={...t,body:await this.scrubPii(redactBody(t.body,t.headers),n)},a=this.createUnifiedItem(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(redactBody(e.body,e.headers),n)},i={...t,body:await this.scrubPii(redactBody(t.body,t.headers),n)},a=this.createProviderItem(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){return this.read(`${e}/${t}/${n}/${n}.json`,`advanced log for actionRunId ${n}`)}async getStep(e,t,n,r){return this.read(`${e}/${t}/${n}/steps/${r}.json`,`step log for actionRunId ${n} stepIndex ${r}`)}async getUnified(e,t,n){return this.read(`${e}/${t}/${n}/${n}.json`,`advanced log for requestId ${n}`)}async getProvider(e,t,n,r){return this.read(`${e}/${t}/${n}/provider/${r}.json`,`provider log for requestId ${n} id ${r}`)}async read(e,t){if(this.#t){this.#i?.warning({message:`No storage available, cannot get ${t} from advanced sink`,category:Y});return}return readStoredLog({bucket:this.requireBucket(),key:e,description:t,errorCode:`AdvancedLogReadError`,category:Y,logger:this.#i})}async send(e,t){if(this.#t)throw Error(`No storage available, cannot send to advanced sink`);let n=this.requireBucket(),r=t===1?`1d`:t===7?`7d`:`30d`,i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);return this.#i?.debug({message:`Storing advanced log in bucket ${n.name} with ttl of ${r}`,category:Y,context:{bucket:n.name,key:e.key,ttlTag:r,expiresAt:a.toISOString()}}),await writeStoredLog({bucket:n,key:e.key,body:e.body,ttlTag:r,expiresAt:a,description:`advanced logs`,errorCode:`AdvancedLogWriteError`,category:Y,logger:this.#i}),{expiresAt:a}}async getObjectExpiry(e){return this.#t?(this.#i?.warning({message:`No storage available, cannot check object expiry`,category:Y}),{exists:!1}):statStoredLog({bucket:this.requireBucket(),key:e,description:`advanced log at ${e}`,errorCode:`AdvancedLogHeadError`,category:Y,logger:this.#i})}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async sendPlatform(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;if(e.organizationId===void 0)return this.#i?.warning({message:`Skipping platform advanced log: no organization to key it under`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType}}),null;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformItem(e,t,e.organizationId,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send platform to advanced sink`,error:t,code:`AdvancedPlatformWriteError`,category:`AdvancedSink`,context:{eventId:e.eventId}}),null}}async getPlatform(e,t){return this.read(platformKey(e,t),`platform advanced log for eventId ${t}`)}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeActionResult(e,t,i,this.#n,this.truncationMode(n))}}createStepItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeStepResult(e,t,i,this.#n,this.truncationMode(n))}}createPlatformItem(e,t,n,r){let i=platformKey(n,e.eventId),a=Math.floor(Date.now()/1e3)+(r??30)*24*60*60;return{key:i,body:this.serializePlatformAdvanced(t,a)}}serializePlatformAdvanced(e,n){let r=(0,i.redactFields)(e.data,i.CensorType.PARTIAL,!0),a={...e.metadata,expirationTime:n,sizeBytes:(0,t.calculateSize)(r)};return this.stringifyPlatform({data:r,metadata:a},a)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeUnifiedResult(e,t,i,this.#n,this.truncationMode(n))}}createProviderItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeProviderResult(e,t,i,this.#n,this.truncationMode(n))}}serializeActionResult(e,n,r,a,o){let s=(0,i.redactHeaders)(e.headers,i.CensorType.PARTIAL),c=(0,i.redactHeaders)(n.headers,i.CensorType.PARTIAL),l=this.processContent(s,e.body,`upload`),u=this.processContent(c,n.body,`download`),d=e.isBackground??isBackgroundLog(e.mode,e.sourceType),f=e.url,p={};if(e.url)try{f=(0,i.redactUrl)(e.url,i.CensorType.PARTIAL);let t=parseActionUrl(f);p=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let m={...p,...(0,t.isObject)(e.queryParams)?e.queryParams:{}},ee={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(s),url:{url:f,path:e.pathParams,queryParams:m},body:l},response:{statusCode:n.statusCode??500,headers:this.filterHeaders(c),body:u},...d?{isBackgroundLog:!0}:{}},metadata:{...d?{isBackgroundLog:!0}:{},expirationTime:r}};return this.serializeAndLimit(ee,a,isErrorResult(n),o)}serializeStepResult(e,t,n,r,i){let a={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,t,n,r,a){let o=(0,i.redactHeaders)(e.headers,i.CensorType.PARTIAL),s=(0,i.redactHeaders)(t.headers,i.CensorType.PARTIAL),c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),d=`/`,f=e.url,p={};if(e.url)try{f=(0,i.redactUrl)(e.url,i.CensorType.PARTIAL);let t=new URL(f);d=t.pathname,p=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let m={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:f,path:d,queryParams:p},body:c},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:l}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(m,r,isErrorResult(t),a)}serializeProviderResult(e,t,n,r,a){let o=(0,i.redactHeaders)(e.headers,i.CensorType.PARTIAL),s=(0,i.redactHeaders)(t.headers,i.CensorType.PARTIAL),c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u,d=``,f=`/`,p={};if(e.url)try{u=(0,i.redactUrl)(e.url,i.CensorType.PARTIAL);let t=new URL(u);d=t.hostname,f=t.pathname,p=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let m={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:u,hostname:d,path:f,queryParams:p},body:c},response:{statusCode:t.statusCode,headers:this.filterHeaders(s),body:l}},metadata:{expirationTime:n}};return this.serializeAndLimit(m,r,isErrorResult(t),a)}serializeAndLimit(e,n,r,i){let a=(0,t.calculateSize)(e);if(i===`complete`)return this.stringifyLog(e,{sizeBytes:a});let o=r&&i===`truncate`?n*this.#r:n;if(a<=o)return this.stringifyLog(e,{sizeBytes:a});if(i===`drop`)return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, dropping payload`,category:`AdvancedSink`,code:`AdvancedLogTooLarge`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r}}),this.stringifyLog({...e,data:{outputs:{error:`Error.TOO_LARGE`}}},{sizeBytes:a,maxSizeBytes:o,truncated:!0});let{data:s,truncatedPaths:c}=truncateToLimit(e,o);return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, storing truncated payload`,category:`AdvancedSink`,code:`AdvancedLogTruncated`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r,truncatedPaths:c}}),this.stringifyLog(s,{sizeBytes:a,maxSizeBytes:o,truncated:!0})}stringifyLog(e,t){let n={...e,metadata:{...e.metadata,...t}};try{return JSON.stringify(n)}catch{return this.#i?.warning({message:`Advanced log payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedLogUnserializable`}),JSON.stringify(withoutPayloads(n))}}filterHeaders(e){if(!e)return;let t={},n=Qe.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return $e.includes(i)||et.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!(0,t.isMissing)(e)){if(!(0,t.isString)(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};const X=2e3,settleWithin=(e,t,n)=>new Promise(r=>{let i=setTimeout(()=>r(n),t);i.unref?.(),e.then(e=>{clearTimeout(i),r(e)})});function defaultProviderFactory(e){let t=new s.OTLPTraceExporter({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`},timeoutMillis:X}),n={[u.ATTR_SERVICE_NAME]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new l.BasicTracerProvider({resource:(0,c.resourceFromAttributes)(n),spanProcessors:[new l.BatchSpanProcessor(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;#i=new Set;#a;#o=!1;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(!this.#r)return;if(this.#i.size>=4){this.#t?.debug({message:`Logfire exports at the limit, leaving spans queued for the next flush`,category:`DatasetsSink`,context:{maxExportsInFlight:4}});return}let e=this.#s()?X:50;await settleWithin(this.#c(this.#r).then(()=>!0),e,!1)||this.#t?.debug({message:`Logfire export still running, not waiting for it`,category:`DatasetsSink`,context:{flushTimeoutMs:e}})}async drain(e=4e3){if(!this.#r)return;let t=[...this.#i,this.#c(this.#r)];await settleWithin(Promise.all(t).then(()=>!0),e,!1)||this.#t?.warning({message:`Logfire exports still running at shutdown, their spans may be lost`,code:`LogfireDrainTimeout`,category:`DatasetsSink`,context:{timeoutMs:e}})}#s(){return this.#o?!1:this.#a===void 0||Date.now()-this.#a>3e5}#c(e){let t=Date.now(),n=!1,r=setTimeout(()=>{n=Date.now()-t>=2250},X);r.unref?.();let i=new Promise(t=>t(e.forceFlush())).then(()=>{this.#a=Date.now(),this.#o=!1},e=>this.#l(e,Date.now()-t,n));return this.#i.add(i),i.finally(()=>{clearTimeout(r),this.#i.delete(i)}),i}#l(e,t,n){if(n){this.#a=void 0,this.#o=!1,this.#t?.debug({message:`Logfire export failed after the process was frozen`,category:`DatasetsSink`,context:{elapsedMs:t,exportTimeoutMs:X,error:String(e)}});return}this.#o=!0,this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`,context:{elapsedMs:t}})}},DatasetsSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async close(e){this.#a??=this.#r.drain?.(e),await this.#a}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,n){if(!n?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let r=0;for(let{input:i,result:a}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,includeBackground:n.includeBackground}}),(0,t.isMissing)(i.body)&&(0,t.isMissing)(a.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if(isBackgroundLog(i.mode,i.sourceType)&&!n.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${i.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(i,a);if((0,t.isMissing)(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if((0,t.exceedsSize)(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}this.send(i,e),r++}r>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${r} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,n){let r=(0,t.isMissing)(e.body)?void 0:(0,t.extractSchema)(e.body),i=(0,t.isMissing)(n.body)?void 0:(0,t.extractSchema)(n.body);if(!((0,t.isMissing)(r)&&(0,t.isMissing)(i)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:r,result:i}}}};const Z=`DefenderSink`;var DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#e)throw Error(`Defender sink bucket is not configured`);return this.#e}async initialize(){if(this.#t){this.#r?.warning({message:`No storage provided, defender sink will not function`,category:Z});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,n){let r=[];for(let{input:i,result:a}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:Z,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,options:{enabled:n?.enabled}}}),!n?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:Z}),r.push(null);continue}if((0,t.isMissing)(a.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:Z,context:{actionRunId:i.actionRunId}}),r.push(null);continue}r.push(await this.send(i,a))}return r}async getAction(e,t,n){if(this.#t){this.#r?.warning({message:`No storage available, cannot get action log from defender sink`,category:Z});return}return readStoredLog({bucket:this.requireBucket(),key:defenderKey(e,t,n),description:`defender log for actionRunId ${n}`,errorCode:`DefenderLogReadError`,category:Z,logger:this.#r})}async send(e,t){if(this.#t)throw Error(`No storage available, cannot send to defender sink`);let n=this.requireBucket(),r=defenderKey(e.organizationId,e.projectSecureId,e.actionRunId),i=Math.floor(Date.now()/1e3)+this.#n*24*60*60,a=new Date(i*1e3),o=`${this.#n}d`;return this.#r?.debug({message:`Storing defender log in bucket ${n.name} with ${this.#n}-day TTL`,category:Z,context:{bucket:n.name,key:r,ttlTag:o,expiresAt:a.toISOString()}}),await writeStoredLog({bucket:n,key:r,body:JSON.stringify(t.defenderContext),ttlTag:o,expiresAt:a,description:`defender log`,errorCode:`DefenderLogWriteError`,category:Z,logger:this.#r}),{expiresAt:a}}};const defenderKey=(e,t,n)=>`${e}/${t}/${n}/defender.json`,Q={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`,piiRedactionEnabled:!1},defender:{enabled:!0},policy:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...Q.logs,...e?.logs},advanced:{...Q.advanced,...e?.advanced},defender:{...Q.defender,...e?.defender},policy:{...Q.policy,...e?.policy},datasets:{...Q.datasets,...e?.datasets}}}function getPolicySink(e,t,n){return new PolicySink(e,t,n)}const $=`PolicySink`;var PolicySink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.ttlDays??365,this.#r=n}async initialize(){if(this.#t){this.#r?.warning({message:`No storage provided, policy sink will not function`,category:$});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,n){let r=[];for(let{input:i,result:a}of e){if(!n?.enabled){r.push(null);continue}if(!this.#e&&!this.#t){r.push(null);continue}if((0,t.isMissing)(a.policyContext)){r.push(null);continue}if(!this.#e)throw Error(`No storage available, cannot send to policy sink`);r.push(await this.send(this.#e,i,a))}return r}async getAction(e,t,n,r){if(this.#t){this.#r?.warning({message:`No storage available, cannot get action log from policy sink`,category:$});return}if(this.#e)return readStoredLog({bucket:this.#e,key:policyKey(e,t,n,r),description:`policy log for actionRunId ${r}`,errorCode:`PolicyLogReadError`,category:$,logger:this.#r})}async send(e,t,n){let r=new Date(Date.now()+this.#n*24*60*60*1e3);return await writeStoredLog({bucket:e,key:policyKey(t.organizationId,t.projectSecureId,t.accountSecureId,t.actionRunId),body:JSON.stringify(n.policyContext),ttlTag:`${this.#n}d`,expiresAt:r,description:`policy log`,errorCode:`PolicyLogWriteError`,category:$,logger:this.#r}),{expiresAt:r}}};const policyKey=(e,t,n,r)=>`${e}/${t}/${n}/${r}/policy.json`,tt=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${tt}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${tt}${e} failed with ${r.status}`);return r},fetchGoogleAccessToken=async e=>{let t=await(await requestMetadata(`/token`,e)).json();if(!t.access_token||typeof t.expires_in!=`number`)throw Error(`Google metadata token response missing access_token or expires_in`);return{accessToken:t.access_token,expiresInSeconds:t.expires_in}},fetchGoogleServiceAccountEmail=async e=>{let t=(await(await requestMetadata(`/email`,e)).text()).trim();if(!t)throw Error(`Google metadata returned an empty service account email`);return t},encodeSegment=e=>Buffer.from(e,`utf8`).toString(`base64url`),nt=__name(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=nt(n);return e?.logger?.warning({message:`Google Kafka token refresh failed, using cached token: ${t.message}`,error:t,code:`GoogleKafkaTokenRefreshFailed`,category:`googleKafkaToken`}),i}throw n}).finally(()=>{r.inflight=void 0}),r.inflight)};return async()=>{try{let[{accessToken:e,expiresAtSeconds:n},r]=await Promise.all([credential(),principal()]);return encodeGoogleKafkaToken(e,{principal:r,issuedAtSeconds:t(),expiresAtSeconds:n})}catch(t){let n=nt(t);throw e?.logger?.error({message:`Failed to mint Google Kafka token: ${n.message}`,error:n,code:`GoogleKafkaTokenError`,category:`googleKafkaToken`}),n}}},resolveSasl=(e,t)=>e.mechanism!==`OAUTHBEARER`||e.token?e:{...e,token:createGoogleKafkaTokenProvider({logger:t})},failedOnClosedConnection=e=>{let{code:t,canRetry:n,errors:r}=e??{};return Array.isArray(r)&&r.length>0?r.every(failedOnClosedConnection):t===`PLT_KFK_NETWORK`&&n===!0},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,a,o,s=new Set,closeQuietly=async e=>{try{await e.close()}catch(e){let t=e instanceof Error?e:Error(String(e));n?.warning({message:`Error closing kafka producer: ${t.message}`,error:t,code:`KafkaProducerCloseError`,category:`buildKafkaClient`})}},dispose=e=>{let t=closeQuietly(e).finally(()=>{s.delete(t)});return s.add(t),t},reconstruct=async e=>{if(a||o)return;let s=Date.now();if(!(s-i<3e4)){i=s;try{let i=r;o=t();let s=await o;if(a){await dispose(s);return}r=s,dispose(i),n?.warning({message:`Kafka producer reconstructed after send failure: ${e.message}`,error:e,code:`KafkaProducerReconstructed`,category:`buildKafkaClient`})}catch(e){let t=e;n?.error({message:`Error reconstructing kafka producer: ${t.message}`,error:t,code:`KafkaProducerReconstructionError`,category:`buildKafkaClient`})}finally{o=void 0}}},close=async()=>(a??=(async()=>{let e=o;for(await closeQuietly(r),e&&await e.catch(()=>void 0);s.size>0;)await Promise.allSettled([...s])})(),a),send=async e=>{let t=r;try{return await t.send(e)}catch(n){if(await reconstruct(n),r!==t&&!a&&failedOnClosedConnection(n))return r.send(e);throw n}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;if(t===`close`)return close;let n=Reflect.get(r,t,r);return typeof n==`function`?n.bind(r):n}})},buildKafkaClient=async(e,t)=>{if(!e)return;let construct=async()=>{let{Producer:n,stringSerializers:r}=await import(`@platformatic/kafka`);return new n({retries:3,retryDelay:1e3,...e,...e.sasl&&{sasl:resolveSasl(e.sasl,t)},serializers:r})};try{return withLazyReconstruction(await construct(),construct,t)}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},toError=e=>e instanceof Error?e:Error(String(e)),createMskKafkaTokenProvider=({region:e,logger:t})=>async()=>{try{let{generateAuthToken:t}=await import(`aws-msk-iam-sasl-signer-js`),{token:n}=await t({region:e});return n}catch(e){let n=toError(e);throw t?.error({message:`Failed to mint MSK Kafka token: ${n.message}`,error:n,code:`MskKafkaTokenError`,category:`mskKafkaToken`}),n}},rotateBootstrapBrokers=(e,t=Math.random)=>{let n=Math.floor(t()*e.length);return[...e.slice(n),...e.slice(0,n)]},buildInternalKafkaClient=async(e,t,n=Math.random)=>{if(!e)return;let{bootstrapBrokers:r,region:i,clientId:a,...o}=e;return buildKafkaClient({bootstrapBrokers:rotateBootstrapBrokers(r,n),clientId:a??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:i,logger:t})},...o},t)},defaultStorage=e=>e?.advanced?.bucket||e?.defender?.bucket||e?.policy?.bucket?(0,o.createStorage)((0,o.storageConfigFromEnv)()):void 0;var rt=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){this.name=`OlapClient`,this.#c=e,this.#l=i??r,this.#u=t,this.#d=a,this.#m=o,this.#f=s,this.#p=c,this.#t=n??defaultStorage(c),this.#n=l}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){let u=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});return await u.initialize(),u}async initialize(){this.#e=await this.#c(this.#l,this.#n);let e=this.#d?{producer:await this.#u(this.#d,this.#n)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#r=new LogsSink(t,this.#n,this.#f,e,this.#m),this.#i=new AdvancedSink(this.#t,this.#p?.advanced,this.#n),this.#a=new DefenderSink(this.#t,this.#p?.defender,this.#n),this.#o=new PolicySink(this.#t,this.#p?.policy,this.#n),this.#s=new DatasetsSink(this.#p?.datasets,this.#n),await this.#r?.initialize(),await this.#i?.initialize(),await this.#s?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async close(e){await Promise.all([this.#r?.close?.(e),this.#s?.close(e)])}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,n){let{logs:r,advanced:i,defender:a,policy:o,datasets:s}=resolveOlapOptions(n);this.#n?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:n,resolvedOptions:{logs:r,advanced:i,defender:a,policy:o,datasets:s}}});for(let n of e)(0,t.isMissing)(n.input.isBackground)&&(n.input.isBackground=isBackgroundLog(n.input.mode,n.input.sourceType));let c=o?.enabled&&this.#o?this.#o.sendActions(e,o).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to policy logs storage: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),l=s?.enabled&&this.#s?this.#s.sendActions(e,s).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[u,d]=await Promise.all([i?.enabled&&this.#i?this.#i.sendActions(e,i).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),a?.enabled&&this.#a?this.#a.sendActions(e,a).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to defender logs storage: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),f=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:u[t]?.expiresAt,defenderExpiresAt:d[t]?.expiresAt}})),p=r?.enabled&&this.#r?this.#r.sendActions(f,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([l,c,p])}async recordStep(e,t,n){await this.recordSteps([{input:e,result:t}],n)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#r&&i.push(this.#r.sendSteps(e,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,r).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to storage: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,n,r){let{logs:i,advanced:a}=resolveOlapOptions(r);this.#n?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:n.success,options:r,resolvedOptions:{logs:i,advanced:a}}}),(0,t.isMissing)(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let o={advancedExpiresAt:(a?.enabled&&this.#i?await this.#i.sendUnified(e,n,a).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};i?.enabled&&this.#r&&await this.#r.sendUnified(e,n,o,i).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#r&&a.push(this.#r.sendProvider(e,t,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to storage: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordPlatform(e,t,n){let r=isPlatformLog(e),i=r&&t&&`data`in t?t:void 0,{logs:a,advanced:o}=resolveOlapOptions(r&&!i?t:n),s=a?.enabled&&this.#r?(r?this.#r.sendPlatform(e,a):this.#r.sendPlatform(e,t??{},a)).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#i?this.#i.sendPlatform(e,i,o).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n){return this.#n?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getLastLogs(e,t,n,r={}){let i={...r,organizationId:e,projectSecureId:t};return this.#n?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#r?.getLastLogs(n,i)||(this.#n?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n){return this.#n?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,n,r){let i=await this.#r?.getAction(e,n,r);if((0,t.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve action log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getLog(e,t,n){this.#n?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n}});let r=await this.getLogs(e,t,{logId:n,pageSize:1});if(!r||r.logs.length===0){this.#n?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let i=r.logs[0];if(i.logType===`action`||i.logType===`unified`)return i}async getStepLogs(e,t,n){return this.#n?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,n,r,i){let a=await this.#r?.getStep(e,n,r,i);if((0,t.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve step log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});return}return a}async getUnifiedLogs(e,t,n){return this.#n?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,n,r){let i=await this.#r?.getUnifiedLog(e,n,r);if((0,t.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve unified log for requestId ${r}`,category:`OlapClient`});return}return i}async getProviderLogs(e,t,n){return this.#n?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getPlatformLogs(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogs(n)||(this.#n?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getPlatformLogDimensions(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform log dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogDimensions(n)||(this.#n?.warning({message:`Failed to query platform log dimensions, returning empty result`,category:`OlapClient`}),{})}async getProviderLog(e,n,r,i){let a=await this.#r?.getProviderLog(e,n,r,i);if((0,t.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve provider log for requestId ${r} id ${i}`,category:`OlapClient`});return}return a}async getActionAdvancedLog(e,n,r){let i=await this.#i?.getAction(e,n,r);if((0,t.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve action advanced log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getStepAdvancedLog(e,n,r,i){let a=await this.#i?.getStep(e,n,r,i);if((0,t.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve step advanced log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});return}return a}async getUnifiedAdvancedLog(e,n,r){let i=await this.#i?.getUnified(e,n,r);if((0,t.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve unified advanced log for requestId ${r}`,category:`OlapClient`});return}return i}async getProviderAdvancedLog(e,n,r,i){let a=await this.#i?.getProvider(e,n,r,i);if((0,t.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve provider advanced log for requestId ${r} id ${i}`,category:`OlapClient`});return}return a}async getPlatformAdvancedLog(e,n){let r=await this.#i?.getPlatform(e,n);if((0,t.isMissing)(r)){this.#n?.debug({message:`Failed to retrieve platform advanced log for eventId ${n}`,category:`OlapClient`});return}return r}async getPolicyLog(e,n,r,i){let a=await this.#o?.getAction(e,n,r,i);if((0,t.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve policy log for actionRunId ${i}`,category:`OlapClient`});return}return a}async getDefenderLog(e,n,r){let i=await this.#a?.getAction(e,n,r);if((0,t.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve defender log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getLogsStatsAggregate(e,t,n){return this.#n?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n}}),await this.#r?.getAggregate(e,t,n)??{data:[]}}async getLogsStatsDimensions(e,t,n){return this.#n?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getDimensions(e,t,n)??{}}async getSourceUsage(e,t,n){return this.#n?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSourceUsage(e,t,n)??[]}async getActionsCount(e){if(!this.#r)throw Error(`Cannot count actions: the logs sink is not configured`);return this.#r.getActionsCount(e)}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l})=>rt.create({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});var OlapClientManager=class{static{this.olapClientPromise=null}static{this.closingPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l,getOlapClient:u=buildOlapClientInstance}){return this.olapClientPromise||=u({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null,this.closingPromise=null}static async close(e){let t=this.olapClientPromise;if(this.olapClientPromise=null,!t)return this.closingPromise??void 0;let n=this.closingPromise,r=(async()=>{await n?.catch(()=>void 0),await this.drain(t,e)})().finally(()=>{this.closingPromise===r&&(this.closingPromise=null)});return this.closingPromise=r,r}static async drain(e,t){let n,r=!1;try{let i=await Promise.race([e,new Promise((e,t)=>{n=setTimeout(()=>{r=!0,t(Error(`timed out waiting for olap initialisation`))},6e4),n.unref?.()})]);n&&=(clearTimeout(n),void 0),await i.close?.(t)}catch{}finally{n&&clearTimeout(n),r&&e.then(e=>e.close?.(t)).catch(()=>void 0)}}};exports.AuthType=ee,exports.DEFAULT_TOPIC_CLUSTER_MAP=_,exports.Dimension=ge,exports.IntervalType=g,exports.InvalidAuthPairError=InvalidAuthPairError,exports.InvalidLogQueryConditionsError=InvalidLogQueryConditionsError,exports.LOG_QUERY_FIELDS=y,exports.LOG_QUERY_OPERATORS=x,exports.LogType=h,exports.OlapClient=rt,exports.OlapClientManager=OlapClientManager,exports.OrderBy=me,exports.OrderDirection=he,exports.PlatformDimension=_e,exports.PolicySink=PolicySink,exports.QueryClientNotConfiguredError=QueryClientNotConfiguredError,exports.SourceType=f,exports.StreamType=m,exports.TransportType=p,exports.getPolicySink=getPolicySink,exports.hasErrorEntries=hasErrorEntries,exports.parseLogQueryConditions=parseLogQueryConditions;