@stackone/olap 3.1.0 → 3.1.1
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 +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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`],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={...i,body:await this.scrubPii(redactBody(i.body,i.headers),t),queryParams:await this.scrubPii((0,r.redactFields)(i.queryParams,r.CensorType.PARTIAL,!0),t)},o={...a,body:await this.scrubPii(redactBody(a.body??a.refusal,a.headers),t)},s=this.createActionItem(e,o,t),c=await this.send(s,t?.ttl);n.push(c)}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))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=new URL(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()}};function defaultProviderFactory(e){let t=new i.OTLPTraceExporter({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),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;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)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;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 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 S=`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:S});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:S,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:S}),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:S,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:S});return}return readStoredLog({bucket:this.requireBucket(),key:defenderKey(e,t,n),description:`defender log for actionRunId ${n}`,errorCode:`DefenderLogReadError`,category:S,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:S,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:S,logger:this.#r}),{expiresAt:a}}};const defenderKey=(e,t,n)=>`${e}/${t}/${n}/defender.json`,pe={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},C=`action_logs_filtered`,w=`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(`.`),T=[...w.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(`, `),E=`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/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`],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={...i,body:await this.scrubPii(redactBody(i.body,i.headers),t),queryParams:await this.scrubPii((0,r.redactFields)(i.queryParams,r.CensorType.PARTIAL,!0),t)},o={...a,body:await this.scrubPii(redactBody(a.body??a.refusal,a.headers),t)},s=this.createActionItem(e,o,t),c=await this.send(s,t?.ttl);n.push(c)}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=new URL(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()}};function defaultProviderFactory(e){let t=new i.OTLPTraceExporter({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),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;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)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;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 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 S=`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:S});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:S,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:S}),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:S,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:S});return}return readStoredLog({bucket:this.requireBucket(),key:defenderKey(e,t,n),description:`defender log for actionRunId ${n}`,errorCode:`DefenderLogReadError`,category:S,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:S,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:S,logger:this.#r}),{expiresAt:a}}};const defenderKey=(e,t,n)=>`${e}/${t}/${n}/defender.json`,pe={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},C=`action_logs_filtered`,w=`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(`.`),T=[...w.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(`, `),E=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
|
|
2
2
|
AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}
|
|
3
3
|
AND ${d}`,toNullableFlag=e=>e===void 0?null:Number(e),buildViewParams=e=>({...Object.fromEntries(w.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 *
|
package/dist/index.d.cts
CHANGED
package/dist/index.d.mts
CHANGED
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./chunk-BhWHdk3m.mjs";import{createStorage as t,storageConfigFromEnv as n}from"@stackone/storage";import{calculateSize as r,convertKeysToCamelCase as i,exceedsSize as a,extractSchema as o,isDate as s,isMissing as c,isObject as l,isString as u,snakeToCamel as d}from"@stackone/utils";import{CensorType as f,redactFields as p,redactFormBody as m,redactHeaders as h,redactUrl as g}from"@stackone/redaction";import{OTLPTraceExporter as _}from"@opentelemetry/exporter-trace-otlp-proto";import{resourceFromAttributes as ee}from"@opentelemetry/resources";import{BasicTracerProvider as te,BatchSpanProcessor as ne}from"@opentelemetry/sdk-trace-base";import{ATTR_SERVICE_NAME as re}from"@opentelemetry/semantic-conventions";import{randomUUID as ie}from"crypto";import{ZodError as ae,z as v}from"zod";import{createClient as oe}from"@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 y=`({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)}),b={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),se={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},ce={Asc:`asc`,Desc:`desc`},x={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},le={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`},ue={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`},S={actions:[`internal`],steps:[`internal`],unified_requests:[`internal`],provider_requests:[`internal`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===b.Platform,C={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`},de={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},fe={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},pe={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},me=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],he=[C.Scheduler,C.DataSync,C.DataSyncV2,C.Internal],ge=[`data_sync`],_e=[C.DataSync,C.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&me.includes(e)||t&&he.includes(t))}function isDataSync(e,t){return!!(e&&ge.includes(e)||t&&_e.includes(t))}const ve=[`content-type`,`contenttype`],contentTypeOf=e=>String(Object.entries(e??{}).find(([e])=>ve.includes(e.toLowerCase()))?.[1]??``).toLowerCase(),parseJson=e=>{try{return{parsed:JSON.parse(e)}}catch{return}},redactBody=(e,t)=>{if(!u(e))return p(e,f.PARTIAL,!0);let n=parseJson(e);return n?redactBody(n.parsed,t):contentTypeOf(t).includes(`application/x-www-form-urlencoded`)?m(e,f.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=>c(e)?!1:Array.isArray(e)||u(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}},ye=64*1024,be=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],w=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>l(e)?e[t]:void 0,e),withPath=(e,t,n)=>{let[r,...i]=t.split(`.`);if(i.length===0)return{...e,[r]:n};let a=e[r];return l(a)?{...e,[r]:withPath(a,i.join(`.`),n)}:{...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:n,total:i}=e.reduce((e,n)=>{if(e.total>t)return e;let i=e.total+r(n);return i>t?{kept:e.kept,total:i}:{kept:e.kept+1,total:i}},{kept:0,total:0});return i>t?e.slice(0,n):e},fitObject=(e,t)=>{let n=Object.entries(e).map(([e,t])=>({key:e,value:t,size:e.length*2+r(t)})).sort((e,t)=>e.size-t.size),{kept:i,remaining:a}=n.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:t}),o=n.filter(e=>!i.includes(e.key)),s=o.length===0?0:Math.floor(a/o.length);return Object.fromEntries(n.map(e=>[e.key,i.includes(e.key)?e.value:fitValue(e.value,s)]))},fitValue=(e,t)=>{let n=r(e);return n<=t?e:(u(e)||Array.isArray(e)||l(e)&&!s(e))&&t<=0?marker(n):u(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):l(e)&&!s(e)?fitObject(e,t):e},payloadFields=e=>be.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!c(e)).map(e=>({...e,size:r(e.value)})),byRetentionPriority=e=>[...e.filter(e=>w.includes(e.path)),...e.filter(e=>!w.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*ye;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(ye,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=>be.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),xe=[`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`],Se=[`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`],Ce=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`,T=`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:T});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`&&r(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:i}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:i.success,statusCode:i.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&&i.success&&!i.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={...r,body:await this.scrubPii(redactBody(r.body,r.headers),t),queryParams:await this.scrubPii(p(r.queryParams,f.PARTIAL,!0),t)},a={...i,body:await this.scrubPii(redactBody(i.body??i.refusal,i.headers),t)},o=this.createActionItem(e,a,t),s=await this.send(o,t?.ttl);n.push(s)}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))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(p(e.inputs,f.PARTIAL,!0),n)},i={...t,outputs:await this.scrubPii(p(t.outputs,f.PARTIAL,!0),n),errors:await this.scrubPii(p(t.errors,f.PARTIAL,!0),n)},a=this.createStepItem(r,i,n);try{return await this.send(a,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:T});return}return readStoredLog({bucket:this.requireBucket(),key:e,description:t,errorCode:`AdvancedLogReadError`,category:T,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:T,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:T,logger:this.#i}),{expiresAt:a}}async getObjectExpiry(e){return this.#t?(this.#i?.warning({message:`No storage available, cannot check object expiry`,category:T}),{exists:!1}):statStoredLog({bucket:this.requireBucket(),key:e,description:`advanced log at ${e}`,errorCode:`AdvancedLogHeadError`,category:T,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 n=p(e.data,f.PARTIAL,!0),i={...e.metadata,expirationTime:t,sizeBytes:r(n)};return this.stringifyPlatform({data:n,metadata:i},i)}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,n,r,i){let a=h(e.headers,f.PARTIAL),o=h(t.headers,f.PARTIAL),s=this.processContent(a,e.body,`upload`),c=this.processContent(o,t.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),d=e.url,p={};if(e.url)try{d=g(e.url,f.PARTIAL);let t=new URL(d);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,...l(e.queryParams)?e.queryParams:{}},_={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:d,path:e.pathParams,queryParams:m},body:s},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:c},...u?{isBackgroundLog:!0}:{}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}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,i){let a=h(e.headers,f.PARTIAL),o=h(t.headers,f.PARTIAL),s=this.processContent(a,e.body,`upload`),c=this.processContent(o,t.body,`download`),l=e.isBackground??isBackgroundLog(e.mode,e.sourceType),u=`/`,d=e.url,p={};if(e.url)try{d=g(e.url,f.PARTIAL);let t=new URL(d);u=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(a),url:{url:d,path:u,queryParams:p},body:s},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:c}},metadata:{...l?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(m,r,isErrorResult(t),i)}serializeProviderResult(e,t,n,r,i){let a=h(e.headers,f.PARTIAL),o=h(t.headers,f.PARTIAL),s=this.processContent(a,e.body,`upload`),c=this.processContent(o,t.body,`download`),l,u=``,d=`/`,p={};if(e.url)try{l=g(e.url,f.PARTIAL);let t=new URL(l);u=t.hostname,d=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(a),url:{url:l,hostname:u,path:d,queryParams:p},body:s},response:{statusCode:t.statusCode,headers:this.filterHeaders(o),body:c}},metadata:{expirationTime:n}};return this.serializeAndLimit(m,r,isErrorResult(t),i)}serializeAndLimit(e,t,n,i){let a=r(e);if(i===`complete`)return this.stringifyLog(e,{sizeBytes:a});let o=n&&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:n}}),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:n,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=xe.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 Se.includes(i)||Ce.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!c(e)){if(!u(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()}};function defaultProviderFactory(e){let t=new _({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[re]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new te({resource:ee(n),spanProcessors:[new ne(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;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)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;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 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 n=0;for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,includeBackground:t.includeBackground}}),c(r.body)&&c(i.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(r,i);if(c(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(a(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}this.send(r,e),n++}n>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${n} 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 n=c(e.body)?void 0:o(e.body),r=c(t.body)?void 0:o(t.body);if(!(c(n)&&c(r)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:n,result:r}}}};const E=`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:E});return}}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:i}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:E,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:E}),n.push(null);continue}if(c(i.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:E,context:{actionRunId:r.actionRunId}}),n.push(null);continue}n.push(await this.send(r,i))}return n}async getAction(e,t,n){if(this.#t){this.#r?.warning({message:`No storage available, cannot get action log from defender sink`,category:E});return}return readStoredLog({bucket:this.requireBucket(),key:defenderKey(e,t,n),description:`defender log for actionRunId ${n}`,errorCode:`DefenderLogReadError`,category:E,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:E,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:E,logger:this.#r}),{expiresAt:a}}};const defenderKey=(e,t,n)=>`${e}/${t}/${n}/defender.json`,we={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},D=`action_logs_filtered`,O=`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(`.`),k=[...O.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(`, `),A=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
|
|
1
|
+
import{t as e}from"./chunk-BhWHdk3m.mjs";import{createStorage as t,storageConfigFromEnv as n}from"@stackone/storage";import{calculateSize as r,convertKeysToCamelCase as i,exceedsSize as a,extractSchema as o,isDate as s,isMissing as c,isObject as l,isString as u,snakeToCamel as d}from"@stackone/utils";import{CensorType as f,redactFields as p,redactFormBody as m,redactHeaders as h,redactUrl as g}from"@stackone/redaction";import{OTLPTraceExporter as _}from"@opentelemetry/exporter-trace-otlp-proto";import{resourceFromAttributes as ee}from"@opentelemetry/resources";import{BasicTracerProvider as te,BatchSpanProcessor as ne}from"@opentelemetry/sdk-trace-base";import{ATTR_SERVICE_NAME as re}from"@opentelemetry/semantic-conventions";import{randomUUID as ie}from"crypto";import{ZodError as ae,z as v}from"zod";import{createClient as oe}from"@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 y=`({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)}),b={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),se={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},ce={Asc:`asc`,Desc:`desc`},x={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},le={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`},ue={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`},S={actions:[`internal`],steps:[`internal`],unified_requests:[`internal`],provider_requests:[`internal`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===b.Platform,C={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`},de={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},fe={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},pe={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},me=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],he=[C.Scheduler,C.DataSync,C.DataSyncV2,C.Internal],ge=[`data_sync`],_e=[C.DataSync,C.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&me.includes(e)||t&&he.includes(t))}function isDataSync(e,t){return!!(e&&ge.includes(e)||t&&_e.includes(t))}const ve=[`content-type`,`contenttype`],contentTypeOf=e=>String(Object.entries(e??{}).find(([e])=>ve.includes(e.toLowerCase()))?.[1]??``).toLowerCase(),parseJson=e=>{try{return{parsed:JSON.parse(e)}}catch{return}},redactBody=(e,t)=>{if(!u(e))return p(e,f.PARTIAL,!0);let n=parseJson(e);return n?redactBody(n.parsed,t):contentTypeOf(t).includes(`application/x-www-form-urlencoded`)?m(e,f.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=>c(e)?!1:Array.isArray(e)||u(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}},ye=64*1024,be=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],w=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>l(e)?e[t]:void 0,e),withPath=(e,t,n)=>{let[r,...i]=t.split(`.`);if(i.length===0)return{...e,[r]:n};let a=e[r];return l(a)?{...e,[r]:withPath(a,i.join(`.`),n)}:{...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:n,total:i}=e.reduce((e,n)=>{if(e.total>t)return e;let i=e.total+r(n);return i>t?{kept:e.kept,total:i}:{kept:e.kept+1,total:i}},{kept:0,total:0});return i>t?e.slice(0,n):e},fitObject=(e,t)=>{let n=Object.entries(e).map(([e,t])=>({key:e,value:t,size:e.length*2+r(t)})).sort((e,t)=>e.size-t.size),{kept:i,remaining:a}=n.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:t}),o=n.filter(e=>!i.includes(e.key)),s=o.length===0?0:Math.floor(a/o.length);return Object.fromEntries(n.map(e=>[e.key,i.includes(e.key)?e.value:fitValue(e.value,s)]))},fitValue=(e,t)=>{let n=r(e);return n<=t?e:(u(e)||Array.isArray(e)||l(e)&&!s(e))&&t<=0?marker(n):u(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):l(e)&&!s(e)?fitObject(e,t):e},payloadFields=e=>be.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!c(e)).map(e=>({...e,size:r(e.value)})),byRetentionPriority=e=>[...e.filter(e=>w.includes(e.path)),...e.filter(e=>!w.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*ye;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(ye,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=>be.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),xe=[`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`],Se=[`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`],Ce=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`,T=`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:T});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`&&r(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:i}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:i.success,statusCode:i.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&&i.success&&!i.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={...r,body:await this.scrubPii(redactBody(r.body,r.headers),t),queryParams:await this.scrubPii(p(r.queryParams,f.PARTIAL,!0),t)},a={...i,body:await this.scrubPii(redactBody(i.body??i.refusal,i.headers),t)},o=this.createActionItem(e,a,t),s=await this.send(o,t?.ttl);n.push(s)}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(p(e.inputs,f.PARTIAL,!0),n)},i={...t,outputs:await this.scrubPii(p(t.outputs,f.PARTIAL,!0),n),errors:await this.scrubPii(p(t.errors,f.PARTIAL,!0),n)},a=this.createStepItem(r,i,n);try{return await this.send(a,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:T});return}return readStoredLog({bucket:this.requireBucket(),key:e,description:t,errorCode:`AdvancedLogReadError`,category:T,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:T,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:T,logger:this.#i}),{expiresAt:a}}async getObjectExpiry(e){return this.#t?(this.#i?.warning({message:`No storage available, cannot check object expiry`,category:T}),{exists:!1}):statStoredLog({bucket:this.requireBucket(),key:e,description:`advanced log at ${e}`,errorCode:`AdvancedLogHeadError`,category:T,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 n=p(e.data,f.PARTIAL,!0),i={...e.metadata,expirationTime:t,sizeBytes:r(n)};return this.stringifyPlatform({data:n,metadata:i},i)}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,n,r,i){let a=h(e.headers,f.PARTIAL),o=h(t.headers,f.PARTIAL),s=this.processContent(a,e.body,`upload`),c=this.processContent(o,t.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),d=e.url,p={};if(e.url)try{d=g(e.url,f.PARTIAL);let t=new URL(d);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,...l(e.queryParams)?e.queryParams:{}},_={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:d,path:e.pathParams,queryParams:m},body:s},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:c},...u?{isBackgroundLog:!0}:{}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}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,i){let a=h(e.headers,f.PARTIAL),o=h(t.headers,f.PARTIAL),s=this.processContent(a,e.body,`upload`),c=this.processContent(o,t.body,`download`),l=e.isBackground??isBackgroundLog(e.mode,e.sourceType),u=`/`,d=e.url,p={};if(e.url)try{d=g(e.url,f.PARTIAL);let t=new URL(d);u=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(a),url:{url:d,path:u,queryParams:p},body:s},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:c}},metadata:{...l?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(m,r,isErrorResult(t),i)}serializeProviderResult(e,t,n,r,i){let a=h(e.headers,f.PARTIAL),o=h(t.headers,f.PARTIAL),s=this.processContent(a,e.body,`upload`),c=this.processContent(o,t.body,`download`),l,u=``,d=`/`,p={};if(e.url)try{l=g(e.url,f.PARTIAL);let t=new URL(l);u=t.hostname,d=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(a),url:{url:l,hostname:u,path:d,queryParams:p},body:s},response:{statusCode:t.statusCode,headers:this.filterHeaders(o),body:c}},metadata:{expirationTime:n}};return this.serializeAndLimit(m,r,isErrorResult(t),i)}serializeAndLimit(e,t,n,i){let a=r(e);if(i===`complete`)return this.stringifyLog(e,{sizeBytes:a});let o=n&&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:n}}),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:n,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=xe.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 Se.includes(i)||Ce.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!c(e)){if(!u(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()}};function defaultProviderFactory(e){let t=new _({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[re]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new te({resource:ee(n),spanProcessors:[new ne(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;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)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;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 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 n=0;for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,includeBackground:t.includeBackground}}),c(r.body)&&c(i.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(r,i);if(c(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(a(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}this.send(r,e),n++}n>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${n} 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 n=c(e.body)?void 0:o(e.body),r=c(t.body)?void 0:o(t.body);if(!(c(n)&&c(r)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:n,result:r}}}};const E=`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:E});return}}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:i}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:E,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:E}),n.push(null);continue}if(c(i.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:E,context:{actionRunId:r.actionRunId}}),n.push(null);continue}n.push(await this.send(r,i))}return n}async getAction(e,t,n){if(this.#t){this.#r?.warning({message:`No storage available, cannot get action log from defender sink`,category:E});return}return readStoredLog({bucket:this.requireBucket(),key:defenderKey(e,t,n),description:`defender log for actionRunId ${n}`,errorCode:`DefenderLogReadError`,category:E,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:E,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:E,logger:this.#r}),{expiresAt:a}}};const defenderKey=(e,t,n)=>`${e}/${t}/${n}/defender.json`,we={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},D=`action_logs_filtered`,O=`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(`.`),k=[...O.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(`, `),A=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
|
|
2
2
|
AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}
|
|
3
3
|
AND ${y}`,toNullableFlag=e=>e===void 0?null:Number(e),buildViewParams=e=>({...Object.fromEntries(O.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 *
|