@stackone/olap 3.6.0 → 3.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -5
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +3 -0
- package/dist/index.d.mts +3 -0
- package/dist/index.mjs +31 -31
- package/package.json +7 -6
package/README.md
CHANGED
|
@@ -49,9 +49,9 @@ $ pnpm lint
|
|
|
49
49
|
$ pnpm lint:fix
|
|
50
50
|
```
|
|
51
51
|
|
|
52
|
-
## Where advanced, defender and
|
|
52
|
+
## Where advanced, defender, policy and schema logs are stored
|
|
53
53
|
|
|
54
|
-
The advanced, defender and policy sinks write through [`@stackone/storage`](../storage/README.md), so
|
|
54
|
+
The advanced, defender and policy sinks, and the datasets sink's schema logs, write through [`@stackone/storage`](../storage/README.md), so
|
|
55
55
|
the same build stores them in S3, MinIO or GCS depending on where it is deployed. olap has no AWS SDK
|
|
56
56
|
dependency of its own.
|
|
57
57
|
|
|
@@ -65,6 +65,7 @@ const olap = await OlapClientManager.getInstance({
|
|
|
65
65
|
advanced: { bucket: process.env.ADVANCED_LOGS_BUCKET },
|
|
66
66
|
defender: { bucket: process.env.DEFENDER_LOGS_BUCKET },
|
|
67
67
|
policy: { bucket: process.env.POLICY_LOGS_BUCKET },
|
|
68
|
+
datasets: { bucket: process.env.SCHEMA_LOGS_BUCKET, region: process.env.AWS_REGION },
|
|
68
69
|
},
|
|
69
70
|
// ...
|
|
70
71
|
});
|
|
@@ -74,9 +75,15 @@ const olap = await OlapClientManager.getInstance({
|
|
|
74
75
|
but only when one of those sinks has a bucket, so a service that stores nothing never reads a storage
|
|
75
76
|
config. Passing it is how a service tunes retries and timeouts for these writes.
|
|
76
77
|
|
|
77
|
-
Each log is JSON with a `ttl` tag (`1d`, `7d` or `30d` for advanced
|
|
78
|
-
defender and policy) and an `expiresAt`, so bucket lifecycle rules can
|
|
79
|
-
tag on S3 and MinIO, by `daysSinceCustomTime` on GCS.
|
|
78
|
+
Each advanced, defender and policy log is JSON with a `ttl` tag (`1d`, `7d` or `30d` for advanced
|
|
79
|
+
logs; the sink's `ttlDays` for defender and policy) and an `expiresAt`, so bucket lifecycle rules can
|
|
80
|
+
expire it on every cloud — by tag on S3 and MinIO, by `daysSinceCustomTime` on GCS.
|
|
81
|
+
|
|
82
|
+
Schema logs are kept, not expired: one JSON object per action at
|
|
83
|
+
`action_schemas/<organizationId>/<actionId>/<YYYY-MM-DD>/<actionRunId>-<uuid>.json`, written only
|
|
84
|
+
when the call's `datasets.enabled` option is true (connect-sdk sets it from
|
|
85
|
+
`settings.olap.datasets.enabled`, and absent means false). `datasets.storage` gives the sink its own
|
|
86
|
+
storage, for a bucket in another region than the shared one.
|
|
80
87
|
|
|
81
88
|
### Upgrading from 1.x
|
|
82
89
|
|
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/redaction"),n=require("@stackone/utils"),r=require("crypto"),i=require("zod"),a=require("@clickhouse/client"),o=require("@stackone/storage"),s=require("@opentelemetry/exporter-trace-otlp-proto"),c=require("@opentelemetry/resources"),l=require("@opentelemetry/sdk-trace
|
|
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/redaction"),n=require("@stackone/utils"),r=require("crypto"),i=require("zod"),a=require("@clickhouse/client"),o=require("@stackone/storage"),s=require("@opentelemetry/exporter-trace-otlp-proto"),c=require("@opentelemetry/resources"),l=require("@opentelemetry/sdk-trace"),u=require("@opentelemetry/semantic-conventions");const d=/* @__PURE__ */ new Set([`idempotency-key`,`x-hub-version`,`x-request-id`]),f=/* @__PURE__ */ new Set([`authorization`,`cookie`,`x-api-key`]),codePointsOf=(e,t)=>Array.from(e.slice(0,t*2)).slice(0,t),joinedWithin=e=>e.reduce((e,t)=>{let n=e.shown===``?``:`, `,r=e.room-n.length;if(r<=0)return{...e,room:0};let i=codePointsOf(t,r);return{shown:e.shown+n+i.join(``),room:r-i.length}},{shown:``,room:256}).shown.trim(),textsOf=e=>(Array.isArray(e)?e:[e]).filter(n.isString).map(e=>e.trim()).filter(e=>e!==``),callerHeadersOf=e=>{let n=[...Object.entries(e??{}).map(([e,t])=>[e.toLowerCase(),t]).filter(([e])=>d.has(e)||f.has(e)).reduce((e,[t,n])=>e.set(t,[...e.get(t)??[],...textsOf(n)]),/* @__PURE__ */ new Map)].filter(([,e])=>e.length>0).map(([e,n])=>[e,f.has(e)?t.REDACT_CENSOR:joinedWithin(n)]);return n.length>0?Object.fromEntries(n):void 0};function toArray(e){return e==null?[]:Array.isArray(e)?e:[e]}function toCsvArray(e){return toArray(e).flatMap(e=>e.split(`,`)).map(e=>e.trim()).filter(e=>e.length>0)}function toStatusCodes(e){let t=toArray(e);if(t.length===0)return[];let n=t.map(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length===0?NaN:Number(t)}).filter(e=>Number.isInteger(e)&&e>=-32768&&e<=32767);return n.length>0?n:[-1]}function toClickHouseDate(e){return e?(typeof e==`string`?new Date(e):e).toISOString().replace(`T`,` `).replace(`Z`,``):null}function buildPaginationParams(e,t){let n=Math.min(t??100,1e3);return{limit:n,offset:(Math.max(e??1,1)-1)*n}}function sanitizeOrderDirection(e){return e?.toLowerCase()===`asc`?`ASC`:`DESC`}function sanitizeOrderBy(e,t,n){return e?t[e]??n:n}function buildArrayFilter(e,t,n=`String`){return`({${t}:Array(${n})} = [] OR ${e} IN {${t}:Array(${n})})`}const narrowArrayFilter=(e,t)=>{let n=e.length===0?[...t]:t.filter(t=>e.includes(t));return n.length>0?n:void 0},p=`({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)}),m={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`},h={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},ee={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},te={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},ne=[`refresh_authentication`,`data_sync`,`test_actions`,`webhook_setup`],re=[m.Scheduler,m.DataSync,m.DataSyncV2,m.Internal],ie=[`data_sync`],ae=[m.DataSync,m.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&ne.includes(e)||t&&re.includes(t))}function isDataSync(e,t){return!!(e&&ie.includes(e)||t&&ae.includes(t))}const oe=[`content-type`,`contenttype`],contentTypeOf=e=>String(Object.entries(e??{}).find(([e])=>oe.includes(e.toLowerCase()))?.[1]??``).toLowerCase(),parseJson=e=>{try{return{parsed:JSON.parse(e)}}catch{return}},redactBody=(e,r)=>{if(!(0,n.isString)(e))return(0,t.redactFields)(e,t.CensorType.PARTIAL,!0);let i=parseJson(e);return i?redactBody(i.parsed,r):contentTypeOf(r).includes(`application/x-www-form-urlencoded`)?(0,t.redactFormBody)(e,t.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||typeof e!=`object`||Object.keys(e).length>0,se={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},ce=`action_logs_filtered`,le=/* @__PURE__ */ `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(`.`),ue=[...le.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(`, `),de=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
|
|
2
2
|
AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}
|
|
3
3
|
AND ${p}`,toNullableFlag=e=>e===void 0?null:Number(e),buildViewParams=e=>({...Object.fromEntries(le.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),r=sanitizeOrderBy(e.orderBy,se,`eventTime`),i=sanitizeOrderDirection(e.orderDirection);return{sql:`
|
|
4
4
|
SELECT *
|
|
@@ -238,4 +238,4 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
238
238
|
SELECT count() as total
|
|
239
239
|
FROM ${L}(${R})
|
|
240
240
|
${z}
|
|
241
|
-
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),...toAuthPairParams(e.authPairs),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const Je={id:`project_unified_logs`,buildQuery:buildUnifiedLogsQuery,buildCountQuery:buildUnifiedLogsCountQuery};var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,t){this.#t=e,this.#n=t,e?.url&&(this.#e=(0,a.createClient)({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){let{data:t}=await this.#a(e);return t}async queryWithPagination(e){let{data:t,total:n}=await this.#a(e);return{data:t,total:n??t.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??t.length}}isReady(){return!!(this.#e&&this.#t?.url)}async close(){await this.#e?.close()}#r(){if(!this.#e)throw this.#n?.error({message:`ClickHouse client not initialized`,category:`ClickHouseClient`,code:`ClientNotReady`}),Error(`ClickHouse client is not initialized`);if(!this.#t?.url)throw this.#n?.warning({message:`Missing ClickHouse URL`,category:`ClickHouseClient`}),Error(`ClickHouseClient - Missing URL`);return this.#e}#i(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`ClickHouseClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`ClickHouseClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#a(e){try{let{data:t,total:n}=await this.#o(e.query,e.params);return{data:this.#i(t,e.schema),total:n}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error running clickhouse query ${e.query.id}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async#o(e,t){let n=this.#r(),{sql:r,params:i}=e.buildQuery(t);this.#n?.debug({message:`Running clickhouse query: ${e.id}`,category:`ClickHouseClient`,context:{query:e.id,params:t}});let a=Date.now(),o=await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json(),s=(Date.now()-a)/1e3,c;if(e.buildCountQuery){let{sql:r,params:i}=e.buildCountQuery(t);c=(await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${o.length} rows`,category:`ClickHouseClient`,context:{query:e.id,rows:o.length,elapsed:s}}),{data:o,total:c}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return(/* @__PURE__ */ new Date(t+`Z`)).toISOString()},B=i.z.preprocess(e=>{if(e instanceof Date)return e;if(typeof e==`string`&&e.length>0)try{return new Date(utcDateTransform(e))}catch(e){throw new i.z.ZodError([{code:i.z.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},i.z.coerce.date()),V=i.z.object({logType:i.z.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:B,startTime:B,endTime:B.optional().nullable().transform(e=>e??void 0),durationMs:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:i.z.coerce.string(),projectSecureId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),H=V.extend({logType:i.z.literal(`action`),actionRunId:i.z.coerce.string(),actionId:i.z.coerce.string(),connectorKey:i.z.coerce.string(),connectorVersion:i.z.coerce.string(),connectorOwner:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:i.z.coerce.string(),accountSecureId:i.z.coerce.string(),actionType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),mode:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),category:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),actingUserId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),policyResult:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),isBackground:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:B.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:B.optional().nullable().transform(e=>e??void 0)}),U=V.extend({logType:i.z.literal(`step`),actionRunId:i.z.coerce.string(),stepIndex:i.z.coerce.number(),stepId:i.z.coerce.string(),projectSecureId:i.z.coerce.string(),accountSecureId:i.z.coerce.string(),skipped:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),message:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:i.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),W=V.extend({logType:i.z.literal(`unified`),requestId:i.z.coerce.string(),connectorKey:i.z.coerce.string(),connectorVersion:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:i.z.coerce.string(),accountSecureId:i.z.coerce.string(),mode:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),path:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),actingUserId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:B.optional().nullable().transform(e=>e??void 0),duration:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:B.optional().nullable().transform(e=>e??void 0)}),G=V.extend({logType:i.z.literal(`provider`),requestId:i.z.coerce.string(),id:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:i.z.coerce.string(),mode:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:i.z.coerce.string(),originOwnerId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:i.z.coerce.string(),path:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:i.z.coerce.string(),connectorVersion:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:i.z.coerce.string(),accountSecureId:i.z.coerce.string(),status:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:B.optional().nullable().transform(e=>e??void 0),duration:i.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),K=V.extend({logType:i.z.literal(`platform`),eventId:i.z.coerce.string(),eventType:i.z.coerce.string(),service:i.z.coerce.string(),organizationId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:i.z.undefined().optional(),userId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:i.z.record(i.z.string(),i.z.unknown()).optional().nullable().transform(e=>e??void 0)}),Ye=i.z.discriminatedUnion(`logType`,[H,U,W,G]),Xe=/* @__PURE__ */ new Set([`success`,`isRead`]),foldTimeBuckets=e=>{let t=/* @__PURE__ */ new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},q=[`success`,`isWorker`,`isBackground`,`skipped`];var QueryClientNotConfiguredError=class extends Error{constructor(){super(`No ClickHouse query client is configured`),this.name=`QueryClientNotConfiguredError`}};const Ze=15e3;var LogsSink=class{#e;#t;#n;#r;#i;#a(){if(!this.#r?.isReady())throw new QueryClientNotConfiguredError;return this.#r}#o(e){parseLogQueryConditions(e.conditions)}constructor(e,t,n,r,i){this.#e=e,this.#t=r,this.#n=i,this.#i=t,n&&(this.#r=new ClickHouseClient(n,t),this.#i?.debug({message:`LogsSink initialized with the ClickHouse query client`,category:`LogsSink`}))}async initialize(){!this.#e?.producer&&!this.#t?.producer?this.#i?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`}):(this.#r?.isReady()?this.#i?.info({message:`Logs sink query client ready: clickhouse`,category:`LogsSink`}):this.#i?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}),this.#i?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#u())}async close(e=3e4){return this.#s??=this.#c(e),this.#s}#s;async#c(e){let t=[];if(this.#e?.producer){let e=this.#e.producer;t.push([`external kafka producer`,()=>e.close()])}if(this.#t?.producer){let e=this.#t.producer;t.push([`internal kafka producer`,()=>e.close()])}if(this.#r){let e=this.#r;t.push([`clickhouse client`,()=>e.close()])}(await Promise.allSettled(t.map(([,t])=>this.#l(t,e)))).forEach((n,r)=>{if(n.status===`rejected`){let i=n.reason instanceof Error?n.reason:Error(String(n.reason)),a=i.name===`LogsSinkCloseTimeout`,o=t[r]?.[0]??`resource`,s=o.includes(`producer`),c={message:a?s?`Timed out closing ${o} after ${e}ms; buffered records may have been lost`:`Timed out releasing ${o} after ${e}ms`:`Error closing ${o}: ${i.message}`,error:i,code:`LogsSinkCloseError`,category:`LogsSink`};a&&s?this.#i?.error(c):this.#i?.warning(c)}})}async#l(e,t){let n,r=new Promise((e,r)=>{n=setTimeout(()=>{let e=/* @__PURE__ */ Error(`timed out after ${t}ms`);e.name=`LogsSinkCloseTimeout`,r(e)},t),n.unref?.()});try{return await Promise.race([Promise.resolve().then(e),r])}finally{n&&clearTimeout(n)}}async#u(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{let n;try{await Promise.race([t?.connectToBrokers(),new Promise((e,t)=>{n=setTimeout(()=>t(/* @__PURE__ */ Error(`connectivity probe timed out after ${Ze}ms`)),Ze),n.unref?.()})]),this.#i?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#i?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}finally{n&&clearTimeout(n)}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t,metadata:n})=>this.buildActionLog(e,t,n));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n,r){if(!r?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async sendPlatform(e,t,n){let r=isPlatformLog(e);if(!(r?t:n)?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending platform to log sink (topic: platform)`,category:`LogsSink`});let i=r?e:this.buildPlatformLog(e,t??{});await this.send(`platform`,[i])}async getLogs(e){this.#o(e);let t=this.#a();try{this.#i?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:je,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} logs (${n.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(n.data),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(e){throw this.#i?.error({message:`Failed to query for logs`,category:`LogsSink`,code:`LogsQueryFailed`,error:e}),e}}async getLastLogs(e,t){this.#o(t);let n=this.#a(),r=e?.ids??[];if(r.length===0)return emptyQueryResult();try{this.#i?.info({message:`Querying last logs for ${r.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await n.queryWithPagination({query:Pe,params:{...t,entities:e}});return this.#i?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){throw this.#i?.error({message:`Failed to query for last logs`,category:`LogsSink`,code:`LastLogsQueryFailed`,error:e}),e}}async getActions(e){let t=this.#a();try{this.#i?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:fe,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} action logs (${n.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(n.data,H),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n})).actionLogs[0]}async getSteps(e){let t=this.#a();try{this.#i?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Ke,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} step logs (${n.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(n.data,U),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for step logs, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r})).stepLogs[0]}async getUnifiedLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Je,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} unified logs (${n.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(n.data,W),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n})).unifiedLogs[0]}async getProviderLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Ue,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} provider logs (${n.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(n.data,G),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.error({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,code:`ProviderLogsQueryFailed`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogDimensions(e){let t=this.#a();try{this.#i?.info({message:`Querying platform log dimensions`,category:`LogsSink`,context:{query:e}});let n=await t.query({query:ze,params:e});this.#i?.info({message:`Successfully retrieved ${n.length} platform dimension facets`,category:`LogsSink`});let r={};for(let e of n)r[e.dimension]=Xe.has(e.dimension)?e.values.map(e=>({value:e.value===`1`?`true`:`false`,count:e.count})):e.values;return r}catch(e){return this.#i?.error({message:`Failed to query platform log dimensions: ${e instanceof Error?e.message:String(e)}`,category:`LogsSink`,code:`PlatformDimensionsQueryFailed`}),{}}}async getPlatformLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Ve,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} platform logs (${n.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(n.data,K),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:t}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r})).providerLogs[0]}async getAggregate(e,t,r){this.#o(r);let i=this.#a();try{this.#i?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:r}});let{dimensions:a,startTime:o,endTime:s,...c}=r,l=r.intervalType===_.None,u={organizationId:e,projectSecureId:t,...c,...a&&a.length>0&&{dimensions:a.join(`,`)},...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...l&&{pageSize:void 0,pageNumber:void 0}},d=await i.query({query:Me,params:u});this.#i?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>(0,n.convertKeysToCamelCase)(e,!0)).map(e=>{let t={...e};for(let e of q)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:l?foldTimeBuckets(f):f}}catch(e){throw this.#i?.error({message:`Failed to query for logs stats aggregate`,category:`LogsSink`,code:`LogsAggregateQueryFailed`,error:e}),e}}async getDimensions(e,t,n){this.#o(n);let r=this.#a();try{this.#i?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n}});let{dimensions:i,startTime:a,endTime:o,...s}=n,c={organizationId:e,projectSecureId:t,...s,dimensions:i.join(`,`),...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await r.query({query:Ne,params:c});this.#i?.info({message:`Successfully retrieved ${l.length} dimension facets`,category:`LogsSink`});let u={};for(let e of l)q.includes(e.dimension)?u[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):u[e.dimension]=e.values;return u}catch(e){throw this.#i?.error({message:`Failed to query for logs stats dimensions`,category:`LogsSink`,code:`LogsDimensionsQueryFailed`,error:e}),e}}async getActionsCount(e){let[t]=await this.#a().query({query:me,params:e});return Number(t?.actions_count??0)}async getSourceUsage(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n}});let{startTime:i,endTime:a,sourceType:o}=n,s={organizationId:e,projectSecureId:t,sourceType:o||void 0,...i&&{startTime:i.toISOString()},...a&&{endTime:a.toISOString()}},c=await r.query({query:We,params:s});return this.#i?.info({message:`Successfully retrieved ${c.length} source usage records`,category:`LogsSink`}),c.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))}catch(e){return this.#i?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}),[]}}#d(e){return(this.#n??v)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#d(e);if(!n)throw this.#i?.error({message:`No cluster routing configured for topic ${e}, dropping ${t.length} log(s)`,category:`KafkaSink`,code:`TopicNotRouted`}),Error(`No cluster routing configured for topic ${e}`);if(n.length===0){this.#i?.debug({message:`Topic ${e} is muted by the topic cluster map, dropping ${t.length} log(s)`,category:`KafkaSink`});return}let r=this.validateLogsBeforeSend(t);if(r.length===0){this.#i?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}r.length<t.length&&this.#i?.warning({message:`${t.length-r.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let i=r.map(t=>({topic:e,value:safeSerialize(t)})),a=await Promise.allSettled(n.map(({cluster:t,producer:n})=>this.#f(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#f(e,t,n,r){if(!t)throw this.#i?.error({message:`Kafka not initialized, dropping message for topic ${n}`,category:`KafkaSink`,code:`KafkaNotReady`,context:{cluster:e}}),Error(`Kafka producer is not initialized`);let i=Date.now();this.#i?.debug({message:`Sending ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{cluster:e}});try{let a=await t.send({messages:r,compression:`gzip`});this.#i?.debug({message:`Successfully sent ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{durationMs:Date.now()-i,topic:n,cluster:e,result:a}})}catch(t){throw this.#i?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=/* @__PURE__ */ new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.actingUserId&&{actingUserId:e.actingUserId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.allowed!==void 0&&{allowed:t.defenderContext.result.allowed},...t.defenderContext?.result?.tier2Decision!==void 0&&{tier2Decision:t.defenderContext.result.tier2Decision},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},...t.defenderContext?.result?.tier2LatencyMs!==void 0&&{tier2LatencyMs:t.defenderContext.result.tier2LatencyMs},...t.defenderContext?.result?.tier3Decision!==void 0&&{tier3Decision:t.defenderContext.result.tier3Decision},...t.defenderContext?.result?.tier3PromptTokens!==void 0&&{tier3PromptTokens:t.defenderContext.result.tier3PromptTokens},...t.defenderContext?.result?.tier3CompletionTokens!==void 0&&{tier3CompletionTokens:t.defenderContext.result.tier3CompletionTokens},...t.defenderContext?.result?.tier3LatencyMs!==void 0&&{tier3LatencyMs:t.defenderContext.result.tier3LatencyMs},...t.policyContext&&{policyResult:t.policyContext.result},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=/* @__PURE__ */ new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=/* @__PURE__ */ new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.actingUserId&&{actingUserId:e.actingUserId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=/* @__PURE__ */ new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}buildPlatformLog(e,t){let n=/* @__PURE__ */ new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`platform`,eventId:e.eventId??(0,r.randomUUID)(),eventType:e.eventType,service:e.service,...e.organizationId!==void 0&&{organizationId:e.organizationId},...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.userId!==void 0&&{userId:e.userId},...e.userEmail!==void 0&&{userEmail:e.userEmail},...e.action!==void 0&&{action:e.action},...e.resource!==void 0&&{resource:e.resource},...e.resourceId!==void 0&&{resourceId:e.resourceId},...e.sourceType!==void 0&&{sourceType:e.sourceType},...e.sourceId!==void 0&&{sourceId:e.sourceId},...e.authType!==void 0&&{authType:e.authType},...e.authId!==void 0&&{authId:e.authId},...e.userAgent!==void 0&&{userAgent:e.userAgent},...e.ipAddress!==void 0&&{ipAddress:e.ipAddress},...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.agentId!==void 0&&{agentId:e.agentId},...e.transportType!==void 0&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...e.isRead!==void 0&&{isRead:e.isRead},...e.statusCode!==void 0&&{statusCode:e.statusCode},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeObject(e.details)},startTime:e.startTime??n,...t.endTime!==void 0&&{endTime:t.endTime},...i!==void 0&&{durationMs:i},eventTime:n}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof i.ZodError){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#i?.error({message:`Failed to validate ${n} log from the query engine`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.issues,log:safeSerialize(e)}}),Error(`Log data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,Ye)}validateLogsBeforeSend(e){let t=[];for(let n of e)try{let e=this.getSchemaForLogType(n.logType).parse(n);t.push(e)}catch(e){e instanceof i.ZodError?this.#i?.warning({message:`Log validation failed before sending to Kafka, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.issues,log:safeSerialize(n)}}):this.#i?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return H;case`step`:return U;case`unified`:return W;case`provider`:return G;case`platform`:return K}}};const readStoredLog=async({bucket:e,key:t,description:n,errorCode:r,category:i,logger:a})=>{try{let r=await e.readText(t);if(r===void 0){a?.debug({message:`No ${n} in storage`,category:i});return}return a?.debug({message:`Retrieved ${n} from storage`,category:i}),JSON.parse(r)}catch(e){throw a?.error({message:`Error when getting ${n} from storage`,error:e,code:r,category:i}),e}},writeStoredLog=async({bucket:e,key:t,body:n,ttlTag:r,expiresAt:i,description:a,errorCode:o,category:s,logger:c})=>{try{await e.write(t,n,{contentType:`application/json`,tags:{ttl:r},expiresAt:i})}catch(e){throw c?.error({message:`Failed to write ${a} to storage at ${t}`,error:e,code:o,category:s}),e}},statStoredLog=async({bucket:e,key:t,description:n,errorCode:r,category:i,logger:a})=>{try{let n=await e.stat(t);return n===void 0?{exists:!1}:{exists:!0,expiresAt:n.expiresAt}}catch(e){throw a?.error({message:`Error when checking ${n} in storage`,error:e,code:r,category:i}),e}},Qe=65536,$e=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],et=[`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=>$e.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=>et.includes(e.path)),...e.filter(e=>!et.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*Qe;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(Qe,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=>$e.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),tt=[`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`],nt=[`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`],rt=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],parseActionUrl=e=>e.startsWith(`/`)?new URL(e,`http://path.invalid`):new URL(e),platformKey=(e,t)=>`${e}/platform/${t}.json`,J=`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:J});else 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,n){let r=[];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:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),r.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`}),r.push(null);continue}if(n.errorsOnly&&a.success&&!a.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${i.mode||`action`}`,category:`AdvancedSink`}),r.push(null);continue}if(isBackgroundLog(i.mode,i.sourceType)&&!n.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${i.mode}`,category:`AdvancedSink`}),r.push(null);continue}let e=callerHeadersOf(i.callerHeaders),[o,s,c,l]=await Promise.all([this.scrubPii(redactBody(i.body,i.headers),n),this.scrubPii((0,t.redactFields)(i.queryParams,t.CensorType.PARTIAL,!0),n),this.scrubPii((0,t.redactFields)(i.pathParams,t.CensorType.PARTIAL,!0),n),Object.values(e??{}).some(e=>e!==t.REDACT_CENSOR)?this.scrubPii(e,n):e]),u={...i,body:o,queryParams:s,pathParams:c,callerHeaders:l},d={...a,body:await this.scrubPii(redactBody(a.body??a.refusal,a.headers),n)},f=this.createActionItem(u,d,n),p=await this.send(f,n?.ttl);r.push(p)}return r}async sendStep(e,n,r){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:n.success,options:{enabled:r?.enabled,errorsOnly:r?.errorsOnly,includeBackground:r?.includeBackground,ttl:r?.ttl}}}),!r?.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(r.errorsOnly&&e.actionSuccess===!0&&n.success!==!1&&!hasErrorEntries(n.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)&&!r.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,t.redactFields)(e.inputs,t.CensorType.PARTIAL,!0),r)},a={...n,outputs:await this.scrubPii((0,t.redactFields)(n.outputs,t.CensorType.PARTIAL,!0),r),errors:await this.scrubPii((0,t.redactFields)(n.errors,t.CensorType.PARTIAL,!0),r)},o=this.createStepItem(i,a,r);try{return await this.send(o,r?.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:J});else return readStoredLog({bucket:this.requireBucket(),key:e,description:t,errorCode:`AdvancedLogReadError`,category:J,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=/* @__PURE__ */ new Date(i*1e3);return this.#i?.debug({message:`Storing advanced log in bucket ${n.name} with ttl of ${r}`,category:J,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:J,logger:this.#i}),{expiresAt:a}}async getObjectExpiry(e){return this.#t?(this.#i?.warning({message:`No storage available, cannot check object expiry`,category:J}),{exists:!1}):statStoredLog({bucket:this.requireBucket(),key:e,description:`advanced log at ${e}`,errorCode:`AdvancedLogHeadError`,category:J,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,r){let i=(0,t.redactFields)(e.data,t.CensorType.PARTIAL,!0),a={...e.metadata,expirationTime:r,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,r,i,a,o){let s=(0,t.redactHeaders)(e.headers,t.CensorType.PARTIAL),c=(0,t.redactHeaders)(r.headers,t.CensorType.PARTIAL),l=this.processContent(s,e.body,`upload`),u=this.processContent(c,r.body,`download`),d=e.isBackground??isBackgroundLog(e.mode,e.sourceType),f=e.url,p={};if(e.url)try{f=(0,t.redactUrl)(e.url,t.CensorType.PARTIAL);let n=parseActionUrl(f);p=Object.fromEntries(n.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),callerHeaders:e.callerHeaders,url:{url:f,path:e.pathParams,queryParams:m},body:l},response:{statusCode:r.statusCode??500,headers:this.filterHeaders(c),body:u},...d?{isBackgroundLog:!0}:{}},metadata:{...d?{isBackgroundLog:!0}:{},expirationTime:i}};return this.serializeAndLimit(h,a,isErrorResult(r),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,n,r,i,a){let o=(0,t.redactHeaders)(e.headers,t.CensorType.PARTIAL),s=(0,t.redactHeaders)(n.headers,t.CensorType.PARTIAL),c=this.processContent(o,e.body,`upload`),l=this.processContent(s,n.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),d=`/`,f=e.url,p={};if(e.url)try{f=(0,t.redactUrl)(e.url,t.CensorType.PARTIAL);let n=new URL(f);d=n.pathname,p=Object.fromEntries(n.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:n.statusCode??500,headers:this.filterHeaders(s),body:l}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:r}};return this.serializeAndLimit(m,i,isErrorResult(n),a)}serializeProviderResult(e,n,r,i,a){let o=(0,t.redactHeaders)(e.headers,t.CensorType.PARTIAL),s=(0,t.redactHeaders)(n.headers,t.CensorType.PARTIAL),c=this.processContent(o,e.body,`upload`),l=this.processContent(s,n.body,`download`),u,d=``,f=`/`,p={};if(e.url)try{u=(0,t.redactUrl)(e.url,t.CensorType.PARTIAL);let n=new URL(u);d=n.hostname,f=n.pathname,p=Object.fromEntries(n.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:n.statusCode,headers:this.filterHeaders(s),body:l}},metadata:{expirationTime:r}};return this.serializeAndLimit(m,i,isErrorResult(n),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=tt.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 nt.includes(i)||rt.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!(0,n.isMissing)(e)){if(!(0,n.isString)(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};const Y=2e3,settleWithin=(e,t,n)=>new Promise(r=>{let i=setTimeout(()=>r(n),t);i.unref?.(),e.then(e=>{clearTimeout(i),r(e)})});function defaultProviderFactory(e){let t=e.baseUrl??`https://logfire-eu.pydantic.dev`,n=new s.OTLPTraceExporter({url:`${t}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`},timeoutMillis:Y}),r={[u.ATTR_SERVICE_NAME]:e.serviceName??`stackone-olap`};return e.environment&&(r[`deployment.environment.name`]=e.environment),e.region&&(r[`cloud.region`]=e.region),new l.BasicTracerProvider({resource:(0,c.resourceFromAttributes)(r),spanProcessors:[new l.BatchSpanProcessor(n)]})}var LogfireEmitter=class{#e;#t;#n;#r;#i=/* @__PURE__ */ new Set;#a;#o=!1;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(!this.#r)return;if(this.#i.size>=4){this.#t?.debug({message:`Logfire exports at the limit, leaving spans queued for the next flush`,category:`DatasetsSink`,context:{maxExportsInFlight:4}});return}let e=this.#s()?Y:50,t=this.#c(this.#r);await settleWithin(t.then(()=>!0),e,!1)||this.#t?.debug({message:`Logfire export still running, not waiting for it`,category:`DatasetsSink`,context:{flushTimeoutMs:e}})}async drain(e=4e3){if(!this.#r)return;let t=[...this.#i,this.#c(this.#r)];await settleWithin(Promise.all(t).then(()=>!0),e,!1)||this.#t?.warning({message:`Logfire exports still running at shutdown, their spans may be lost`,code:`LogfireDrainTimeout`,category:`DatasetsSink`,context:{timeoutMs:e}})}#s(){return this.#o?!1:this.#a===void 0||Date.now()-this.#a>3e5}#c(e){let t=Date.now(),n=!1,r=setTimeout(()=>{n=Date.now()-t>=2250},Y);r.unref?.();let i=new Promise(t=>t(e.forceFlush())).then(()=>{this.#a=Date.now(),this.#o=!1},e=>this.#l(e,Date.now()-t,n));return this.#i.add(i),i.finally(()=>{clearTimeout(r),this.#i.delete(i)}),i}#l(e,t,n){n?(this.#a=void 0,this.#o=!1,this.#t?.debug({message:`Logfire export failed after the process was frozen`,category:`DatasetsSink`,context:{elapsedMs:t,exportTimeoutMs:Y,error:String(e)}})):(this.#o=!0,this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`,context:{elapsedMs:t}}))}},DatasetsSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){this.#e.token?this.#r.configure():this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`})}async close(e){this.#a??=this.#r.drain?.(e),await this.#a}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let r=0;for(let{input:i,result:a}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,includeBackground:t.includeBackground}}),(0,n.isMissing)(i.body)&&(0,n.isMissing)(a.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if(isBackgroundLog(i.mode,i.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${i.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(i,a);(0,n.isMissing)(e)?this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}}):(0,n.exceedsSize)(e,this.#n)?this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}}):(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 X=`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(){this.#t&&this.#r?.warning({message:`No storage provided, defender sink will not function`,category:X})}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)this.#r?.debug({message:`Defender sink called to send action`,category:X,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,options:{enabled:t?.enabled}}}),t?.enabled?(0,n.isMissing)(a.defenderContext)?(this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:X,context:{actionRunId:i.actionRunId}}),r.push(null)):r.push(await this.send(i,a)):(this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:X}),r.push(null));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:X});else return readStoredLog({bucket:this.requireBucket(),key:defenderKey(e,t,n),description:`defender log for actionRunId ${n}`,errorCode:`DefenderLogReadError`,category:X,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=/* @__PURE__ */ 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:X,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:X,logger:this.#r}),{expiresAt:a}}};const defenderKey=(e,t,n)=>`${e}/${t}/${n}/defender.json`,Z={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`,piiRedactionEnabled:!1},defender:{enabled:!0},policy:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...Z.logs,...e?.logs},advanced:{...Z.advanced,...e?.advanced},defender:{...Z.defender,...e?.defender},policy:{...Z.policy,...e?.policy},datasets:{...Z.datasets,...e?.datasets}}}function getPolicySink(e,t,n){return new PolicySink(e,t,n)}const Q=`PolicySink`;var PolicySink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.ttlDays??365,this.#r=n}async initialize(){this.#t&&this.#r?.warning({message:`No storage provided, policy sink will not function`,category:Q})}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let r=[];for(let{input:i,result:a}of e)if(!t?.enabled)r.push(null);else if(!this.#e&&!this.#t)r.push(null);else if((0,n.isMissing)(a.policyContext))r.push(null);else{if(!this.#e)throw Error(`No storage available, cannot send to policy sink`);r.push(await this.send(this.#e,i,a))}return r}async getAction(e,t,n,r){if(this.#t)this.#r?.warning({message:`No storage available, cannot get action log from policy sink`,category:Q});else if(this.#e)return readStoredLog({bucket:this.#e,key:policyKey(e,t,n,r),description:`policy log for actionRunId ${r}`,errorCode:`PolicyLogReadError`,category:Q,logger:this.#r})}async send(e,t,n){let r=new Date(Date.now()+this.#n*24*60*60*1e3);return await writeStoredLog({bucket:e,key:policyKey(t.organizationId,t.projectSecureId,t.accountSecureId,t.actionRunId),body:JSON.stringify(n.policyContext),ttlTag:`${this.#n}d`,expiresAt:r,description:`policy log`,errorCode:`PolicyLogWriteError`,category:Q,logger:this.#r}),{expiresAt:r}}};const policyKey=(e,t,n,r)=>`${e}/${t}/${n}/${r}/policy.json`,it=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${it}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${it}${e} failed with ${r.status}`);return r},fetchGoogleAccessToken=async e=>{let t=await(await requestMetadata(`/token`,e)).json();if(!t.access_token||typeof t.expires_in!=`number`)throw Error(`Google metadata token response missing access_token or expires_in`);return{accessToken:t.access_token,expiresInSeconds:t.expires_in}},fetchGoogleServiceAccountEmail=async e=>{let t=(await(await requestMetadata(`/email`,e)).text()).trim();if(!t)throw Error(`Google metadata returned an empty service account email`);return t},encodeSegment=e=>Buffer.from(e,`utf8`).toString(`base64url`),at=/* @__PURE__ */ __name(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=at(n);return e?.logger?.warning({message:`Google Kafka token refresh failed, using cached token: ${t.message}`,error:t,code:`GoogleKafkaTokenRefreshFailed`,category:`googleKafkaToken`}),i}throw n}).finally(()=>{r.inflight=void 0}),r.inflight)};return async()=>{try{let[{accessToken:e,expiresAtSeconds:n},r]=await Promise.all([credential(),principal()]);return encodeGoogleKafkaToken(e,{principal:r,issuedAtSeconds:t(),expiresAtSeconds:n})}catch(t){let n=at(t);throw e?.logger?.error({message:`Failed to mint Google Kafka token: ${n.message}`,error:n,code:`GoogleKafkaTokenError`,category:`googleKafkaToken`}),n}}},resolveSasl=(e,t)=>e.mechanism!==`OAUTHBEARER`||e.token?e:{...e,token:createGoogleKafkaTokenProvider({logger:t})},failedOnClosedConnection=e=>{let{code:t,canRetry:n,errors:r}=e??{};return Array.isArray(r)&&r.length>0?r.every(failedOnClosedConnection):t===`PLT_KFK_NETWORK`&&n===!0},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,a,o,s=/* @__PURE__ */ new Set,closeQuietly=async e=>{try{await e.close()}catch(e){let t=e instanceof Error?e:Error(String(e));n?.warning({message:`Error closing kafka producer: ${t.message}`,error:t,code:`KafkaProducerCloseError`,category:`buildKafkaClient`})}},dispose=e=>{let t=closeQuietly(e).finally(()=>{s.delete(t)});return s.add(t),t},reconstruct=async e=>{if(a||o)return;let s=Date.now();if(!(s-i<3e4)){i=s;try{let i=r;o=t();let s=await o;if(a){await dispose(s);return}r=s,dispose(i),n?.warning({message:`Kafka producer reconstructed after send failure: ${e.message}`,error:e,code:`KafkaProducerReconstructed`,category:`buildKafkaClient`})}catch(e){let t=e;n?.error({message:`Error reconstructing kafka producer: ${t.message}`,error:t,code:`KafkaProducerReconstructionError`,category:`buildKafkaClient`})}finally{o=void 0}}},close=async()=>(a??=(async()=>{let e=o;for(await closeQuietly(r),e&&await e.catch(()=>void 0);s.size>0;)await Promise.allSettled([...s])})(),a),send=async e=>{let t=r;try{return await t.send(e)}catch(n){if(await reconstruct(n),r!==t&&!a&&failedOnClosedConnection(n))return r.send(e);throw n}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;if(t===`close`)return close;let n=Reflect.get(r,t,r);return typeof n==`function`?n.bind(r):n}})},buildKafkaClient=async(e,t)=>{if(!e)return;let construct=async()=>{let{Producer:n,stringSerializers:r}=await import(`@platformatic/kafka`);return new n({retries:3,retryDelay:1e3,...e,...e.sasl&&{sasl:resolveSasl(e.sasl,t)},serializers:r})};try{return withLazyReconstruction(await construct(),construct,t)}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},toError=e=>e instanceof Error?e:Error(String(e)),createMskKafkaTokenProvider=({region:e,logger:t})=>async()=>{try{let{generateAuthToken:t}=await import(`aws-msk-iam-sasl-signer-js`),{token:n}=await t({region:e});return n}catch(e){let n=toError(e);throw t?.error({message:`Failed to mint MSK Kafka token: ${n.message}`,error:n,code:`MskKafkaTokenError`,category:`mskKafkaToken`}),n}},rotateBootstrapBrokers=(e,t=Math.random)=>{let n=Math.floor(t()*e.length);return[...e.slice(n),...e.slice(0,n)]},buildInternalKafkaClient=async(e,t,n=Math.random)=>{if(!e)return;let{bootstrapBrokers:r,region:i,clientId:a,...o}=e;return buildKafkaClient({bootstrapBrokers:rotateBootstrapBrokers(r,n),clientId:a??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:i,logger:t})},...o},t)},defaultStorage=e=>e?.advanced?.bucket||e?.defender?.bucket||e?.policy?.bucket?(0,o.createStorage)((0,o.storageConfigFromEnv)()):void 0;var $=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){this.name=`OlapClient`,this.#c=e,this.#l=i??r,this.#u=t,this.#d=a,this.#m=o,this.#f=s,this.#p=c,this.#t=n??defaultStorage(c),this.#n=l}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){let u=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});return await u.initialize(),u}async initialize(){this.#e=await this.#c(this.#l,this.#n);let e=this.#d?{producer:await this.#u(this.#d,this.#n)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#r=new LogsSink(t,this.#n,this.#f,e,this.#m),this.#i=new AdvancedSink(this.#t,this.#p?.advanced,this.#n),this.#a=new DefenderSink(this.#t,this.#p?.defender,this.#n),this.#o=new PolicySink(this.#t,this.#p?.policy,this.#n),this.#s=new DatasetsSink(this.#p?.datasets,this.#n),await this.#r?.initialize(),await this.#i?.initialize(),await this.#s?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async close(e){await Promise.all([this.#r?.close?.(e),this.#s?.close(e)])}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:r,advanced:i,defender:a,policy:o,datasets:s}=resolveOlapOptions(t);this.#n?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:r,advanced:i,defender:a,policy:o,datasets:s}}});for(let t of e)(0,n.isMissing)(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let c=o?.enabled&&this.#o?this.#o.sendActions(e,o).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to policy logs storage: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),l=s?.enabled&&this.#s?this.#s.sendActions(e,s).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[u,d]=await Promise.all([i?.enabled&&this.#i?this.#i.sendActions(e,i).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),a?.enabled&&this.#a?this.#a.sendActions(e,a).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to defender logs storage: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),f=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:u[t]?.expiresAt,defenderExpiresAt:d[t]?.expiresAt}})),p=r?.enabled&&this.#r?this.#r.sendActions(f,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([l,c,p])}async recordStep(e,t,n){await this.recordSteps([{input:e,result:t}],n)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#r&&i.push(this.#r.sendSteps(e,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,r).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to storage: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,r){let{logs:i,advanced:a}=resolveOlapOptions(r);this.#n?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:r,resolvedOptions:{logs:i,advanced:a}}}),(0,n.isMissing)(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let o={advancedExpiresAt:(a?.enabled&&this.#i?await this.#i.sendUnified(e,t,a).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};i?.enabled&&this.#r&&await this.#r.sendUnified(e,t,o,i).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#r&&a.push(this.#r.sendProvider(e,t,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to storage: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordPlatform(e,t,n){let r=isPlatformLog(e),i=r&&t&&`data`in t?t:void 0,{logs:a,advanced:o}=resolveOlapOptions(r&&!i?t:n),s=a?.enabled&&this.#r?(r?this.#r.sendPlatform(e,a):this.#r.sendPlatform(e,t??{},a)).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#i?this.#i.sendPlatform(e,i,o).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n){return this.#n?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getLastLogs(e,t,n,r={}){let i={...r,organizationId:e,projectSecureId:t};return this.#n?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#r?.getLastLogs(n,i)||(this.#n?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n){return this.#n?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,r){let i=await this.#r?.getAction(e,t,r);if((0,n.isMissing)(i))this.#n?.debug({message:`Failed to retrieve action log for actionRunId ${r}`,category:`OlapClient`});else return i}async getLog(e,t,n){this.#n?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n}});let r=await this.getLogs(e,t,{logId:n,pageSize:1});if(!r||r.logs.length===0){this.#n?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let i=r.logs[0];if(i.logType===`action`||i.logType===`unified`)return i}async getStepLogs(e,t,n){return this.#n?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,r,i){let a=await this.#r?.getStep(e,t,r,i);if((0,n.isMissing)(a))this.#n?.debug({message:`Failed to retrieve step log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});else return a}async getUnifiedLogs(e,t,n){return this.#n?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,r){let i=await this.#r?.getUnifiedLog(e,t,r);if((0,n.isMissing)(i))this.#n?.debug({message:`Failed to retrieve unified log for requestId ${r}`,category:`OlapClient`});else return i}async getProviderLogs(e,t,n){return this.#n?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getPlatformLogs(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogs(n)||(this.#n?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getPlatformLogDimensions(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform log dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogDimensions(n)||(this.#n?.warning({message:`Failed to query platform log dimensions, returning empty result`,category:`OlapClient`}),{})}async getProviderLog(e,t,r,i){let a=await this.#r?.getProviderLog(e,t,r,i);if((0,n.isMissing)(a))this.#n?.debug({message:`Failed to retrieve provider log for requestId ${r} id ${i}`,category:`OlapClient`});else return a}async getActionAdvancedLog(e,t,r){let i=await this.#i?.getAction(e,t,r);if((0,n.isMissing)(i))this.#n?.debug({message:`Failed to retrieve action advanced log for actionRunId ${r}`,category:`OlapClient`});else return i}async getStepAdvancedLog(e,t,r,i){let a=await this.#i?.getStep(e,t,r,i);if((0,n.isMissing)(a))this.#n?.debug({message:`Failed to retrieve step advanced log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});else return a}async getUnifiedAdvancedLog(e,t,r){let i=await this.#i?.getUnified(e,t,r);if((0,n.isMissing)(i))this.#n?.debug({message:`Failed to retrieve unified advanced log for requestId ${r}`,category:`OlapClient`});else return i}async getProviderAdvancedLog(e,t,r,i){let a=await this.#i?.getProvider(e,t,r,i);if((0,n.isMissing)(a))this.#n?.debug({message:`Failed to retrieve provider advanced log for requestId ${r} id ${i}`,category:`OlapClient`});else return a}async getPlatformAdvancedLog(e,t){let r=await this.#i?.getPlatform(e,t);if((0,n.isMissing)(r))this.#n?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});else return r}async getPolicyLog(e,t,r,i){let a=await this.#o?.getAction(e,t,r,i);if((0,n.isMissing)(a))this.#n?.debug({message:`Failed to retrieve policy log for actionRunId ${i}`,category:`OlapClient`});else return a}async getDefenderLog(e,t,r){let i=await this.#a?.getAction(e,t,r);if((0,n.isMissing)(i))this.#n?.debug({message:`Failed to retrieve defender log for actionRunId ${r}`,category:`OlapClient`});else return i}async getLogsStatsAggregate(e,t,n){return this.#n?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n}}),await this.#r?.getAggregate(e,t,n)??{data:[]}}async getLogsStatsDimensions(e,t,n){return this.#n?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getDimensions(e,t,n)??{}}async getSourceUsage(e,t,n){return this.#n?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSourceUsage(e,t,n)??[]}async getActionsCount(e){if(!this.#r)throw Error(`Cannot count actions: the logs sink is not configured`);return this.#r.getActionsCount(e)}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l})=>$.create({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});var OlapClientManager=class{static{this.olapClientPromise=null}static{this.closingPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l,getOlapClient:u=buildOlapClientInstance}){return this.olapClientPromise||=u({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null,this.closingPromise=null}static async close(e){let t=this.olapClientPromise;if(this.olapClientPromise=null,!t)return this.closingPromise??void 0;let n=this.closingPromise,r=(async()=>{await n?.catch(()=>void 0),await this.drain(t,e)})().finally(()=>{this.closingPromise===r&&(this.closingPromise=null)});return this.closingPromise=r,r}static async drain(e,t){let n,r=!1;try{let i=await Promise.race([e,new Promise((e,t)=>{n=setTimeout(()=>{r=!0,t(/* @__PURE__ */ Error(`timed out waiting for olap initialisation`))},6e4),n.unref?.()})]);n&&=(clearTimeout(n),void 0),await i.close?.(t)}catch{}finally{n&&clearTimeout(n),r&&e.then(e=>e.close?.(t)).catch(()=>void 0)}}};exports.AuthType=te,exports.DEFAULT_TOPIC_CLUSTER_MAP=v,exports.Dimension=_e,exports.IntervalType=_,exports.InvalidAuthPairError=InvalidAuthPairError,exports.InvalidLogQueryConditionsError=InvalidLogQueryConditionsError,exports.LOG_QUERY_FIELDS=b,exports.LOG_QUERY_OPERATORS=S,exports.LogType=g,exports.OlapClient=$,exports.OlapClientManager=OlapClientManager,exports.OrderBy=he,exports.OrderDirection=ge,exports.PlatformDimension=ve,exports.PolicySink=PolicySink,exports.QueryClientNotConfiguredError=QueryClientNotConfiguredError,exports.SourceType=m,exports.StreamType=ee,exports.TransportType=h,exports.callerHeadersOf=callerHeadersOf,exports.getPolicySink=getPolicySink,exports.hasErrorEntries=hasErrorEntries,exports.parseLogQueryConditions=parseLogQueryConditions;
|
|
241
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),...toAuthPairParams(e.authPairs),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const Je={id:`project_unified_logs`,buildQuery:buildUnifiedLogsQuery,buildCountQuery:buildUnifiedLogsCountQuery};var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,t){this.#t=e,this.#n=t,e?.url&&(this.#e=(0,a.createClient)({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){let{data:t}=await this.#a(e);return t}async queryWithPagination(e){let{data:t,total:n}=await this.#a(e);return{data:t,total:n??t.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??t.length}}isReady(){return!!(this.#e&&this.#t?.url)}async close(){await this.#e?.close()}#r(){if(!this.#e)throw this.#n?.error({message:`ClickHouse client not initialized`,category:`ClickHouseClient`,code:`ClientNotReady`}),Error(`ClickHouse client is not initialized`);if(!this.#t?.url)throw this.#n?.warning({message:`Missing ClickHouse URL`,category:`ClickHouseClient`}),Error(`ClickHouseClient - Missing URL`);return this.#e}#i(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`ClickHouseClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`ClickHouseClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#a(e){try{let{data:t,total:n}=await this.#o(e.query,e.params);return{data:this.#i(t,e.schema),total:n}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error running clickhouse query ${e.query.id}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async#o(e,t){let n=this.#r(),{sql:r,params:i}=e.buildQuery(t);this.#n?.debug({message:`Running clickhouse query: ${e.id}`,category:`ClickHouseClient`,context:{query:e.id,params:t}});let a=Date.now(),o=await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json(),s=(Date.now()-a)/1e3,c;if(e.buildCountQuery){let{sql:r,params:i}=e.buildCountQuery(t);c=(await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${o.length} rows`,category:`ClickHouseClient`,context:{query:e.id,rows:o.length,elapsed:s}}),{data:o,total:c}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return(/* @__PURE__ */ new Date(t+`Z`)).toISOString()},B=i.z.preprocess(e=>{if(e instanceof Date)return e;if(typeof e==`string`&&e.length>0)try{return new Date(utcDateTransform(e))}catch(e){throw new i.z.ZodError([{code:i.z.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},i.z.coerce.date()),V=i.z.object({logType:i.z.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:B,startTime:B,endTime:B.optional().nullable().transform(e=>e??void 0),durationMs:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:i.z.coerce.string(),projectSecureId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),H=V.extend({logType:i.z.literal(`action`),actionRunId:i.z.coerce.string(),actionId:i.z.coerce.string(),connectorKey:i.z.coerce.string(),connectorVersion:i.z.coerce.string(),connectorOwner:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:i.z.coerce.string(),accountSecureId:i.z.coerce.string(),actionType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),mode:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),category:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),actingUserId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),policyResult:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),isBackground:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:B.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:B.optional().nullable().transform(e=>e??void 0)}),U=V.extend({logType:i.z.literal(`step`),actionRunId:i.z.coerce.string(),stepIndex:i.z.coerce.number(),stepId:i.z.coerce.string(),projectSecureId:i.z.coerce.string(),accountSecureId:i.z.coerce.string(),skipped:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),message:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:i.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),W=V.extend({logType:i.z.literal(`unified`),requestId:i.z.coerce.string(),connectorKey:i.z.coerce.string(),connectorVersion:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:i.z.coerce.string(),accountSecureId:i.z.coerce.string(),mode:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),path:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),actingUserId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:B.optional().nullable().transform(e=>e??void 0),duration:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:B.optional().nullable().transform(e=>e??void 0)}),G=V.extend({logType:i.z.literal(`provider`),requestId:i.z.coerce.string(),id:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:i.z.coerce.string(),mode:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:i.z.coerce.string(),originOwnerId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:i.z.coerce.string(),path:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:i.z.coerce.string(),connectorVersion:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:i.z.coerce.string(),accountSecureId:i.z.coerce.string(),status:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:B.optional().nullable().transform(e=>e??void 0),duration:i.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),K=V.extend({logType:i.z.literal(`platform`),eventId:i.z.coerce.string(),eventType:i.z.coerce.string(),service:i.z.coerce.string(),organizationId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:i.z.undefined().optional(),userId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:i.z.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:i.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:i.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:i.z.record(i.z.string(),i.z.unknown()).optional().nullable().transform(e=>e??void 0)}),Ye=i.z.discriminatedUnion(`logType`,[H,U,W,G]),Xe=/* @__PURE__ */ new Set([`success`,`isRead`]),foldTimeBuckets=e=>{let t=/* @__PURE__ */ new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},q=[`success`,`isWorker`,`isBackground`,`skipped`];var QueryClientNotConfiguredError=class extends Error{constructor(){super(`No ClickHouse query client is configured`),this.name=`QueryClientNotConfiguredError`}};const Ze=15e3;var LogsSink=class{#e;#t;#n;#r;#i;#a(){if(!this.#r?.isReady())throw new QueryClientNotConfiguredError;return this.#r}#o(e){parseLogQueryConditions(e.conditions)}constructor(e,t,n,r,i){this.#e=e,this.#t=r,this.#n=i,this.#i=t,n&&(this.#r=new ClickHouseClient(n,t),this.#i?.debug({message:`LogsSink initialized with the ClickHouse query client`,category:`LogsSink`}))}async initialize(){!this.#e?.producer&&!this.#t?.producer?this.#i?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`}):(this.#r?.isReady()?this.#i?.info({message:`Logs sink query client ready: clickhouse`,category:`LogsSink`}):this.#i?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}),this.#i?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#u())}async close(e=3e4){return this.#s??=this.#c(e),this.#s}#s;async#c(e){let t=[];if(this.#e?.producer){let e=this.#e.producer;t.push([`external kafka producer`,()=>e.close()])}if(this.#t?.producer){let e=this.#t.producer;t.push([`internal kafka producer`,()=>e.close()])}if(this.#r){let e=this.#r;t.push([`clickhouse client`,()=>e.close()])}(await Promise.allSettled(t.map(([,t])=>this.#l(t,e)))).forEach((n,r)=>{if(n.status===`rejected`){let i=n.reason instanceof Error?n.reason:Error(String(n.reason)),a=i.name===`LogsSinkCloseTimeout`,o=t[r]?.[0]??`resource`,s=o.includes(`producer`),c={message:a?s?`Timed out closing ${o} after ${e}ms; buffered records may have been lost`:`Timed out releasing ${o} after ${e}ms`:`Error closing ${o}: ${i.message}`,error:i,code:`LogsSinkCloseError`,category:`LogsSink`};a&&s?this.#i?.error(c):this.#i?.warning(c)}})}async#l(e,t){let n,r=new Promise((e,r)=>{n=setTimeout(()=>{let e=/* @__PURE__ */ Error(`timed out after ${t}ms`);e.name=`LogsSinkCloseTimeout`,r(e)},t),n.unref?.()});try{return await Promise.race([Promise.resolve().then(e),r])}finally{n&&clearTimeout(n)}}async#u(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{let n;try{await Promise.race([t?.connectToBrokers(),new Promise((e,t)=>{n=setTimeout(()=>t(/* @__PURE__ */ Error(`connectivity probe timed out after ${Ze}ms`)),Ze),n.unref?.()})]),this.#i?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#i?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}finally{n&&clearTimeout(n)}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t,metadata:n})=>this.buildActionLog(e,t,n));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n,r){if(!r?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async sendPlatform(e,t,n){let r=isPlatformLog(e);if(!(r?t:n)?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending platform to log sink (topic: platform)`,category:`LogsSink`});let i=r?e:this.buildPlatformLog(e,t??{});await this.send(`platform`,[i])}async getLogs(e){this.#o(e);let t=this.#a();try{this.#i?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:je,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} logs (${n.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(n.data),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(e){throw this.#i?.error({message:`Failed to query for logs`,category:`LogsSink`,code:`LogsQueryFailed`,error:e}),e}}async getLastLogs(e,t){this.#o(t);let n=this.#a(),r=e?.ids??[];if(r.length===0)return emptyQueryResult();try{this.#i?.info({message:`Querying last logs for ${r.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await n.queryWithPagination({query:Pe,params:{...t,entities:e}});return this.#i?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){throw this.#i?.error({message:`Failed to query for last logs`,category:`LogsSink`,code:`LastLogsQueryFailed`,error:e}),e}}async getActions(e){let t=this.#a();try{this.#i?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:fe,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} action logs (${n.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(n.data,H),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n})).actionLogs[0]}async getSteps(e){let t=this.#a();try{this.#i?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Ke,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} step logs (${n.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(n.data,U),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for step logs, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r})).stepLogs[0]}async getUnifiedLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Je,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} unified logs (${n.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(n.data,W),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n})).unifiedLogs[0]}async getProviderLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Ue,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} provider logs (${n.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(n.data,G),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.error({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,code:`ProviderLogsQueryFailed`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogDimensions(e){let t=this.#a();try{this.#i?.info({message:`Querying platform log dimensions`,category:`LogsSink`,context:{query:e}});let n=await t.query({query:ze,params:e});this.#i?.info({message:`Successfully retrieved ${n.length} platform dimension facets`,category:`LogsSink`});let r={};for(let e of n)r[e.dimension]=Xe.has(e.dimension)?e.values.map(e=>({value:e.value===`1`?`true`:`false`,count:e.count})):e.values;return r}catch(e){return this.#i?.error({message:`Failed to query platform log dimensions: ${e instanceof Error?e.message:String(e)}`,category:`LogsSink`,code:`PlatformDimensionsQueryFailed`}),{}}}async getPlatformLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Ve,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} platform logs (${n.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(n.data,K),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:t}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r})).providerLogs[0]}async getAggregate(e,t,r){this.#o(r);let i=this.#a();try{this.#i?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:r}});let{dimensions:a,startTime:o,endTime:s,...c}=r,l=r.intervalType===_.None,u={organizationId:e,projectSecureId:t,...c,...a&&a.length>0&&{dimensions:a.join(`,`)},...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...l&&{pageSize:void 0,pageNumber:void 0}},d=await i.query({query:Me,params:u});this.#i?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>(0,n.convertKeysToCamelCase)(e,!0)).map(e=>{let t={...e};for(let e of q)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:l?foldTimeBuckets(f):f}}catch(e){throw this.#i?.error({message:`Failed to query for logs stats aggregate`,category:`LogsSink`,code:`LogsAggregateQueryFailed`,error:e}),e}}async getDimensions(e,t,n){this.#o(n);let r=this.#a();try{this.#i?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n}});let{dimensions:i,startTime:a,endTime:o,...s}=n,c={organizationId:e,projectSecureId:t,...s,dimensions:i.join(`,`),...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await r.query({query:Ne,params:c});this.#i?.info({message:`Successfully retrieved ${l.length} dimension facets`,category:`LogsSink`});let u={};for(let e of l)q.includes(e.dimension)?u[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):u[e.dimension]=e.values;return u}catch(e){throw this.#i?.error({message:`Failed to query for logs stats dimensions`,category:`LogsSink`,code:`LogsDimensionsQueryFailed`,error:e}),e}}async getActionsCount(e){let[t]=await this.#a().query({query:me,params:e});return Number(t?.actions_count??0)}async getSourceUsage(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n}});let{startTime:i,endTime:a,sourceType:o}=n,s={organizationId:e,projectSecureId:t,sourceType:o||void 0,...i&&{startTime:i.toISOString()},...a&&{endTime:a.toISOString()}},c=await r.query({query:We,params:s});return this.#i?.info({message:`Successfully retrieved ${c.length} source usage records`,category:`LogsSink`}),c.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))}catch(e){return this.#i?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}),[]}}#d(e){return(this.#n??v)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#d(e);if(!n)throw this.#i?.error({message:`No cluster routing configured for topic ${e}, dropping ${t.length} log(s)`,category:`KafkaSink`,code:`TopicNotRouted`}),Error(`No cluster routing configured for topic ${e}`);if(n.length===0){this.#i?.debug({message:`Topic ${e} is muted by the topic cluster map, dropping ${t.length} log(s)`,category:`KafkaSink`});return}let r=this.validateLogsBeforeSend(t);if(r.length===0){this.#i?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}r.length<t.length&&this.#i?.warning({message:`${t.length-r.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let i=r.map(t=>({topic:e,value:safeSerialize(t)})),a=await Promise.allSettled(n.map(({cluster:t,producer:n})=>this.#f(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#f(e,t,n,r){if(!t)throw this.#i?.error({message:`Kafka not initialized, dropping message for topic ${n}`,category:`KafkaSink`,code:`KafkaNotReady`,context:{cluster:e}}),Error(`Kafka producer is not initialized`);let i=Date.now();this.#i?.debug({message:`Sending ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{cluster:e}});try{let a=await t.send({messages:r,compression:`gzip`});this.#i?.debug({message:`Successfully sent ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{durationMs:Date.now()-i,topic:n,cluster:e,result:a}})}catch(t){throw this.#i?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=/* @__PURE__ */ new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.actingUserId&&{actingUserId:e.actingUserId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.allowed!==void 0&&{allowed:t.defenderContext.result.allowed},...t.defenderContext?.result?.tier2Decision!==void 0&&{tier2Decision:t.defenderContext.result.tier2Decision},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},...t.defenderContext?.result?.tier2LatencyMs!==void 0&&{tier2LatencyMs:t.defenderContext.result.tier2LatencyMs},...t.defenderContext?.result?.tier3Decision!==void 0&&{tier3Decision:t.defenderContext.result.tier3Decision},...t.defenderContext?.result?.tier3PromptTokens!==void 0&&{tier3PromptTokens:t.defenderContext.result.tier3PromptTokens},...t.defenderContext?.result?.tier3CompletionTokens!==void 0&&{tier3CompletionTokens:t.defenderContext.result.tier3CompletionTokens},...t.defenderContext?.result?.tier3LatencyMs!==void 0&&{tier3LatencyMs:t.defenderContext.result.tier3LatencyMs},...t.policyContext&&{policyResult:t.policyContext.result},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=/* @__PURE__ */ new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=/* @__PURE__ */ new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.actingUserId&&{actingUserId:e.actingUserId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=/* @__PURE__ */ new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}buildPlatformLog(e,t){let n=/* @__PURE__ */ new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`platform`,eventId:e.eventId??(0,r.randomUUID)(),eventType:e.eventType,service:e.service,...e.organizationId!==void 0&&{organizationId:e.organizationId},...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.userId!==void 0&&{userId:e.userId},...e.userEmail!==void 0&&{userEmail:e.userEmail},...e.action!==void 0&&{action:e.action},...e.resource!==void 0&&{resource:e.resource},...e.resourceId!==void 0&&{resourceId:e.resourceId},...e.sourceType!==void 0&&{sourceType:e.sourceType},...e.sourceId!==void 0&&{sourceId:e.sourceId},...e.authType!==void 0&&{authType:e.authType},...e.authId!==void 0&&{authId:e.authId},...e.userAgent!==void 0&&{userAgent:e.userAgent},...e.ipAddress!==void 0&&{ipAddress:e.ipAddress},...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.agentId!==void 0&&{agentId:e.agentId},...e.transportType!==void 0&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...e.isRead!==void 0&&{isRead:e.isRead},...e.statusCode!==void 0&&{statusCode:e.statusCode},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeObject(e.details)},startTime:e.startTime??n,...t.endTime!==void 0&&{endTime:t.endTime},...i!==void 0&&{durationMs:i},eventTime:n}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof i.ZodError){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#i?.error({message:`Failed to validate ${n} log from the query engine`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.issues,log:safeSerialize(e)}}),Error(`Log data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,Ye)}validateLogsBeforeSend(e){let t=[];for(let n of e)try{let e=this.getSchemaForLogType(n.logType).parse(n);t.push(e)}catch(e){e instanceof i.ZodError?this.#i?.warning({message:`Log validation failed before sending to Kafka, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.issues,log:safeSerialize(n)}}):this.#i?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return H;case`step`:return U;case`unified`:return W;case`provider`:return G;case`platform`:return K}}};const readStoredLog=async({bucket:e,key:t,description:n,errorCode:r,category:i,logger:a})=>{try{let r=await e.readText(t);if(r===void 0){a?.debug({message:`No ${n} in storage`,category:i});return}return a?.debug({message:`Retrieved ${n} from storage`,category:i}),JSON.parse(r)}catch(e){throw a?.error({message:`Error when getting ${n} from storage`,error:e,code:r,category:i}),e}},writeStoredLog=async({bucket:e,key:t,body:n,ttlTag:r,expiresAt:i,description:a,errorCode:o,category:s,logger:c})=>{try{await e.write(t,n,{contentType:`application/json`,...r&&{tags:{ttl:r}},...i&&{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}},Qe=65536,$e=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],et=[`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=>$e.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=>et.includes(e.path)),...e.filter(e=>!et.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*Qe;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(Qe,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=>$e.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),tt=[`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`],nt=[`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`],rt=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],parseActionUrl=e=>e.startsWith(`/`)?new URL(e,`http://path.invalid`):new URL(e),platformKey=(e,t)=>`${e}/platform/${t}.json`,J=`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:J});else 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,n){let r=[];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:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),r.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`}),r.push(null);continue}if(n.errorsOnly&&a.success&&!a.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${i.mode||`action`}`,category:`AdvancedSink`}),r.push(null);continue}if(isBackgroundLog(i.mode,i.sourceType)&&!n.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${i.mode}`,category:`AdvancedSink`}),r.push(null);continue}let e=callerHeadersOf(i.callerHeaders),[o,s,c,l]=await Promise.all([this.scrubPii(redactBody(i.body,i.headers),n),this.scrubPii((0,t.redactFields)(i.queryParams,t.CensorType.PARTIAL,!0),n),this.scrubPii((0,t.redactFields)(i.pathParams,t.CensorType.PARTIAL,!0),n),Object.values(e??{}).some(e=>e!==t.REDACT_CENSOR)?this.scrubPii(e,n):e]),u={...i,body:o,queryParams:s,pathParams:c,callerHeaders:l},d={...a,body:await this.scrubPii(redactBody(a.body??a.refusal,a.headers),n)},f=this.createActionItem(u,d,n),p=await this.send(f,n?.ttl);r.push(p)}return r}async sendStep(e,n,r){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:n.success,options:{enabled:r?.enabled,errorsOnly:r?.errorsOnly,includeBackground:r?.includeBackground,ttl:r?.ttl}}}),!r?.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(r.errorsOnly&&e.actionSuccess===!0&&n.success!==!1&&!hasErrorEntries(n.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)&&!r.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,t.redactFields)(e.inputs,t.CensorType.PARTIAL,!0),r)},a={...n,outputs:await this.scrubPii((0,t.redactFields)(n.outputs,t.CensorType.PARTIAL,!0),r),errors:await this.scrubPii((0,t.redactFields)(n.errors,t.CensorType.PARTIAL,!0),r)},o=this.createStepItem(i,a,r);try{return await this.send(o,r?.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:J});else return readStoredLog({bucket:this.requireBucket(),key:e,description:t,errorCode:`AdvancedLogReadError`,category:J,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=/* @__PURE__ */ new Date(i*1e3);return this.#i?.debug({message:`Storing advanced log in bucket ${n.name} with ttl of ${r}`,category:J,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:J,logger:this.#i}),{expiresAt:a}}async getObjectExpiry(e){return this.#t?(this.#i?.warning({message:`No storage available, cannot check object expiry`,category:J}),{exists:!1}):statStoredLog({bucket:this.requireBucket(),key:e,description:`advanced log at ${e}`,errorCode:`AdvancedLogHeadError`,category:J,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,r){let i=(0,t.redactFields)(e.data,t.CensorType.PARTIAL,!0),a={...e.metadata,expirationTime:r,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,r,i,a,o){let s=(0,t.redactHeaders)(e.headers,t.CensorType.PARTIAL),c=(0,t.redactHeaders)(r.headers,t.CensorType.PARTIAL),l=this.processContent(s,e.body,`upload`),u=this.processContent(c,r.body,`download`),d=e.isBackground??isBackgroundLog(e.mode,e.sourceType),f=e.url,p={};if(e.url)try{f=(0,t.redactUrl)(e.url,t.CensorType.PARTIAL);let n=parseActionUrl(f);p=Object.fromEntries(n.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),callerHeaders:e.callerHeaders,url:{url:f,path:e.pathParams,queryParams:m},body:l},response:{statusCode:r.statusCode??500,headers:this.filterHeaders(c),body:u},...d?{isBackgroundLog:!0}:{}},metadata:{...d?{isBackgroundLog:!0}:{},expirationTime:i}};return this.serializeAndLimit(h,a,isErrorResult(r),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,n,r,i,a){let o=(0,t.redactHeaders)(e.headers,t.CensorType.PARTIAL),s=(0,t.redactHeaders)(n.headers,t.CensorType.PARTIAL),c=this.processContent(o,e.body,`upload`),l=this.processContent(s,n.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),d=`/`,f=e.url,p={};if(e.url)try{f=(0,t.redactUrl)(e.url,t.CensorType.PARTIAL);let n=new URL(f);d=n.pathname,p=Object.fromEntries(n.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:n.statusCode??500,headers:this.filterHeaders(s),body:l}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:r}};return this.serializeAndLimit(m,i,isErrorResult(n),a)}serializeProviderResult(e,n,r,i,a){let o=(0,t.redactHeaders)(e.headers,t.CensorType.PARTIAL),s=(0,t.redactHeaders)(n.headers,t.CensorType.PARTIAL),c=this.processContent(o,e.body,`upload`),l=this.processContent(s,n.body,`download`),u,d=``,f=`/`,p={};if(e.url)try{u=(0,t.redactUrl)(e.url,t.CensorType.PARTIAL);let n=new URL(u);d=n.hostname,f=n.pathname,p=Object.fromEntries(n.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:n.statusCode,headers:this.filterHeaders(s),body:l}},metadata:{expirationTime:r}};return this.serializeAndLimit(m,i,isErrorResult(n),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=tt.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 nt.includes(i)||rt.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!(0,n.isMissing)(e)){if(!(0,n.isString)(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};const Y=2e3,settleWithin=(e,t,n)=>new Promise(r=>{let i=setTimeout(()=>r(n),t);i.unref?.(),e.then(e=>{clearTimeout(i),r(e)})});function defaultProviderFactory(e){let t=e.baseUrl??`https://logfire-eu.pydantic.dev`,n=new s.OTLPTraceExporter({url:`${t}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`},timeoutMillis:Y}),r={[u.ATTR_SERVICE_NAME]:e.serviceName??`stackone-olap`};return e.environment&&(r[`deployment.environment.name`]=e.environment),e.region&&(r[`cloud.region`]=e.region),new l.TracerProvider({resource:(0,c.resourceFromAttributes)(r),spanProcessors:[new l.BatchSpanProcessor({exporter:n})]})}var LogfireEmitter=class{#e;#t;#n;#r;#i=/* @__PURE__ */ new Set;#a;#o=!1;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(!this.#r)return;if(this.#i.size>=4){this.#t?.debug({message:`Logfire exports at the limit, leaving spans queued for the next flush`,category:`DatasetsSink`,context:{maxExportsInFlight:4}});return}let e=this.#s()?Y:50,t=this.#c(this.#r);await settleWithin(t.then(()=>!0),e,!1)||this.#t?.debug({message:`Logfire export still running, not waiting for it`,category:`DatasetsSink`,context:{flushTimeoutMs:e}})}async drain(e=4e3){if(!this.#r)return;let t=[...this.#i,this.#c(this.#r)];await settleWithin(Promise.all(t).then(()=>!0),e,!1)||this.#t?.warning({message:`Logfire exports still running at shutdown, their spans may be lost`,code:`LogfireDrainTimeout`,category:`DatasetsSink`,context:{timeoutMs:e}})}#s(){return this.#o?!1:this.#a===void 0||Date.now()-this.#a>3e5}#c(e){let t=Date.now(),n=!1,r=setTimeout(()=>{n=Date.now()-t>=2250},Y);r.unref?.();let i=new Promise(t=>t(e.forceFlush())).then(()=>{this.#a=Date.now(),this.#o=!1},e=>this.#l(e,Date.now()-t,n));return this.#i.add(i),i.finally(()=>{clearTimeout(r),this.#i.delete(i)}),i}#l(e,t,n){n?(this.#a=void 0,this.#o=!1,this.#t?.debug({message:`Logfire export failed after the process was frozen`,category:`DatasetsSink`,context:{elapsedMs:t,exportTimeoutMs:Y,error:String(e)}})):(this.#o=!0,this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`,context:{elapsedMs:t}}))}};const it=1e3;var DatasetsSink=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;constructor(e,t,n,r){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;let i=e?.storage??r;this.#o=e?.bucket?i?.bucket(e.bucket):void 0,this.#s=!!e?.bucket&&!i,this.#c=e?.region}async initialize(){this.#s&&this.#i?.warning({message:`Datasets bucket configured without storage, schema logs will not be stored`,category:`DatasetsSink`}),this.#e.token?this.#r.configure():this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`})}async close(e){this.#a??=this.#r.drain?.(e),await this.#a}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let r=[];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);(0,n.isMissing)(e)?this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}}):(0,n.exceedsSize)(e,this.#n)?this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}}):(this.send(i,e),r.push({input:i,schemaLog:e}))}r.length>0&&throwFirstFailure(await Promise.allSettled([this.flushToLogfire(r.length),this.store(r)]))}async flushToLogfire(e){await this.#r.flush(),this.#i?.info({message:`Sent ${e} schema log(s) to logfire`,category:`DatasetsSink`})}async store(e){let t=this.#o;if(!t)return;let n=/* @__PURE__ */ new Date,r=await Promise.allSettled(e.map(({input:e,schemaLog:r})=>{let i={...r,actionRunId:e.actionRunId,timestamp:n.toISOString(),...this.#c&&{region:this.#c}},a=writeStoredLog({bucket:t,key:schemaLogKey(i),body:JSON.stringify(i),description:`schema log for actionRunId ${e.actionRunId}`,errorCode:`DatasetsSchemaLogWriteError`,category:`DatasetsSink`,logger:this.#i});return withinDeadline(a,it,`Schema log write to ${t.name} did not finish within ${it}ms`)})),i=r.filter(e=>e.status===`fulfilled`).length;i>0&&this.#i?.info({message:`Wrote ${i} schema log(s) to ${t.name}`,category:`DatasetsSink`}),throwFirstFailure(r)}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 schemaLogKey=e=>[`action_schemas`,keySegment(e.organizationId),keySegment(e.actionId),e.timestamp.slice(0,10),`${keySegment(e.actionRunId)}-${(0,r.randomUUID)()}.json`].join(`/`),keySegment=e=>e?encodeURIComponent(e).replaceAll(`.`,`%2E`).slice(0,200):`unknown`,withinDeadline=(e,t,n)=>{let r,i=new Promise((e,i)=>{r=setTimeout(()=>i(Error(n)),t),r.unref?.()});return Promise.race([e,i]).finally(()=>clearTimeout(r))},throwFirstFailure=e=>{let t=e.find(e=>e.status===`rejected`);if(t)throw t.reason},X=`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(){this.#t&&this.#r?.warning({message:`No storage provided, defender sink will not function`,category:X})}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)this.#r?.debug({message:`Defender sink called to send action`,category:X,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,options:{enabled:t?.enabled}}}),t?.enabled?(0,n.isMissing)(a.defenderContext)?(this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:X,context:{actionRunId:i.actionRunId}}),r.push(null)):r.push(await this.send(i,a)):(this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:X}),r.push(null));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:X});else return readStoredLog({bucket:this.requireBucket(),key:defenderKey(e,t,n),description:`defender log for actionRunId ${n}`,errorCode:`DefenderLogReadError`,category:X,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=/* @__PURE__ */ 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:X,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:X,logger:this.#r}),{expiresAt:a}}};const defenderKey=(e,t,n)=>`${e}/${t}/${n}/defender.json`,Z={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`,piiRedactionEnabled:!1},defender:{enabled:!0},policy:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...Z.logs,...e?.logs},advanced:{...Z.advanced,...e?.advanced},defender:{...Z.defender,...e?.defender},policy:{...Z.policy,...e?.policy},datasets:{...Z.datasets,...e?.datasets}}}function getPolicySink(e,t,n){return new PolicySink(e,t,n)}const Q=`PolicySink`;var PolicySink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.ttlDays??365,this.#r=n}async initialize(){this.#t&&this.#r?.warning({message:`No storage provided, policy sink will not function`,category:Q})}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let r=[];for(let{input:i,result:a}of e)if(!t?.enabled)r.push(null);else if(!this.#e&&!this.#t)r.push(null);else if((0,n.isMissing)(a.policyContext))r.push(null);else{if(!this.#e)throw Error(`No storage available, cannot send to policy sink`);r.push(await this.send(this.#e,i,a))}return r}async getAction(e,t,n,r){if(this.#t)this.#r?.warning({message:`No storage available, cannot get action log from policy sink`,category:Q});else if(this.#e)return readStoredLog({bucket:this.#e,key:policyKey(e,t,n,r),description:`policy log for actionRunId ${r}`,errorCode:`PolicyLogReadError`,category:Q,logger:this.#r})}async send(e,t,n){let r=new Date(Date.now()+this.#n*24*60*60*1e3);return await writeStoredLog({bucket:e,key:policyKey(t.organizationId,t.projectSecureId,t.accountSecureId,t.actionRunId),body:JSON.stringify(n.policyContext),ttlTag:`${this.#n}d`,expiresAt:r,description:`policy log`,errorCode:`PolicyLogWriteError`,category:Q,logger:this.#r}),{expiresAt:r}}};const policyKey=(e,t,n,r)=>`${e}/${t}/${n}/${r}/policy.json`,at=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${at}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${at}${e} failed with ${r.status}`);return r},fetchGoogleAccessToken=async e=>{let t=await(await requestMetadata(`/token`,e)).json();if(!t.access_token||typeof t.expires_in!=`number`)throw Error(`Google metadata token response missing access_token or expires_in`);return{accessToken:t.access_token,expiresInSeconds:t.expires_in}},fetchGoogleServiceAccountEmail=async e=>{let t=(await(await requestMetadata(`/email`,e)).text()).trim();if(!t)throw Error(`Google metadata returned an empty service account email`);return t},encodeSegment=e=>Buffer.from(e,`utf8`).toString(`base64url`),ot=/* @__PURE__ */ __name(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=ot(n);return e?.logger?.warning({message:`Google Kafka token refresh failed, using cached token: ${t.message}`,error:t,code:`GoogleKafkaTokenRefreshFailed`,category:`googleKafkaToken`}),i}throw n}).finally(()=>{r.inflight=void 0}),r.inflight)};return async()=>{try{let[{accessToken:e,expiresAtSeconds:n},r]=await Promise.all([credential(),principal()]);return encodeGoogleKafkaToken(e,{principal:r,issuedAtSeconds:t(),expiresAtSeconds:n})}catch(t){let n=ot(t);throw e?.logger?.error({message:`Failed to mint Google Kafka token: ${n.message}`,error:n,code:`GoogleKafkaTokenError`,category:`googleKafkaToken`}),n}}},resolveSasl=(e,t)=>e.mechanism!==`OAUTHBEARER`||e.token?e:{...e,token:createGoogleKafkaTokenProvider({logger:t})},failedOnClosedConnection=e=>{let{code:t,canRetry:n,errors:r}=e??{};return Array.isArray(r)&&r.length>0?r.every(failedOnClosedConnection):t===`PLT_KFK_NETWORK`&&n===!0},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,a,o,s=/* @__PURE__ */ new Set,closeQuietly=async e=>{try{await e.close()}catch(e){let t=e instanceof Error?e:Error(String(e));n?.warning({message:`Error closing kafka producer: ${t.message}`,error:t,code:`KafkaProducerCloseError`,category:`buildKafkaClient`})}},dispose=e=>{let t=closeQuietly(e).finally(()=>{s.delete(t)});return s.add(t),t},reconstruct=async e=>{if(a||o)return;let s=Date.now();if(!(s-i<3e4)){i=s;try{let i=r;o=t();let s=await o;if(a){await dispose(s);return}r=s,dispose(i),n?.warning({message:`Kafka producer reconstructed after send failure: ${e.message}`,error:e,code:`KafkaProducerReconstructed`,category:`buildKafkaClient`})}catch(e){let t=e;n?.error({message:`Error reconstructing kafka producer: ${t.message}`,error:t,code:`KafkaProducerReconstructionError`,category:`buildKafkaClient`})}finally{o=void 0}}},close=async()=>(a??=(async()=>{let e=o;for(await closeQuietly(r),e&&await e.catch(()=>void 0);s.size>0;)await Promise.allSettled([...s])})(),a),send=async e=>{let t=r;try{return await t.send(e)}catch(n){if(await reconstruct(n),r!==t&&!a&&failedOnClosedConnection(n))return r.send(e);throw n}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;if(t===`close`)return close;let n=Reflect.get(r,t,r);return typeof n==`function`?n.bind(r):n}})},buildKafkaClient=async(e,t)=>{if(!e)return;let construct=async()=>{let{Producer:n,stringSerializers:r}=await import(`@platformatic/kafka`);return new n({retries:3,retryDelay:1e3,...e,...e.sasl&&{sasl:resolveSasl(e.sasl,t)},serializers:r})};try{return withLazyReconstruction(await construct(),construct,t)}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},toError=e=>e instanceof Error?e:Error(String(e)),createMskKafkaTokenProvider=({region:e,logger:t})=>async()=>{try{let{generateAuthToken:t}=await import(`aws-msk-iam-sasl-signer-js`),{token:n}=await t({region:e});return n}catch(e){let n=toError(e);throw t?.error({message:`Failed to mint MSK Kafka token: ${n.message}`,error:n,code:`MskKafkaTokenError`,category:`mskKafkaToken`}),n}},rotateBootstrapBrokers=(e,t=Math.random)=>{let n=Math.floor(t()*e.length);return[...e.slice(n),...e.slice(0,n)]},buildInternalKafkaClient=async(e,t,n=Math.random)=>{if(!e)return;let{bootstrapBrokers:r,region:i,clientId:a,...o}=e;return buildKafkaClient({bootstrapBrokers:rotateBootstrapBrokers(r,n),clientId:a??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:i,logger:t})},...o},t)},defaultStorage=e=>e?.advanced?.bucket||e?.defender?.bucket||e?.policy?.bucket||e?.datasets?.bucket?(0,o.createStorage)((0,o.storageConfigFromEnv)()):void 0;var $=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){this.name=`OlapClient`,this.#c=e,this.#l=i??r,this.#u=t,this.#d=a,this.#m=o,this.#f=s,this.#p=c,this.#t=n??defaultStorage(c),this.#n=l}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){let u=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});return await u.initialize(),u}async initialize(){this.#e=await this.#c(this.#l,this.#n);let e=this.#d?{producer:await this.#u(this.#d,this.#n)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#r=new LogsSink(t,this.#n,this.#f,e,this.#m),this.#i=new AdvancedSink(this.#t,this.#p?.advanced,this.#n),this.#a=new DefenderSink(this.#t,this.#p?.defender,this.#n),this.#o=new PolicySink(this.#t,this.#p?.policy,this.#n),this.#s=new DatasetsSink(this.#p?.datasets,this.#n,void 0,this.#t),await this.#r?.initialize(),await this.#i?.initialize(),await this.#s?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async close(e){await Promise.all([this.#r?.close?.(e),this.#s?.close(e)])}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:r,advanced:i,defender:a,policy:o,datasets:s}=resolveOlapOptions(t);this.#n?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:r,advanced:i,defender:a,policy:o,datasets:s}}});for(let t of e)(0,n.isMissing)(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let c=o?.enabled&&this.#o?this.#o.sendActions(e,o).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to policy logs storage: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),l=s?.enabled&&this.#s?this.#s.sendActions(e,s).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[u,d]=await Promise.all([i?.enabled&&this.#i?this.#i.sendActions(e,i).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),a?.enabled&&this.#a?this.#a.sendActions(e,a).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to defender logs storage: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),f=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:u[t]?.expiresAt,defenderExpiresAt:d[t]?.expiresAt}})),p=r?.enabled&&this.#r?this.#r.sendActions(f,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([l,c,p])}async recordStep(e,t,n){await this.recordSteps([{input:e,result:t}],n)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#r&&i.push(this.#r.sendSteps(e,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,r).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to storage: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,r){let{logs:i,advanced:a}=resolveOlapOptions(r);this.#n?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:r,resolvedOptions:{logs:i,advanced:a}}}),(0,n.isMissing)(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let o={advancedExpiresAt:(a?.enabled&&this.#i?await this.#i.sendUnified(e,t,a).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};i?.enabled&&this.#r&&await this.#r.sendUnified(e,t,o,i).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#r&&a.push(this.#r.sendProvider(e,t,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to storage: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordPlatform(e,t,n){let r=isPlatformLog(e),i=r&&t&&`data`in t?t:void 0,{logs:a,advanced:o}=resolveOlapOptions(r&&!i?t:n),s=a?.enabled&&this.#r?(r?this.#r.sendPlatform(e,a):this.#r.sendPlatform(e,t??{},a)).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#i?this.#i.sendPlatform(e,i,o).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n){return this.#n?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getLastLogs(e,t,n,r={}){let i={...r,organizationId:e,projectSecureId:t};return this.#n?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#r?.getLastLogs(n,i)||(this.#n?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n){return this.#n?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,r){let i=await this.#r?.getAction(e,t,r);if((0,n.isMissing)(i))this.#n?.debug({message:`Failed to retrieve action log for actionRunId ${r}`,category:`OlapClient`});else return i}async getLog(e,t,n){this.#n?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n}});let r=await this.getLogs(e,t,{logId:n,pageSize:1});if(!r||r.logs.length===0){this.#n?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let i=r.logs[0];if(i.logType===`action`||i.logType===`unified`)return i}async getStepLogs(e,t,n){return this.#n?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,r,i){let a=await this.#r?.getStep(e,t,r,i);if((0,n.isMissing)(a))this.#n?.debug({message:`Failed to retrieve step log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});else return a}async getUnifiedLogs(e,t,n){return this.#n?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,r){let i=await this.#r?.getUnifiedLog(e,t,r);if((0,n.isMissing)(i))this.#n?.debug({message:`Failed to retrieve unified log for requestId ${r}`,category:`OlapClient`});else return i}async getProviderLogs(e,t,n){return this.#n?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getPlatformLogs(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogs(n)||(this.#n?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getPlatformLogDimensions(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform log dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogDimensions(n)||(this.#n?.warning({message:`Failed to query platform log dimensions, returning empty result`,category:`OlapClient`}),{})}async getProviderLog(e,t,r,i){let a=await this.#r?.getProviderLog(e,t,r,i);if((0,n.isMissing)(a))this.#n?.debug({message:`Failed to retrieve provider log for requestId ${r} id ${i}`,category:`OlapClient`});else return a}async getActionAdvancedLog(e,t,r){let i=await this.#i?.getAction(e,t,r);if((0,n.isMissing)(i))this.#n?.debug({message:`Failed to retrieve action advanced log for actionRunId ${r}`,category:`OlapClient`});else return i}async getStepAdvancedLog(e,t,r,i){let a=await this.#i?.getStep(e,t,r,i);if((0,n.isMissing)(a))this.#n?.debug({message:`Failed to retrieve step advanced log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});else return a}async getUnifiedAdvancedLog(e,t,r){let i=await this.#i?.getUnified(e,t,r);if((0,n.isMissing)(i))this.#n?.debug({message:`Failed to retrieve unified advanced log for requestId ${r}`,category:`OlapClient`});else return i}async getProviderAdvancedLog(e,t,r,i){let a=await this.#i?.getProvider(e,t,r,i);if((0,n.isMissing)(a))this.#n?.debug({message:`Failed to retrieve provider advanced log for requestId ${r} id ${i}`,category:`OlapClient`});else return a}async getPlatformAdvancedLog(e,t){let r=await this.#i?.getPlatform(e,t);if((0,n.isMissing)(r))this.#n?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});else return r}async getPolicyLog(e,t,r,i){let a=await this.#o?.getAction(e,t,r,i);if((0,n.isMissing)(a))this.#n?.debug({message:`Failed to retrieve policy log for actionRunId ${i}`,category:`OlapClient`});else return a}async getDefenderLog(e,t,r){let i=await this.#a?.getAction(e,t,r);if((0,n.isMissing)(i))this.#n?.debug({message:`Failed to retrieve defender log for actionRunId ${r}`,category:`OlapClient`});else return i}async getLogsStatsAggregate(e,t,n){return this.#n?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n}}),await this.#r?.getAggregate(e,t,n)??{data:[]}}async getLogsStatsDimensions(e,t,n){return this.#n?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getDimensions(e,t,n)??{}}async getSourceUsage(e,t,n){return this.#n?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSourceUsage(e,t,n)??[]}async getActionsCount(e){if(!this.#r)throw Error(`Cannot count actions: the logs sink is not configured`);return this.#r.getActionsCount(e)}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l})=>$.create({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});var OlapClientManager=class{static{this.olapClientPromise=null}static{this.closingPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l,getOlapClient:u=buildOlapClientInstance}){return this.olapClientPromise||=u({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null,this.closingPromise=null}static async close(e){let t=this.olapClientPromise;if(this.olapClientPromise=null,!t)return this.closingPromise??void 0;let n=this.closingPromise,r=(async()=>{await n?.catch(()=>void 0),await this.drain(t,e)})().finally(()=>{this.closingPromise===r&&(this.closingPromise=null)});return this.closingPromise=r,r}static async drain(e,t){let n,r=!1;try{let i=await Promise.race([e,new Promise((e,t)=>{n=setTimeout(()=>{r=!0,t(/* @__PURE__ */ Error(`timed out waiting for olap initialisation`))},6e4),n.unref?.()})]);n&&=(clearTimeout(n),void 0),await i.close?.(t)}catch{}finally{n&&clearTimeout(n),r&&e.then(e=>e.close?.(t)).catch(()=>void 0)}}};exports.AuthType=te,exports.DEFAULT_TOPIC_CLUSTER_MAP=v,exports.Dimension=_e,exports.IntervalType=_,exports.InvalidAuthPairError=InvalidAuthPairError,exports.InvalidLogQueryConditionsError=InvalidLogQueryConditionsError,exports.LOG_QUERY_FIELDS=b,exports.LOG_QUERY_OPERATORS=S,exports.LogType=g,exports.OlapClient=$,exports.OlapClientManager=OlapClientManager,exports.OrderBy=he,exports.OrderDirection=ge,exports.PlatformDimension=ve,exports.PolicySink=PolicySink,exports.QueryClientNotConfiguredError=QueryClientNotConfiguredError,exports.SourceType=m,exports.StreamType=ee,exports.TransportType=h,exports.callerHeadersOf=callerHeadersOf,exports.getPolicySink=getPolicySink,exports.hasErrorEntries=hasErrorEntries,exports.parseLogQueryConditions=parseLogQueryConditions;
|
package/dist/index.d.cts
CHANGED
package/dist/index.d.mts
CHANGED