@stackone/olap 1.67.0 → 1.68.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 +26 -0
- package/dist/index.cjs +25 -101
- package/dist/index.d.cts +7 -8
- package/dist/index.d.mts +7 -8
- package/dist/index.mjs +25 -101
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhouse/client";import{calculateSize as n,convertKeysToCamelCase as r,exceedsSize as i,extractSchema as a,isDate as o,isMissing as s,isObject as c,isString as l,snakeToCamel as u}from"@stackone/utils";import d from"node:http";import{CensorType as f,redactFields as p,redactObject as m,redactUrl as h}from"@stackone/redaction";import{GetObjectCommand as g,HeadObjectCommand as _,PutObjectCommand as v,S3Client as y}from"@aws-sdk/client-s3";import{OTLPTraceExporter as b}from"@opentelemetry/exporter-trace-otlp-proto";import{resourceFromAttributes as
|
|
2
|
-
({${t}:Nullable(DateTime64(3))} IS NULL OR ${e} >= {${t}:Nullable(DateTime64(3))})
|
|
3
|
-
AND ({${n}:Nullable(DateTime64(3))} IS NULL OR ${e} <= {${n}:Nullable(DateTime64(3))})
|
|
4
|
-
`.trim()}function buildBooleanFilter(e,t){return`({${t}:Nullable(UInt8)} IS NULL OR ${e} = {${t}:Nullable(UInt8)})`}const T={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildActionLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
1
|
+
import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhouse/client";import{calculateSize as n,convertKeysToCamelCase as r,exceedsSize as i,extractSchema as a,isDate as o,isMissing as s,isObject as c,isString as l,snakeToCamel as u}from"@stackone/utils";import d from"node:http";import{CensorType as f,redactFields as p,redactObject as m,redactUrl as h}from"@stackone/redaction";import{GetObjectCommand as g,HeadObjectCommand as _,PutObjectCommand as v,S3Client as y}from"@aws-sdk/client-s3";import{OTLPTraceExporter as b}from"@opentelemetry/exporter-trace-otlp-proto";import{resourceFromAttributes as ee}from"@opentelemetry/resources";import{BasicTracerProvider as te,BatchSpanProcessor as ne}from"@opentelemetry/sdk-trace-base";import{ATTR_SERVICE_NAME as re}from"@opentelemetry/semantic-conventions";import{randomUUID as x}from"crypto";import{ZodError as S,z as C}from"zod";import{HttpClient as ie}from"@stackone/transport";const w=new Map;function registerQuery(e){w.set(e.id,e)}function getQueryDefinition(e){return w.get(e)}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 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 ae={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildActionLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
5
2
|
SELECT
|
|
6
3
|
eventTime,
|
|
7
4
|
startTime,
|
|
@@ -76,7 +73,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
76
73
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
77
74
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
78
75
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
79
|
-
ORDER BY ${sanitizeOrderBy(e.orderBy,
|
|
76
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,ae,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
80
77
|
LIMIT {limit:UInt32}
|
|
81
78
|
OFFSET {offset:UInt32}
|
|
82
79
|
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),actionRunId:toArray(e.actionRunId),accountSecureId:toArray(e.accountSecureId),actionId:toArray(e.actionId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),actionType:toArray(e.actionType),mode:toArray(e.mode),category:toArray(e.category),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),httpMethod:toArray(e.httpMethod),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildActionLogsCountQuery(e){return{sql:`
|
|
@@ -114,7 +111,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
114
111
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
115
112
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
116
113
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
117
|
-
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),actionRunId:toArray(e.actionRunId),accountSecureId:toArray(e.accountSecureId),actionId:toArray(e.actionId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),actionType:toArray(e.actionType),mode:toArray(e.mode),category:toArray(e.category),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),httpMethod:toArray(e.httpMethod),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_action_logs.json`,buildQuery:buildActionLogsQuery,buildCountQuery:buildActionLogsCountQuery});const
|
|
114
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),actionRunId:toArray(e.actionRunId),accountSecureId:toArray(e.accountSecureId),actionId:toArray(e.actionId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),actionType:toArray(e.actionType),mode:toArray(e.mode),category:toArray(e.category),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),httpMethod:toArray(e.httpMethod),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_action_logs.json`,buildQuery:buildActionLogsQuery,buildCountQuery:buildActionLogsCountQuery});const oe={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildStepLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
118
115
|
SELECT
|
|
119
116
|
eventTime,
|
|
120
117
|
startTime,
|
|
@@ -145,7 +142,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
145
142
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
146
143
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
147
144
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
148
|
-
ORDER BY ${sanitizeOrderBy(e.orderBy,
|
|
145
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,oe,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
149
146
|
LIMIT {limit:UInt32}
|
|
150
147
|
OFFSET {offset:UInt32}
|
|
151
148
|
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildStepLogsCountQuery(e){return{sql:`
|
|
@@ -161,7 +158,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
161
158
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
162
159
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
163
160
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
164
|
-
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_step_logs.json`,buildQuery:buildStepLogsQuery,buildCountQuery:buildStepLogsCountQuery});const
|
|
161
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_step_logs.json`,buildQuery:buildStepLogsQuery,buildCountQuery:buildStepLogsCountQuery});const se={startTime:`startTime`,endTime:`endTime`,eventTime:`eventDatetime`,durationMs:`duration`};function buildUnifiedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
165
162
|
SELECT
|
|
166
163
|
eventDatetime as eventTime,
|
|
167
164
|
startTime,
|
|
@@ -239,7 +236,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
239
236
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
240
237
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
241
238
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
242
|
-
ORDER BY ${sanitizeOrderBy(e.orderBy,
|
|
239
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,se,`eventDatetime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
243
240
|
LIMIT {limit:UInt32}
|
|
244
241
|
OFFSET {offset:UInt32}
|
|
245
242
|
`,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),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:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildUnifiedLogsCountQuery(e){return{sql:`
|
|
@@ -279,7 +276,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
279
276
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
280
277
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
281
278
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
282
|
-
`,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),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:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_unified_logs.json`,buildQuery:buildUnifiedLogsQuery,buildCountQuery:buildUnifiedLogsCountQuery});const
|
|
279
|
+
`,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),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:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_unified_logs.json`,buildQuery:buildUnifiedLogsQuery,buildCountQuery:buildUnifiedLogsCountQuery});const ce={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},le=[`requestId`,`resource`,`service`,`subResource`,`childResource`,`action`,`path`,`accountId`,`status`],ue=[`actionRunId`,`actionId`,`actionType`,`category`,`riskLevel`],hasAnyFilter=(e,t)=>{let n=e;return t.some(e=>n[e]!==void 0)},untypedFilter=(e,t)=>e[t],toInt16Filter=e=>{let t=toArray(e),n=t.map(e=>typeof e==`string`&&e.trim()===``?NaN:Number(e)).filter(e=>Number.isInteger(e)&&e>=-32768&&e<=32767);return{values:n,unsatisfiable:t.length>0&&n.length===0}},hasUnsatisfiableFilter=e=>toInt16Filter(e.statusCode).unsatisfiable||toInt16Filter(untypedFilter(e,`status`)).unsatisfiable;function shouldIncludeUnified(e){let t=toArray(e.logType);return t.length>0&&!t.includes(`unified`)||hasUnsatisfiableFilter(e)?!1:!hasAnyFilter(e,ue)}function shouldIncludeActions(e){let t=toArray(e.logType);return t.length>0&&!t.includes(`action`)||hasUnsatisfiableFilter(e)?!1:!hasAnyFilter(e,le)}function buildUnifiedFilters(){return`
|
|
283
280
|
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
284
281
|
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
285
282
|
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
@@ -331,13 +328,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
331
328
|
AND ${buildArrayFilter(`actionType`,`actionType`)}
|
|
332
329
|
AND ${buildArrayFilter(`category`,`category`)}
|
|
333
330
|
AND ${buildArrayFilter(`riskLevel`,`riskLevel`)}
|
|
334
|
-
`.trim()}function
|
|
335
|
-
`)}const A=`
|
|
336
|
-
CAST(NULL AS Nullable(String)) as eventId,
|
|
337
|
-
CAST(NULL AS Nullable(String)) as eventType,
|
|
338
|
-
CAST(NULL AS Nullable(String)) as userId,
|
|
339
|
-
CAST(NULL AS Nullable(String)) as subAction,
|
|
340
|
-
CAST(NULL AS Nullable(String)) as details`;function buildUnifiedSelect(){return`
|
|
331
|
+
`.trim()}function buildUnifiedSelect(){return`
|
|
341
332
|
SELECT
|
|
342
333
|
eventDatetime as eventTime,
|
|
343
334
|
startTime,
|
|
@@ -390,7 +381,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
390
381
|
statusCode,
|
|
391
382
|
CAST(NULL AS Nullable(String)) as message,
|
|
392
383
|
CAST(NULL AS Nullable(String)) as riskLevel,
|
|
393
|
-
CAST(NULL AS Nullable(Float32)) as tier2Score
|
|
384
|
+
CAST(NULL AS Nullable(Float32)) as tier2Score,
|
|
394
385
|
'unified' as logType
|
|
395
386
|
FROM unified_requests
|
|
396
387
|
WHERE 1=1
|
|
@@ -450,78 +441,14 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
450
441
|
statusCode,
|
|
451
442
|
message,
|
|
452
443
|
riskLevel,
|
|
453
|
-
tier2Score
|
|
444
|
+
tier2Score,
|
|
454
445
|
'action' as logType
|
|
455
446
|
FROM actions
|
|
456
447
|
WHERE 1=1
|
|
457
448
|
${buildActionsFilters()}
|
|
458
449
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
459
450
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
460
|
-
`}function
|
|
461
|
-
SELECT
|
|
462
|
-
eventTime,
|
|
463
|
-
startTime,
|
|
464
|
-
endTime,
|
|
465
|
-
durationMs,
|
|
466
|
-
organizationId,
|
|
467
|
-
projectSecureId,
|
|
468
|
-
accountSecureId,
|
|
469
|
-
CAST(NULL AS Nullable(String)) as connectorKey,
|
|
470
|
-
CAST(NULL AS Nullable(String)) as connectorVersion,
|
|
471
|
-
CAST(NULL AS Nullable(String)) as connectorOwner,
|
|
472
|
-
CAST(NULL AS Nullable(String)) as connectorProfileId,
|
|
473
|
-
toLowCardinality(sourceType) as sourceType,
|
|
474
|
-
toLowCardinality(sourceId) as sourceId,
|
|
475
|
-
toLowCardinality(authType) as authType,
|
|
476
|
-
authId,
|
|
477
|
-
sessionId,
|
|
478
|
-
agentId,
|
|
479
|
-
userAgent,
|
|
480
|
-
ipAddress,
|
|
481
|
-
toLowCardinality(transportType) as transportType,
|
|
482
|
-
toLowCardinality(streamType) as streamType,
|
|
483
|
-
CAST(NULL AS Nullable(String)) as sourceValue,
|
|
484
|
-
CAST(NULL AS Nullable(String)) as originOwnerId,
|
|
485
|
-
CAST(NULL AS Nullable(String)) as originOwnerName,
|
|
486
|
-
CAST(NULL AS LowCardinality(Nullable(String))) as mode,
|
|
487
|
-
CAST(NULL AS LowCardinality(Nullable(String))) as httpMethod,
|
|
488
|
-
CAST(NULL AS Nullable(String)) as url,
|
|
489
|
-
success,
|
|
490
|
-
eventId as logId,
|
|
491
|
-
CAST(NULL AS Nullable(DateTime64(3))) as advancedExpiresAt,
|
|
492
|
-
CAST(NULL AS Nullable(DateTime64(3))) as defenderExpiresAt,
|
|
493
|
-
-- non-common fields
|
|
494
|
-
CAST(NULL AS Nullable(String)) as requestId,
|
|
495
|
-
CAST(NULL AS Nullable(String)) as path,
|
|
496
|
-
CAST(NULL AS Nullable(String)) as resource,
|
|
497
|
-
CAST(NULL AS Nullable(String)) as subResource,
|
|
498
|
-
CAST(NULL AS Nullable(String)) as childResource,
|
|
499
|
-
service,
|
|
500
|
-
action,
|
|
501
|
-
CAST(NULL AS Nullable(Int16)) as status,
|
|
502
|
-
CAST(NULL AS Nullable(String)) as accountId,
|
|
503
|
-
CAST(NULL AS Nullable(String)) as provider,
|
|
504
|
-
CAST(NULL AS Nullable(UInt8)) as isWorker,
|
|
505
|
-
CAST(NULL AS Nullable(UInt8)) as isBackground,
|
|
506
|
-
CAST(NULL AS Nullable(String)) as actionRunId,
|
|
507
|
-
CAST(NULL AS Nullable(String)) as actionId,
|
|
508
|
-
CAST(NULL AS Nullable(String)) as actionType,
|
|
509
|
-
CAST(NULL AS Nullable(String)) as category,
|
|
510
|
-
CAST(NULL AS Nullable(Int16)) as statusCode,
|
|
511
|
-
CAST(NULL AS Nullable(String)) as message,
|
|
512
|
-
CAST(NULL AS Nullable(String)) as riskLevel,
|
|
513
|
-
CAST(NULL AS Nullable(Float32)) as tier2Score,
|
|
514
|
-
eventId,
|
|
515
|
-
eventType,
|
|
516
|
-
userId,
|
|
517
|
-
subAction,
|
|
518
|
-
details,
|
|
519
|
-
'platform' as logType
|
|
520
|
-
FROM platform
|
|
521
|
-
WHERE 1=1
|
|
522
|
-
${buildPlatformFilters()}
|
|
523
|
-
AND ${buildDateRangeFilter(`eventTime`,`startTime`,`endTime`)}
|
|
524
|
-
`}function buildCombinedSourceSql(e){let t=[shouldIncludeUnified(e)?buildUnifiedSelect():void 0,shouldIncludeActions(e)?buildActionsSelect():void 0,shouldIncludePlatform(e)?buildPlatformSelect():void 0].filter(e=>e!==void 0);return t.length===0?`${buildUnifiedSelect()} AND 1 = 0`:t.join(` UNION ALL `)}function buildCommonLogParams(e){return{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toInt16Filter(e.statusCode).values,isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),logId:toArray(e.logId),service:toArray(e.service),action:toArray(e.action),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),eventId:toArray(e.eventId),eventType:toArray(e.eventType),userId:toArray(e.userId),subAction:toArray(e.subAction),requestId:toArray(e.requestId),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),actionRunId:toArray(e.actionRunId),actionId:toArray(e.actionId),actionType:toArray(e.actionType),category:toArray(e.category),path:toArray(untypedFilter(e,`path`)),accountId:toArray(untypedFilter(e,`accountId`)),riskLevel:toArray(untypedFilter(e,`riskLevel`)),status:toInt16Filter(untypedFilter(e,`status`)).values}}function buildCombinedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize),r=sanitizeOrderBy(e.orderBy,se,`eventTime`),i=sanitizeOrderDirection(e.orderDirection);return{sql:`
|
|
451
|
+
`}function buildCombinedSourceSql(e){let t=[shouldIncludeUnified(e)?buildUnifiedSelect():void 0,shouldIncludeActions(e)?buildActionsSelect():void 0].filter(e=>e!==void 0);return t.length===0?`${buildUnifiedSelect()} AND 1 = 0`:t.join(` UNION ALL `)}function buildCommonLogParams(e){return{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toInt16Filter(e.statusCode).values,isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),logId:toArray(e.logId),requestId:toArray(e.requestId),resource:toArray(e.resource),service:toArray(e.service),subResource:toArray(e.subResource),childResource:toArray(e.childResource),action:toArray(e.action),actionRunId:toArray(e.actionRunId),actionId:toArray(e.actionId),actionType:toArray(e.actionType),category:toArray(e.category),path:toArray(untypedFilter(e,`path`)),accountId:toArray(untypedFilter(e,`accountId`)),riskLevel:toArray(untypedFilter(e,`riskLevel`)),status:toInt16Filter(untypedFilter(e,`status`)).values}}function buildCombinedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize),r=sanitizeOrderBy(e.orderBy,ce,`eventTime`),i=sanitizeOrderDirection(e.orderDirection);return{sql:`
|
|
525
452
|
WITH combined AS (
|
|
526
453
|
${buildCombinedSourceSql(e)}
|
|
527
454
|
)
|
|
@@ -543,13 +470,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
543
470
|
${buildActionsFilters()}
|
|
544
471
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
545
472
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
546
|
-
`),
|
|
547
|
-
SELECT count() as cnt
|
|
548
|
-
FROM platform
|
|
549
|
-
WHERE 1=1
|
|
550
|
-
${buildPlatformFilters()}
|
|
551
|
-
AND ${buildDateRangeFilter(`eventTime`,`startTime`,`endTime`)}
|
|
552
|
-
`),{sql:t.length>0?`SELECT sum(cnt) as total FROM (${t.join(` UNION ALL `)})`:`SELECT 0 as total`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs.json`,buildQuery:buildCombinedLogsQuery,buildCountQuery:buildCombinedLogsCountQuery});const j={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,isBackground:`isBackground`},M=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`]);function buildDimensionsQuery(e){let t=toCsvArray(e.dimensions).map(u),n=e.maxValues??100,r=t.filter(e=>Object.prototype.hasOwnProperty.call(j,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildCombinedSourceSql(e);return{sql:r.map(e=>{let t=j[e];return`
|
|
473
|
+
`),{sql:t.length>0?`SELECT sum(cnt) as total FROM (${t.join(` UNION ALL `)})`:`SELECT 0 as total`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs.json`,buildQuery:buildCombinedLogsQuery,buildCountQuery:buildCombinedLogsCountQuery});const T={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,isBackground:`isBackground`},E=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`]);function buildDimensionsQuery(e){let t=toCsvArray(e.dimensions).map(u),n=e.maxValues??100,r=t.filter(e=>Object.prototype.hasOwnProperty.call(T,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildCombinedSourceSql(e);return{sql:r.map(e=>{let t=T[e];return`
|
|
553
474
|
SELECT
|
|
554
475
|
'${e}' as dimension,
|
|
555
476
|
arrayReverseSort(
|
|
@@ -564,14 +485,14 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
564
485
|
${i}
|
|
565
486
|
) AS combined
|
|
566
487
|
WHERE ${t} IS NOT NULL
|
|
567
|
-
${
|
|
488
|
+
${E.has(e)?`AND ${t} != ''`:``}
|
|
568
489
|
GROUP BY ${t}
|
|
569
490
|
ORDER BY count DESC
|
|
570
491
|
LIMIT {maxValues:UInt32}
|
|
571
492
|
) AS facets
|
|
572
493
|
`}).join(`
|
|
573
494
|
UNION ALL
|
|
574
|
-
`),params:{...buildCommonLogParams(e),maxValues:n}}}registerQuery({id:`project_logs_dimensions.json`,buildQuery:buildDimensionsQuery});const narrowScanFilter=(e,t,n)=>{if(!(t in e))return{};let r=e[t],i=r.length===0?n:n.filter(e=>r.includes(e));return i.length===0?{}:{[t]:i}},buildLastLogsQuery=e=>{let t=e.entities?.field;if(!t||!
|
|
495
|
+
`),params:{...buildCommonLogParams(e),maxValues:n}}}registerQuery({id:`project_logs_dimensions.json`,buildQuery:buildDimensionsQuery});const narrowScanFilter=(e,t,n)=>{if(!(t in e))return{};let r=e[t],i=r.length===0?n:n.filter(e=>r.includes(e));return i.length===0?{}:{[t]:i}},buildLastLogsQuery=e=>{let t=e.entities?.field;if(!t||!E.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=`
|
|
575
496
|
WITH combined AS (
|
|
576
497
|
${buildCombinedSourceSql(e)}
|
|
577
498
|
)
|
|
@@ -579,7 +500,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
579
500
|
WHERE ${t} IN {entityIds:Array(String)}
|
|
580
501
|
ORDER BY eventTime DESC
|
|
581
502
|
LIMIT 1 BY ${t}
|
|
582
|
-
`,r=toArray(e.entities?.ids),i=buildCommonLogParams(e);return{sql:n,params:{...i,...narrowScanFilter(i,t,r),entityIds:r}}};registerQuery({id:`project_last_logs.json`,buildQuery:buildLastLogsQuery});const
|
|
503
|
+
`,r=toArray(e.entities?.ids),i=buildCommonLogParams(e);return{sql:n,params:{...i,...narrowScanFilter(i,t,r),entityIds:r}}};registerQuery({id:`project_last_logs.json`,buildQuery:buildLastLogsQuery});const D={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),de={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},fe={Asc:`asc`,Desc:`desc`},O={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},pe={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,IsBackground:`isBackground`},k={actions:[`external`],steps:[`external`],unified_requests:[`external`],provider_requests:[`external`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===D.Platform,A={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,isBackground:`isBackground`},j={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},M={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(j,e)?j[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(M,e)?M[e]:3600);return`toDateTime(intDiv(toUnixTimestamp(${n}(eventTime)), ${r}) * ${r})`}function buildAggregationQuery(e){let t=toCsvArray(e.dimensions).map(u),n=e.intervalType??`hour`,r=Math.floor(Number(e.intervalPeriod??1)),i=Number.isFinite(r)&&r>0?r:1,a=t.filter(e=>Object.prototype.hasOwnProperty.call(A,e)).map(e=>A[e]),o=n===O.None?void 0:buildTimeBucket(n,i),s=[...o?[`${o} as startTime`]:[],`count() as count`,...a].join(`, `),c=[...o?[`startTime`]:[],...a],l=c.length>0?`GROUP BY ${c.join(`, `)}`:``,d=o?`ORDER BY startTime ASC`:``;return{sql:`
|
|
583
504
|
WITH combined AS (
|
|
584
505
|
${buildCombinedSourceSql(e)}
|
|
585
506
|
)
|
|
@@ -588,7 +509,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
588
509
|
FROM combined
|
|
589
510
|
${l}
|
|
590
511
|
${d}
|
|
591
|
-
`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const
|
|
512
|
+
`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const me={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildProviderLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
592
513
|
SELECT
|
|
593
514
|
eventDatetime as eventTime,
|
|
594
515
|
startTime,
|
|
@@ -628,7 +549,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
628
549
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
629
550
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
630
551
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
631
|
-
ORDER BY ${sanitizeOrderBy(e.orderBy,
|
|
552
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,me,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
632
553
|
LIMIT {limit:UInt32}
|
|
633
554
|
OFFSET {offset:UInt32}
|
|
634
555
|
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildProviderLogsCountQuery(e){return{sql:`
|
|
@@ -643,7 +564,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
643
564
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
644
565
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
645
566
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
646
|
-
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_provider_logs.json`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery});const
|
|
567
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_provider_logs.json`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery});const N={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
647
568
|
SELECT
|
|
648
569
|
eventTime,
|
|
649
570
|
startTime,
|
|
@@ -668,6 +589,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
668
589
|
agentId,
|
|
669
590
|
transportType,
|
|
670
591
|
streamType,
|
|
592
|
+
isRead,
|
|
671
593
|
success,
|
|
672
594
|
details,
|
|
673
595
|
'platform' as logType
|
|
@@ -692,13 +614,14 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
692
614
|
AND ({agentId:Array(String)} = [] OR agentId IN {agentId:Array(String)})
|
|
693
615
|
AND ({transportType:Array(String)} = [] OR transportType IN {transportType:Array(String)})
|
|
694
616
|
AND ({streamType:Array(String)} = [] OR streamType IN {streamType:Array(String)})
|
|
617
|
+
AND ({isRead:Nullable(UInt8)} IS NULL OR isRead = {isRead:Nullable(UInt8)})
|
|
695
618
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
696
619
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
697
620
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
698
|
-
ORDER BY ${sanitizeOrderBy(e.orderBy,
|
|
621
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,N,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
699
622
|
LIMIT {limit:UInt32}
|
|
700
623
|
OFFSET {offset:UInt32}
|
|
701
|
-
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),action:toArray(e.action),subAction:toArray(e.subAction),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildPlatformLogsCountQuery(e){return{sql:`
|
|
624
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),action:toArray(e.action),subAction:toArray(e.subAction),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildPlatformLogsCountQuery(e){return{sql:`
|
|
702
625
|
SELECT count() as total
|
|
703
626
|
FROM platform
|
|
704
627
|
WHERE 1=1
|
|
@@ -721,10 +644,11 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
721
644
|
AND ({agentId:Array(String)} = [] OR agentId IN {agentId:Array(String)})
|
|
722
645
|
AND ({transportType:Array(String)} = [] OR transportType IN {transportType:Array(String)})
|
|
723
646
|
AND ({streamType:Array(String)} = [] OR streamType IN {streamType:Array(String)})
|
|
647
|
+
AND ({isRead:Nullable(UInt8)} IS NULL OR isRead = {isRead:Nullable(UInt8)})
|
|
724
648
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
725
649
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
726
650
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
727
|
-
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),action:toArray(e.action),subAction:toArray(e.subAction),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`organization_platform_logs.json`,buildQuery:buildPlatformLogsQuery,buildCountQuery:buildPlatformLogsCountQuery});function buildSourceUsageQuery(e){return{sql:`
|
|
651
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),action:toArray(e.action),subAction:toArray(e.subAction),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`organization_platform_logs.json`,buildQuery:buildPlatformLogsQuery,buildCountQuery:buildPlatformLogsCountQuery});function buildSourceUsageQuery(e){return{sql:`
|
|
728
652
|
SELECT
|
|
729
653
|
sourceId,
|
|
730
654
|
sourceType,
|
|
@@ -741,4 +665,4 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
741
665
|
AND sourceId != ''
|
|
742
666
|
GROUP BY sourceId, sourceType
|
|
743
667
|
ORDER BY request_count DESC
|
|
744
|
-
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_source_usage.json`,buildQuery:buildSourceUsageQuery});var SchemaValidationError$1=class extends Error{static{e(this,`SchemaValidationError`)}constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,e?.url&&(this.#e=t({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){try{let t=await this.#a(e.endpoint,e.params);return this.#i(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#a(e.endpoint,e.params),n=this.#i(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryRaw(e){try{let t=await this.#a(e.endpoint,e.params);return t.data=this.#i(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}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$1(t,e)}}async#a(e,t){let n=this.#r(),r=getQueryDefinition(e);if(!r)throw Error(`Unknown endpoint: ${e}. No query definition registered.`);let{sql:i,params:a}=r.buildQuery(t??{});this.#n?.debug({message:`Querying clickhouse endpoint: ${e}`,category:`ClickHouseClient`,context:{endpoint:e,params:t}});let o=Date.now(),s=await(await n.query({query:i,query_params:a,format:`JSONEachRow`})).json(),c=(Date.now()-o)/1e3,l;if(r.buildCountQuery){let{sql:e,params:i}=r.buildCountQuery(t??{});l=(await(await n.query({query:e,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${s.length} rows`,category:`ClickHouseClient`,context:{endpoint:e,rows:s.length,elapsed:c}}),{meta:[],data:s,rows:s.length,rows_before_limit_at_least:l,statistics:{elapsed:c,rows_read:s.length,bytes_read:0}}}},SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},TinybirdClient=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async query(e){try{let t=await this.#o(e.endpoint,e.params);return this.#a(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#o(e.endpoint,e.params),n=this.#a(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryRaw(e){try{let t=await this.#o(e.endpoint,e.params);return t.data=this.#a(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.token)}#r(){return new d.Agent({})}#i(){if(!this.#e)throw this.#n?.error({message:`HTTP client not initialized, cannot perform Tinybird query`,category:`TinybirdClient`,code:`HttpClientNotReady`}),Error(`HTTP client is not initialized`);if(!this.#t?.token)throw this.#n?.warning({message:`Missing OLAP token, cannot perform Tinybird query`,category:`TinybirdClient`}),Error(`TinybirdClient - Missing token`)}#a(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:`TinybirdClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`TinybirdClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#o(e,t){this.#i();let n=this.#e,r=this.#t;if(!n||!r)throw Error(`Client validation failed`);let i=new URL(`/v0/pipes/${e}`,r.baseUrl);this.#n?.debug({message:`Querying tinybird endpoint: ${e}`,category:`TinybirdClient`,context:{endpoint:e,params:t}});let a=await n.request({method:`post`,url:i.toString(),payload:t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r.token}`},...r.allowHttp&&{httpAgent:this.#r()}});return this.#n?.debug({message:`Tinybird query returned ${a.data.data.length} rows`,category:`TinybirdClient`,context:{endpoint:e,rows:a.data.rows,statistics:a.data.statistics}}),a.data}};function createOlapQueryClient(e,t,n){switch(e.type){case`clickhouse`:if(!e.clickhouse)throw Error(`ClickHouse config required when type is "clickhouse"`);return new ClickHouseClient(e.clickhouse,n);default:return new TinybirdClient(t,e.tinybird,n)}}function createConfigFromEnv(){let e=process.env.TINYBIRD_BASE_URL,t=process.env.TINYBIRD_TOKEN,n=e&&t?{baseUrl:e,token:t,allowHttp:process.env.TINYBIRD_ALLOW_HTTP===`true`}:void 0,r=process.env.CLICKHOUSE_URL,i=r?{url:r,username:process.env.CLICKHOUSE_USER,password:process.env.CLICKHOUSE_PASSWORD,database:process.env.CLICKHOUSE_DATABASE??`olap`,requestTimeout:(()=>{if(!process.env.CLICKHOUSE_TIMEOUT)return;let e=Number.parseInt(process.env.CLICKHOUSE_TIMEOUT,10);return Number.isFinite(e)?e:void 0})()}:void 0;return{type:n?`tinybird`:i?`clickhouse`:`tinybird`,tinybird:n,clickhouse:i}}const z={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`},me={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},he={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},ge={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},_e=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],ve=[z.Scheduler,z.DataSync,z.DataSyncV2,z.Internal],ye=[`data_sync`],be=[z.DataSync,z.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&_e.includes(e)||t&&ve.includes(t))}function isDataSync(e,t){return!!(e&&ye.includes(e)||t&&be.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},hasErrorEntries=e=>s(e)?!1:Array.isArray(e)||l(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,B=64*1024,V=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],H=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>c(e)?e[t]:void 0,e),withPath=(e,t,n)=>{let[r,...i]=t.split(`.`);if(i.length===0)return{...e,[r]:n};let a=e[r];return c(a)?{...e,[r]:withPath(a,i.join(`.`),n)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,t)=>{let{kept:r,total:i}=e.reduce((e,r)=>{if(e.total>t)return e;let i=e.total+n(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+n(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=n(e);return r<=t?e:(l(e)||Array.isArray(e)||c(e)&&!o(e))&&t<=0?marker(r):l(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):c(e)&&!o(e)?fitObject(e,t):e},payloadFields=e=>V.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!s(e)).map(e=>({...e,size:n(e.value)})),byRetentionPriority=e=>[...e.filter(e=>H.includes(e.path)),...e.filter(e=>!H.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*B;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(B,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=>V.reduce((e,t)=>readPath(e,t)===void 0?e:withPath(e,t,void 0),e),isErrorResult=e=>e.success===!1||e.hasStepErrors===!0||(e.statusCode??0)>=400||hasErrorEntries(e.errors),xe=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],Se=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],Ce=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`;var AdvancedSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n}async initialize(){if(!this.#e){this.#i?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}}requireBucket(){if(!this.#t)throw Error(`Advanced sink bucket is not configured`);return this.#t}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(r.mode,r.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&i.success&&!i.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${r.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`AdvancedSink`}),n.push(null);continue}let e=this.createActionS3(r,i,t),a=await this.send(e,t?.ttl);n.push(a)}return n}async sendStep(e,t,n){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0&&t.success!==!1&&!hasErrorEntries(t.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let r=this.createStepS3(e,t,n);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r=this.createUnifiedS3(e,t,n);try{return await this.send(r,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=this.createProviderS3(e,t,n);try{return await this.send(r,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){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new g({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new g({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new g({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new g({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e)throw Error(`No s3 client available, cannot send to advanced sink`);let n=this.requireBucket(),r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);this.#i?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:a.toISOString()}});try{return await this.#e.send(new v({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:a,Tagging:r})),{expiresAt:a}}catch(t){throw this.#i?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}async getObjectExpiry(e){if(!this.#e)return this.#i?.warning({message:`No s3 client available, cannot check object expiry`,category:`AdvancedSink`}),{exists:!1};let t=this.requireBucket();try{return{exists:!0,expiresAt:(await this.#e.send(new _({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#i?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#i?.error({message:`Error when checking object expiry in S3 for key ${e}`,error:t,code:`AdvancedLogHeadError`,category:`AdvancedSink`}),t}}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;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformS3(e,t,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){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get platform log from advanced sink`,category:`AdvancedSink`});return}let n=this.requireBucket();try{let r=new g({Bucket:n,Key:platformKey(e,t)}),i=await this.#e.send(r);if(!i.Body){this.#i?.warning({message:`Received empty body when trying to get platform log from S3 for eventId ${t}`,category:`AdvancedSink`});return}let a=await i.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved platform advanced log from S3 for eventId ${t}`,category:`AdvancedSink`}),JSON.parse(a)}catch(e){let n=e;if(n.name===`NoSuchKey`||n.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Platform advanced log not found in S3 for eventId ${t}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting platform advanced log from S3 for eventId ${t}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionS3(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)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(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)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createPlatformS3(e,t,n){let r=platformKey(e.organizationId,e.eventId),i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,ContentType:`application/json`,Expires:new Date(i*1e3),Body:this.serializePlatformAdvanced(t,i)}}serializePlatformAdvanced(e,t){let r=p(e.data,f.PARTIAL,!0),i={...e.metadata,expirationTime:t,sizeBytes:n(r)};return this.stringifyPlatform({data:r,metadata:i},i)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedS3(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)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(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)),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r,i){let a=m({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},f.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=p(e.body,f.PARTIAL,!0),l=p(t.body,f.PARTIAL,!0),u=this.processContent(o,c,`upload`),d=this.processContent(s,l,`download`),g=e.isBackground??isBackgroundLog(e.mode,e.sourceType),_=e.url,v={};if(e.url)try{_=h(e.url,f.PARTIAL);let t=new URL(_);v=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let y={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:_,path:e.pathParams,queryParams:v},body:u},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:d},...g?{isBackgroundLog:!0}:{}},metadata:{...g?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(y,r,isErrorResult(t),i)}serializeStepResult(e,t,n,r,i){let a={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,t,n,r,i){let a=m({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},f.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=p(e.body,f.PARTIAL,!0),l=p(t.body,f.PARTIAL,!0),u=this.processContent(o,c,`upload`),d=this.processContent(s,l,`download`),g=e.isBackground??isBackgroundLog(e.mode,e.sourceType),_=`/`,v=e.url,y={};if(e.url)try{v=h(e.url,f.PARTIAL);let t=new URL(v);_=t.pathname,y=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let b={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:v,path:_,queryParams:y},body:u},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:d}},metadata:{...g?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(b,r,isErrorResult(t),i)}serializeProviderResult(e,t,n,r,i){let a=m({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},f.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=p(e.body,f.PARTIAL,!0),l=p(t.body,f.PARTIAL,!0),u=this.processContent(o,c,`upload`),d=this.processContent(s,l,`download`),g,_=``,v=`/`,y={};if(e.url)try{g=h(e.url,f.PARTIAL);let t=new URL(g);_=t.hostname,v=t.pathname,y=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let b={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:g,hostname:_,path:v,queryParams:y},body:u},response:{statusCode:t.statusCode,headers:this.filterHeaders(s),body:d}},metadata:{expirationTime:n}};return this.serializeAndLimit(b,r,isErrorResult(t),i)}serializeAndLimit(e,t,r,i){let a=n(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=xe.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return Se.includes(i)||Ce.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!s(e)){if(!l(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};function defaultProviderFactory(e){let t=new b({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[ne]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new ee({resource:x(n),spanProcessors:[new te(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(this.#r)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let n=0;for(let{input:r,result:a}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:a.success,statusCode:a.statusCode,includeBackground:t.includeBackground}}),s(r.body)&&s(a.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(r,a);if(s(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(i(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}this.send(r,e),n++}n>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${n} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let n=s(e.body)?void 0:a(e.body),r=s(t.body)?void 0:a(t.body);if(!(s(n)&&s(r)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:n,result:r}}}},DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Defender sink bucket is not configured`);return this.#t}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`}),n.push(null);continue}if(s(i.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:r.actionRunId}}),n.push(null);continue}let e=this.createDefenderS3(r,i),a=await this.send(e);n.push(a)}return n}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=this.requireBucket();try{let i=new g({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#r?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to defender sink`);let t=this.requireBucket(),n=Math.floor(Date.now()/1e3)+this.#n*24*60*60,r=new Date(n*1e3),i=`ttl=${this.#n}d`;this.#r?.debug({message:`Storing defender log in S3 bucket ${t} with ${this.#n}-day TTL`,category:`DefenderSink`,context:{bucket:t,key:e.Key,ttlTag:i,expiresAt:r.toISOString()}});try{return await this.#e.send(new v({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:r,Tagging:i})),{expiresAt:r}}catch(t){throw this.#r?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createDefenderS3(e,t){let n=e.organizationId,r=e.projectSecureId;return{Key:this.generateS3Key(n,r,e.actionRunId),Body:JSON.stringify(t.defenderContext),ContentType:`application/json`}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},U=C.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 C.ZodError([{code:C.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},C.coerce.date()),W=C.object({logType:C.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:U,startTime:U,endTime:U.optional().nullable().transform(e=>e??void 0),durationMs:C.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:C.coerce.string(),projectSecureId:C.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:C.coerce.string().optional().nullable().transform(e=>e??void 0)}),G=W.extend({logType:C.literal(`action`),actionRunId:C.coerce.string(),actionId:C.coerce.string(),connectorKey:C.coerce.string(),connectorVersion:C.coerce.string(),connectorOwner:C.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:C.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:C.coerce.string(),accountSecureId:C.coerce.string(),actionType:C.coerce.string().optional().nullable().transform(e=>e??void 0),mode:C.coerce.string().optional().nullable().transform(e=>e??void 0),category:C.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:C.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:C.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:C.coerce.string().optional().nullable().transform(e=>e??void 0),url:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:C.coerce.string().optional().nullable().transform(e=>e??void 0),authType:C.coerce.string().optional().nullable().transform(e=>e??void 0),authId:C.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:C.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:C.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:C.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:C.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:C.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:C.coerce.string().optional().nullable().transform(e=>e??void 0),success:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:C.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:C.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:C.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:C.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:C.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:C.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:C.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:C.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:C.coerce.number().optional().nullable().transform(e=>e??void 0),isBackground:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:U.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:U.optional().nullable().transform(e=>e??void 0)}),K=W.extend({logType:C.literal(`step`),actionRunId:C.coerce.string(),stepIndex:C.coerce.number(),stepId:C.coerce.string(),projectSecureId:C.coerce.string(),accountSecureId:C.coerce.string(),skipped:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:C.coerce.number().optional().nullable().transform(e=>e??void 0),message:C.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:C.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:C.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:C.coerce.number().optional().nullable().transform(e=>e??void 0)}),q=W.extend({logType:C.literal(`unified`),requestId:C.coerce.string(),connectorKey:C.coerce.string(),connectorVersion:C.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:C.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:C.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:C.coerce.string(),accountSecureId:C.coerce.string(),mode:C.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:C.coerce.string().optional().nullable().transform(e=>e??void 0),url:C.coerce.string().optional().nullable().transform(e=>e??void 0),path:C.coerce.string().optional().nullable().transform(e=>e??void 0),resource:C.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:C.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:C.coerce.string().optional().nullable().transform(e=>e??void 0),service:C.coerce.string().optional().nullable().transform(e=>e??void 0),action:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:C.coerce.string().optional().nullable().transform(e=>e??void 0),authType:C.coerce.string().optional().nullable().transform(e=>e??void 0),authId:C.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:C.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:C.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:C.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:C.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:C.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:C.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:C.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:C.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:C.coerce.number().optional().nullable().transform(e=>e??void 0),success:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:C.coerce.number().optional().nullable().transform(e=>e??void 0),provider:C.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:U.optional().nullable().transform(e=>e??void 0),duration:C.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:U.optional().nullable().transform(e=>e??void 0)}),J=W.extend({logType:C.literal(`provider`),requestId:C.coerce.string(),id:C.coerce.string().optional().nullable().transform(e=>e??void 0),action:C.coerce.string(),mode:C.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:C.coerce.string(),originOwnerId:C.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:C.coerce.string().optional().nullable().transform(e=>e??void 0),url:C.coerce.string(),path:C.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:C.coerce.string(),connectorVersion:C.coerce.string().optional().nullable().transform(e=>e??void 0),resource:C.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:C.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:C.coerce.string().optional().nullable().transform(e=>e??void 0),service:C.coerce.string().optional().nullable().transform(e=>e??void 0),success:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:C.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:C.coerce.string(),accountSecureId:C.coerce.string(),status:C.coerce.number().optional().nullable().transform(e=>e??void 0),provider:C.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:U.optional().nullable().transform(e=>e??void 0),duration:C.coerce.number().optional().nullable().transform(e=>e??void 0)}),Y=W.extend({logType:C.literal(`platform`),eventId:C.coerce.string(),eventType:C.coerce.string(),service:C.coerce.string(),userId:C.coerce.string().optional().nullable().transform(e=>e??void 0),action:C.coerce.string().optional().nullable().transform(e=>e??void 0),subAction:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:C.coerce.string().optional().nullable().transform(e=>e??void 0),authType:C.coerce.string().optional().nullable().transform(e=>e??void 0),authId:C.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:C.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:C.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:C.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:C.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:C.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:C.coerce.string().optional().nullable().transform(e=>e??void 0),success:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:C.coerce.string().optional().nullable().transform(e=>e??void 0)}),we=C.discriminatedUnion(`logType`,[G,K,q,J,Y]),foldTimeBuckets=e=>{let t=new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},requestsPlatformLogs=e=>toArray(e.logType).includes(N.Platform);var LogsSink=class{#e;#t;#n;#r;#i;#a;#o(e){if(e===`clickhouse`&&this.#i?.isReady())return this.#i;if(this.#r?.isReady())return this.#r;if(this.#i?.isReady())return this.#i}#s(e,t){if(!requestsPlatformLogs(e))return this.#o(t);if(this.#i?.isReady())return this.#i;this.#a?.warning({message:`Platform logs were requested but the ClickHouse client is not available`,category:`LogsSink`})}constructor(e,t,n,r,i,a,o){this.#e=e,this.#t=a,this.#n=o,this.#a=r,n&&(this.#r=new TinybirdClient(t,n,r)),i&&(this.#i=new ClickHouseClient(i,r));let s=[];this.#r&&s.push(`tinybird`),this.#i&&s.push(`clickhouse`),s.length>0&&this.#a?.debug({message:`LogsSink initialized with query clients: ${s.join(`, `)}`,category:`LogsSink`})}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#a?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}let e=this.#r?.isReady()??!1,t=this.#i?.isReady()??!1;!e&&!t?this.#a?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}):this.#a?.info({message:`Logs sink query clients ready: tinybird=${e}, clickhouse=${t}`,category:`LogsSink`}),this.#a?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#c()}async#c(){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})=>{try{await t?.connectToBrokers(),this.#a?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#a?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#a?.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.#a?.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.#a?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#a?.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.#a?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#a?.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.#a?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#a?.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,t){let n=this.#s(e,t);try{this.#a?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} logs (${r.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(r.data),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(requestsPlatformLogs(e)||this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getLastLogs(e,t){let n=e?.ids??[];if(n.length===0)return emptyQueryResult();let r=this.#i;if(!r?.isReady())return this.#a?.warning({message:`ClickHouse client not available, returning empty results`,category:`LogsSink`}),emptyQueryResult();try{this.#a?.info({message:`Querying last logs for ${n.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await r.queryWithPagination({endpoint:`project_last_logs.json`,params:{...t,entities:e}});return this.#a?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){return this.#a?.warning({message:`Failed to query for last logs, returning empty results`,category:`LogsSink`,error:e}),emptyQueryResult()}}async getActions(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} action logs (${r.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(r.data,G),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n,r){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n},r)).actionLogs[0]}async getSteps(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} step logs (${r.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(r.data,K),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r,i){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r},i)).stepLogs[0]}async getUnifiedLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} unified logs (${r.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(r.data,q),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n,r){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n},r)).unifiedLogs[0]}async getProviderLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} provider logs (${r.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(r.data,J),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`organization_platform_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} platform logs (${r.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(r.data,Y),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r,i){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r},i)).providerLogs[0]}async getAggregate(e,t,n,i){let a=this.#o(i);try{this.#a?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:n,engine:i}});let{dimensions:o,startTime:s,endTime:c,...l}=n,u=n.intervalType===P.None,d={organizationId:e,projectSecureId:t,...l,...o&&o.length>0&&{dimensions:o.join(`,`)},...s&&{startTime:s.toISOString()},...c&&{endTime:c.toISOString()},...u&&{pageSize:void 0,pageNumber:void 0}},f=await a?.query({endpoint:`project_logs_aggregation.json`,params:d});if(!f)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#a?.info({message:`Successfully retrieved ${f.length} aggregated data points`,category:`LogsSink`});let p=f.map(e=>r(e,!0)),m=[`success`,`isWorker`,`isBackground`,`skipped`],h=p.map(e=>{let t={...e};for(let e of m)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:u?foldTimeBuckets(h):h}}catch(e){return a?.isReady()?this.#a?.warning({message:`Failed to query for logs stats aggregate, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{data:[]}}}async getDimensions(e,t,n,r){let i=this.#o(r);try{this.#a?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n,engine:r}});let{dimensions:a,startTime:o,endTime:s,maxValues:c,...l}=n,u={organizationId:e,projectSecureId:t,...l,dimensions:a.join(`,`),...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...c&&{maxValuesPerDim:c}},d=await i?.query({endpoint:`project_logs_dimensions.json`,params:u});if(!d)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{};this.#a?.info({message:`Successfully retrieved ${d.length} dimension facets`,category:`LogsSink`});let f=[`success`,`isWorker`,`isBackground`,`skipped`],p={};for(let e of d)f.includes(e.dimension)?p[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):p[e.dimension]=e.values;return p}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats dimensions, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{}}}async getSourceUsage(e,t,n,r){let i=this.#o(r);try{this.#a?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n,engine:r}});let{startTime:a,endTime:o,sourceType:s}=n,c={organizationId:e,projectSecureId:t,...s&&{sourceType:Array.isArray(s)?s.join(`,`):s},...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await i?.query({endpoint:`project_source_usage.json`,params:c});return l?(this.#a?.info({message:`Successfully retrieved ${l.length} source usage records`,category:`LogsSink`}),l.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),[])}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),[]}}#l(e){return(this.#n??F)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#l(e);if(!n)throw this.#a?.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.#a?.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.#a?.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.#a?.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.#u(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#u(e,t,n,r){if(!t)throw this.#a?.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.#a?.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.#a?.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.#a?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.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},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,connectorVersion:`2`,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}buildPlatformLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`platform`,eventId:e.eventId??re(),eventType:e.eventType,service:e.service,organizationId:e.organizationId,...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.accountSecureId!==void 0&&{accountSecureId:e.accountSecureId},...e.userId!==void 0&&{userId:e.userId},...e.action!==void 0&&{action:e.action},...e.subAction!==void 0&&{subAction:e.subAction},...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},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeSerialize(e.details)},startTime:e.startTime??n,...t.endTime!==void 0&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},eventTime:n}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof S){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#a?.error({message:`Failed to validate ${n} log from Tinybird`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Tinybird data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,we)}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 S?this.#a?.warning({message:`Log validation failed before sending to Tinybird, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#a?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return G;case`step`:return K;case`unified`:return q;case`provider`:return J;case`platform`:return Y}}};const X={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`},defender:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...X.logs,...e?.logs},advanced:{...X.advanced,...e?.advanced},defender:{...X.defender,...e?.defender},datasets:{...X.datasets,...e?.datasets}}}const buildHttpClient=e=>{try{return new ie({logger:e})}catch(t){let n=t;e?.error({message:`Error building http client: ${n.message}`,error:n,code:`BuildHttpClientError`,category:`buildHttpClient`});return}},Z=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${Z}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${Z}${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`),Q=e(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=Q(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=Q(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})},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,reconstruct=async e=>{let a=Date.now();if(!(a-i<3e4)){i=a;try{let i=r;r=await t(),Promise.resolve().then(()=>i.close()).catch(()=>void 0),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`})}}},send=async e=>{try{return await r.send(e)}catch(e){throw await reconstruct(e),e}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;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}},buildInternalKafkaClient=async(e,t)=>{if(!e)return;let{bootstrapBrokers:n,region:r,clientId:i,...a}=e;return buildKafkaClient({bootstrapBrokers:n,clientId:i??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:r,logger:t})},...a},t)},buildS3Client=(e,t)=>{try{return new y(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var $=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getHttpClient:n=buildHttpClient,getS3Client:r=buildS3Client,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f}){this.name=`OlapClient`,this.#c=e,this.#l=a??i,this.#u=t,this.#d=o,this.#h=s,this.#f=l,this.#p=u,this.#m=d,this.#t=n(f),this.#n=r(c,f),this.#r=f}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getHttpClient:n=buildHttpClient,getS3Client:r=buildS3Client,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f}){let p=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f});return await p.initialize(),p}async initialize(){this.#e=await this.#c(this.#l,this.#r);let e=this.#d?{producer:await this.#u(this.#d,this.#r)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#i=new LogsSink(t,this.#t,this.#f,this.#r,this.#p,e,this.#h),this.#a=new AdvancedSink(this.#n,this.#m?.advanced,this.#r),this.#o=new DefenderSink(this.#n,this.#m?.defender,this.#r),this.#s=new DatasetsSink(this.#m?.datasets,this.#r),await this.#i?.initialize(),await this.#a?.initialize(),await this.#s?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:n,advanced:r,defender:i,datasets:a}=resolveOlapOptions(t);this.#r?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:n,advanced:r,defender:i,datasets:a}}});for(let t of e)s(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let o=a?.enabled&&this.#s?this.#s.sendActions(e,a).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[c,l]=await Promise.all([r?.enabled&&this.#a?this.#a.sendActions(e,r).catch(t=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),i?.enabled&&this.#o?this.#o.sendActions(e,i).catch(t=>(this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),u=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:c[t]?.expiresAt,defenderExpiresAt:l[t]?.expiresAt}})),d=n?.enabled&&this.#i?this.#i.sendActions(u,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([o,d])}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.#i&&i.push(this.#i.sendSteps(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&i.push(this.#a.sendSteps(e,r).then(()=>{}).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n);this.#r?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:n,resolvedOptions:{logs:r,advanced:i}}}),s(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let a={advancedExpiresAt:(i?.enabled&&this.#a?await this.#a.sendUnified(e,t,i).catch(e=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};r?.enabled&&this.#i&&await this.#i.sendUnified(e,t,a,r).catch(e=>{this.#r?.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.#i&&a.push(this.#i.sendProvider(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${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.#i?(r?this.#i.sendPlatform(e,a):this.#i.sendPlatform(e,t??{},a)).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#a?this.#a.sendPlatform(e,i,o).catch(e=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n,r){return this.#r?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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.#r?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#i?.getLastLogs(n,i)||(this.#r?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n,r){return this.#r?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getActions({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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,n,r){let i=await this.#i?.getAction(e,t,n,r);if(s(i)){this.#r?.debug({message:`Failed to retrieve action log for actionRunId ${n}`,category:`OlapClient`});return}return i}async getLog(e,t,n,r){this.#r?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n,engine:r}});let i=await this.getLogs(e,t,{logId:n,pageSize:1},r);if(!i||i.logs.length===0){this.#r?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let a=i.logs[0];if(a.logType===`action`||a.logType===`unified`)return a}async getStepLogs(e,t,n,r){return this.#r?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getSteps({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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,n,r,i){let a=await this.#i?.getStep(e,t,n,r,i);if(s(a)){this.#r?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return a}async getUnifiedLogs(e,t,n,r){return this.#r?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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,n,r){let i=await this.#i?.getUnifiedLog(e,t,n,r);if(s(i)){this.#r?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return i}async getProviderLogs(e,t,n,r){return this.#r?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getProviderLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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,n){let r={...t,organizationId:e};return this.#r?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:r,engine:n}}),await this.#i?.getPlatformLogs(r,n)||(this.#r?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getProviderLog(e,t,n,r,i){let a=await this.#i?.getProviderLog(e,t,n,r,i);if(s(a)){this.#r?.debug({message:`Failed to retrieve provider log for requestId ${n} id ${r}`,category:`OlapClient`});return}return a}async getActionAdvancedLog(e,t,n){let r=await this.#a?.getAction(e,t,n);if(s(r)){this.#r?.debug({message:`Failed to retrieve action advanced log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getStepAdvancedLog(e,t,n,r){let i=await this.#a?.getStep(e,t,n,r);if(s(i)){this.#r?.debug({message:`Failed to retrieve step advanced log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedAdvancedLog(e,t,n){let r=await this.#a?.getUnified(e,t,n);if(s(r)){this.#r?.debug({message:`Failed to retrieve unified advanced log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderAdvancedLog(e,t,n,r){let i=await this.#a?.getProvider(e,t,n,r);if(s(i)){this.#r?.debug({message:`Failed to retrieve provider advanced log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getPlatformAdvancedLog(e,t){let n=await this.#a?.getPlatform(e,t);if(s(n)){this.#r?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});return}return n}async getDefenderLog(e,t,n){let r=await this.#o?.getAction(e,t,n);if(s(r)){this.#r?.debug({message:`Failed to retrieve defender log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLogsStatsAggregate(e,t,n,r){return this.#r?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getAggregate(e,t,n,r)??{data:[]}}async getLogsStatsDimensions(e,t,n,r){return this.#r?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getDimensions(e,t,n,r)??{}}async getSourceUsage(e,t,n,r){return this.#r?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getSourceUsage(e,t,n,r)??[]}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getHttpClient:n=buildHttpClient,getS3Client:r=buildS3Client,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f})=>$.create({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f,getOlapClient:p=buildOlapClientInstance}){return this.olapClientPromise||=p({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};export{ge as AuthType,ClickHouseClient,F as DEFAULT_TOPIC_CLUSTER_MAP,de as Dimension,P as IntervalType,N as LogType,$ as OlapClient,OlapClientManager,le as OrderBy,ue as OrderDirection,z as SourceType,he as StreamType,me as TransportType,createConfigFromEnv,createOlapQueryClient,hasErrorEntries};
|
|
668
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_source_usage.json`,buildQuery:buildSourceUsageQuery});var SchemaValidationError$1=class extends Error{static{e(this,`SchemaValidationError`)}constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,e?.url&&(this.#e=t({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){try{let t=await this.#a(e.endpoint,e.params);return this.#i(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#a(e.endpoint,e.params),n=this.#i(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryRaw(e){try{let t=await this.#a(e.endpoint,e.params);return t.data=this.#i(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}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$1(t,e)}}async#a(e,t){let n=this.#r(),r=getQueryDefinition(e);if(!r)throw Error(`Unknown endpoint: ${e}. No query definition registered.`);let{sql:i,params:a}=r.buildQuery(t??{});this.#n?.debug({message:`Querying clickhouse endpoint: ${e}`,category:`ClickHouseClient`,context:{endpoint:e,params:t}});let o=Date.now(),s=await(await n.query({query:i,query_params:a,format:`JSONEachRow`})).json(),c=(Date.now()-o)/1e3,l;if(r.buildCountQuery){let{sql:e,params:i}=r.buildCountQuery(t??{});l=(await(await n.query({query:e,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${s.length} rows`,category:`ClickHouseClient`,context:{endpoint:e,rows:s.length,elapsed:c}}),{meta:[],data:s,rows:s.length,rows_before_limit_at_least:l,statistics:{elapsed:c,rows_read:s.length,bytes_read:0}}}},SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},TinybirdClient=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async query(e){try{let t=await this.#o(e.endpoint,e.params);return this.#a(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#o(e.endpoint,e.params),n=this.#a(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryRaw(e){try{let t=await this.#o(e.endpoint,e.params);return t.data=this.#a(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.token)}#r(){return new d.Agent({})}#i(){if(!this.#e)throw this.#n?.error({message:`HTTP client not initialized, cannot perform Tinybird query`,category:`TinybirdClient`,code:`HttpClientNotReady`}),Error(`HTTP client is not initialized`);if(!this.#t?.token)throw this.#n?.warning({message:`Missing OLAP token, cannot perform Tinybird query`,category:`TinybirdClient`}),Error(`TinybirdClient - Missing token`)}#a(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:`TinybirdClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`TinybirdClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#o(e,t){this.#i();let n=this.#e,r=this.#t;if(!n||!r)throw Error(`Client validation failed`);let i=new URL(`/v0/pipes/${e}`,r.baseUrl);this.#n?.debug({message:`Querying tinybird endpoint: ${e}`,category:`TinybirdClient`,context:{endpoint:e,params:t}});let a=await n.request({method:`post`,url:i.toString(),payload:t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r.token}`},...r.allowHttp&&{httpAgent:this.#r()}});return this.#n?.debug({message:`Tinybird query returned ${a.data.data.length} rows`,category:`TinybirdClient`,context:{endpoint:e,rows:a.data.rows,statistics:a.data.statistics}}),a.data}};function createOlapQueryClient(e,t,n){switch(e.type){case`clickhouse`:if(!e.clickhouse)throw Error(`ClickHouse config required when type is "clickhouse"`);return new ClickHouseClient(e.clickhouse,n);default:return new TinybirdClient(t,e.tinybird,n)}}function createConfigFromEnv(){let e=process.env.TINYBIRD_BASE_URL,t=process.env.TINYBIRD_TOKEN,n=e&&t?{baseUrl:e,token:t,allowHttp:process.env.TINYBIRD_ALLOW_HTTP===`true`}:void 0,r=process.env.CLICKHOUSE_URL,i=r?{url:r,username:process.env.CLICKHOUSE_USER,password:process.env.CLICKHOUSE_PASSWORD,database:process.env.CLICKHOUSE_DATABASE??`olap`,requestTimeout:(()=>{if(!process.env.CLICKHOUSE_TIMEOUT)return;let e=Number.parseInt(process.env.CLICKHOUSE_TIMEOUT,10);return Number.isFinite(e)?e:void 0})()}:void 0;return{type:n?`tinybird`:i?`clickhouse`:`tinybird`,tinybird:n,clickhouse:i}}const P={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`},F={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},I={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},L={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},R=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],he=[P.Scheduler,P.DataSync,P.DataSyncV2,P.Internal],ge=[`data_sync`],_e=[P.DataSync,P.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&R.includes(e)||t&&he.includes(t))}function isDataSync(e,t){return!!(e&&ge.includes(e)||t&&_e.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},hasErrorEntries=e=>s(e)?!1:Array.isArray(e)||l(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,z=64*1024,B=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],V=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>c(e)?e[t]:void 0,e),withPath=(e,t,n)=>{let[r,...i]=t.split(`.`);if(i.length===0)return{...e,[r]:n};let a=e[r];return c(a)?{...e,[r]:withPath(a,i.join(`.`),n)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,t)=>{let{kept:r,total:i}=e.reduce((e,r)=>{if(e.total>t)return e;let i=e.total+n(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+n(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=n(e);return r<=t?e:(l(e)||Array.isArray(e)||c(e)&&!o(e))&&t<=0?marker(r):l(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):c(e)&&!o(e)?fitObject(e,t):e},payloadFields=e=>B.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!s(e)).map(e=>({...e,size:n(e.value)})),byRetentionPriority=e=>[...e.filter(e=>V.includes(e.path)),...e.filter(e=>!V.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*z;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(z,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=>B.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),ve=[`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`],ye=[`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`],be=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`;var AdvancedSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n}async initialize(){if(!this.#e){this.#i?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}}requireBucket(){if(!this.#t)throw Error(`Advanced sink bucket is not configured`);return this.#t}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(r.mode,r.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&i.success&&!i.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${r.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`AdvancedSink`}),n.push(null);continue}let e=this.createActionS3(r,i,t),a=await this.send(e,t?.ttl);n.push(a)}return n}async sendStep(e,t,n){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0&&t.success!==!1&&!hasErrorEntries(t.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let r=this.createStepS3(e,t,n);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r=this.createUnifiedS3(e,t,n);try{return await this.send(r,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=this.createProviderS3(e,t,n);try{return await this.send(r,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){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new g({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new g({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new g({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new g({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e)throw Error(`No s3 client available, cannot send to advanced sink`);let n=this.requireBucket(),r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);this.#i?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:a.toISOString()}});try{return await this.#e.send(new v({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:a,Tagging:r})),{expiresAt:a}}catch(t){throw this.#i?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}async getObjectExpiry(e){if(!this.#e)return this.#i?.warning({message:`No s3 client available, cannot check object expiry`,category:`AdvancedSink`}),{exists:!1};let t=this.requireBucket();try{return{exists:!0,expiresAt:(await this.#e.send(new _({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#i?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#i?.error({message:`Error when checking object expiry in S3 for key ${e}`,error:t,code:`AdvancedLogHeadError`,category:`AdvancedSink`}),t}}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;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformS3(e,t,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){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get platform log from advanced sink`,category:`AdvancedSink`});return}let n=this.requireBucket();try{let r=new g({Bucket:n,Key:platformKey(e,t)}),i=await this.#e.send(r);if(!i.Body){this.#i?.warning({message:`Received empty body when trying to get platform log from S3 for eventId ${t}`,category:`AdvancedSink`});return}let a=await i.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved platform advanced log from S3 for eventId ${t}`,category:`AdvancedSink`}),JSON.parse(a)}catch(e){let n=e;if(n.name===`NoSuchKey`||n.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Platform advanced log not found in S3 for eventId ${t}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting platform advanced log from S3 for eventId ${t}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionS3(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)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(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)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createPlatformS3(e,t,n){let r=platformKey(e.organizationId,e.eventId),i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,ContentType:`application/json`,Expires:new Date(i*1e3),Body:this.serializePlatformAdvanced(t,i)}}serializePlatformAdvanced(e,t){let r=p(e.data,f.PARTIAL,!0),i={...e.metadata,expirationTime:t,sizeBytes:n(r)};return this.stringifyPlatform({data:r,metadata:i},i)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedS3(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)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(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)),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r,i){let a=m({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},f.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=p(e.body,f.PARTIAL,!0),l=p(t.body,f.PARTIAL,!0),u=this.processContent(o,c,`upload`),d=this.processContent(s,l,`download`),g=e.isBackground??isBackgroundLog(e.mode,e.sourceType),_=e.url,v={};if(e.url)try{_=h(e.url,f.PARTIAL);let t=new URL(_);v=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let y={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:_,path:e.pathParams,queryParams:v},body:u},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:d},...g?{isBackgroundLog:!0}:{}},metadata:{...g?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(y,r,isErrorResult(t),i)}serializeStepResult(e,t,n,r,i){let a={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,t,n,r,i){let a=m({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},f.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=p(e.body,f.PARTIAL,!0),l=p(t.body,f.PARTIAL,!0),u=this.processContent(o,c,`upload`),d=this.processContent(s,l,`download`),g=e.isBackground??isBackgroundLog(e.mode,e.sourceType),_=`/`,v=e.url,y={};if(e.url)try{v=h(e.url,f.PARTIAL);let t=new URL(v);_=t.pathname,y=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let b={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:v,path:_,queryParams:y},body:u},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:d}},metadata:{...g?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(b,r,isErrorResult(t),i)}serializeProviderResult(e,t,n,r,i){let a=m({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},f.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=p(e.body,f.PARTIAL,!0),l=p(t.body,f.PARTIAL,!0),u=this.processContent(o,c,`upload`),d=this.processContent(s,l,`download`),g,_=``,v=`/`,y={};if(e.url)try{g=h(e.url,f.PARTIAL);let t=new URL(g);_=t.hostname,v=t.pathname,y=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let b={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:g,hostname:_,path:v,queryParams:y},body:u},response:{statusCode:t.statusCode,headers:this.filterHeaders(s),body:d}},metadata:{expirationTime:n}};return this.serializeAndLimit(b,r,isErrorResult(t),i)}serializeAndLimit(e,t,r,i){let a=n(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=ve.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 ye.includes(i)||be.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!s(e)){if(!l(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};function defaultProviderFactory(e){let t=new b({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[re]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new te({resource:ee(n),spanProcessors:[new ne(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(this.#r)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let n=0;for(let{input:r,result:a}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:a.success,statusCode:a.statusCode,includeBackground:t.includeBackground}}),s(r.body)&&s(a.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(r,a);if(s(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(i(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}this.send(r,e),n++}n>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${n} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let n=s(e.body)?void 0:a(e.body),r=s(t.body)?void 0:a(t.body);if(!(s(n)&&s(r)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:n,result:r}}}},DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Defender sink bucket is not configured`);return this.#t}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`}),n.push(null);continue}if(s(i.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:r.actionRunId}}),n.push(null);continue}let e=this.createDefenderS3(r,i),a=await this.send(e);n.push(a)}return n}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=this.requireBucket();try{let i=new g({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#r?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to defender sink`);let t=this.requireBucket(),n=Math.floor(Date.now()/1e3)+this.#n*24*60*60,r=new Date(n*1e3),i=`ttl=${this.#n}d`;this.#r?.debug({message:`Storing defender log in S3 bucket ${t} with ${this.#n}-day TTL`,category:`DefenderSink`,context:{bucket:t,key:e.Key,ttlTag:i,expiresAt:r.toISOString()}});try{return await this.#e.send(new v({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:r,Tagging:i})),{expiresAt:r}}catch(t){throw this.#r?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createDefenderS3(e,t){let n=e.organizationId,r=e.projectSecureId;return{Key:this.generateS3Key(n,r,e.actionRunId),Body:JSON.stringify(t.defenderContext),ContentType:`application/json`}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},H=C.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 C.ZodError([{code:C.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},C.coerce.date()),U=C.object({logType:C.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:H,startTime:H,endTime:H.optional().nullable().transform(e=>e??void 0),durationMs:C.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:C.coerce.string(),projectSecureId:C.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:C.coerce.string().optional().nullable().transform(e=>e??void 0)}),W=U.extend({logType:C.literal(`action`),actionRunId:C.coerce.string(),actionId:C.coerce.string(),connectorKey:C.coerce.string(),connectorVersion:C.coerce.string(),connectorOwner:C.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:C.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:C.coerce.string(),accountSecureId:C.coerce.string(),actionType:C.coerce.string().optional().nullable().transform(e=>e??void 0),mode:C.coerce.string().optional().nullable().transform(e=>e??void 0),category:C.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:C.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:C.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:C.coerce.string().optional().nullable().transform(e=>e??void 0),url:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:C.coerce.string().optional().nullable().transform(e=>e??void 0),authType:C.coerce.string().optional().nullable().transform(e=>e??void 0),authId:C.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:C.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:C.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:C.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:C.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:C.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:C.coerce.string().optional().nullable().transform(e=>e??void 0),success:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:C.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:C.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:C.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:C.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:C.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:C.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:C.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:C.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:C.coerce.number().optional().nullable().transform(e=>e??void 0),isBackground:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:H.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:H.optional().nullable().transform(e=>e??void 0)}),G=U.extend({logType:C.literal(`step`),actionRunId:C.coerce.string(),stepIndex:C.coerce.number(),stepId:C.coerce.string(),projectSecureId:C.coerce.string(),accountSecureId:C.coerce.string(),skipped:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:C.coerce.number().optional().nullable().transform(e=>e??void 0),message:C.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:C.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:C.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:C.coerce.number().optional().nullable().transform(e=>e??void 0)}),K=U.extend({logType:C.literal(`unified`),requestId:C.coerce.string(),connectorKey:C.coerce.string(),connectorVersion:C.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:C.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:C.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:C.coerce.string(),accountSecureId:C.coerce.string(),mode:C.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:C.coerce.string().optional().nullable().transform(e=>e??void 0),url:C.coerce.string().optional().nullable().transform(e=>e??void 0),path:C.coerce.string().optional().nullable().transform(e=>e??void 0),resource:C.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:C.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:C.coerce.string().optional().nullable().transform(e=>e??void 0),service:C.coerce.string().optional().nullable().transform(e=>e??void 0),action:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:C.coerce.string().optional().nullable().transform(e=>e??void 0),authType:C.coerce.string().optional().nullable().transform(e=>e??void 0),authId:C.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:C.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:C.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:C.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:C.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:C.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:C.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:C.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:C.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:C.coerce.number().optional().nullable().transform(e=>e??void 0),success:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:C.coerce.number().optional().nullable().transform(e=>e??void 0),provider:C.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:C.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:H.optional().nullable().transform(e=>e??void 0)}),q=U.extend({logType:C.literal(`provider`),requestId:C.coerce.string(),id:C.coerce.string().optional().nullable().transform(e=>e??void 0),action:C.coerce.string(),mode:C.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:C.coerce.string(),originOwnerId:C.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:C.coerce.string().optional().nullable().transform(e=>e??void 0),url:C.coerce.string(),path:C.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:C.coerce.string(),connectorVersion:C.coerce.string().optional().nullable().transform(e=>e??void 0),resource:C.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:C.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:C.coerce.string().optional().nullable().transform(e=>e??void 0),service:C.coerce.string().optional().nullable().transform(e=>e??void 0),success:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:C.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:C.coerce.string(),accountSecureId:C.coerce.string(),status:C.coerce.number().optional().nullable().transform(e=>e??void 0),provider:C.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:C.coerce.number().optional().nullable().transform(e=>e??void 0)}),J=U.extend({logType:C.literal(`platform`),eventId:C.coerce.string(),eventType:C.coerce.string(),service:C.coerce.string(),userId:C.coerce.string().optional().nullable().transform(e=>e??void 0),action:C.coerce.string().optional().nullable().transform(e=>e??void 0),subAction:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:C.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:C.coerce.string().optional().nullable().transform(e=>e??void 0),authType:C.coerce.string().optional().nullable().transform(e=>e??void 0),authId:C.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:C.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:C.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:C.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:C.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:C.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:C.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:C.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:C.coerce.string().optional().nullable().transform(e=>e??void 0)}),xe=C.discriminatedUnion(`logType`,[W,G,K,q]),foldTimeBuckets=e=>{let t=new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},Y=[`success`,`isWorker`,`isBackground`,`skipped`];var LogsSink=class{#e;#t;#n;#r;#i;#a;#o(e){if(e===`clickhouse`&&this.#i?.isReady())return this.#i;if(this.#r?.isReady())return this.#r;if(this.#i?.isReady())return this.#i}#s(){if(this.#i?.isReady())return this.#i;this.#a?.warning({message:`Platform logs were requested but the ClickHouse client is not available`,category:`LogsSink`})}constructor(e,t,n,r,i,a,o){this.#e=e,this.#t=a,this.#n=o,this.#a=r,n&&(this.#r=new TinybirdClient(t,n,r)),i&&(this.#i=new ClickHouseClient(i,r));let s=[];this.#r&&s.push(`tinybird`),this.#i&&s.push(`clickhouse`),s.length>0&&this.#a?.debug({message:`LogsSink initialized with query clients: ${s.join(`, `)}`,category:`LogsSink`})}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#a?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}let e=this.#r?.isReady()??!1,t=this.#i?.isReady()??!1;!e&&!t?this.#a?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}):this.#a?.info({message:`Logs sink query clients ready: tinybird=${e}, clickhouse=${t}`,category:`LogsSink`}),this.#a?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#c()}async#c(){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})=>{try{await t?.connectToBrokers(),this.#a?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#a?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#a?.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.#a?.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.#a?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#a?.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.#a?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#a?.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.#a?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#a?.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,t){let n=this.#o(t);try{this.#a?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} logs (${r.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(r.data),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getLastLogs(e,t){let n=e?.ids??[];if(n.length===0)return emptyQueryResult();let r=this.#i;if(!r?.isReady())return this.#a?.warning({message:`ClickHouse client not available, returning empty results`,category:`LogsSink`}),emptyQueryResult();try{this.#a?.info({message:`Querying last logs for ${n.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await r.queryWithPagination({endpoint:`project_last_logs.json`,params:{...t,entities:e}});return this.#a?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){return this.#a?.warning({message:`Failed to query for last logs, returning empty results`,category:`LogsSink`,error:e}),emptyQueryResult()}}async getActions(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} action logs (${r.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(r.data,W),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n,r){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n},r)).actionLogs[0]}async getSteps(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} step logs (${r.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(r.data,G),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r,i){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r},i)).stepLogs[0]}async getUnifiedLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} unified logs (${r.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(r.data,K),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n,r){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n},r)).unifiedLogs[0]}async getProviderLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} provider logs (${r.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(r.data,q),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogs(e){let t=this.#s();try{this.#a?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`organization_platform_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#a?.info({message:`Successfully retrieved ${n.data.length} platform logs (${n.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(n.data,J),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}catch(n){return t?.isReady()?this.#a?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:n}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r,i){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r},i)).providerLogs[0]}async getAggregate(e,t,n,i){let a=this.#o(i);try{this.#a?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:n,engine:i}});let{dimensions:o,startTime:s,endTime:c,...l}=n,u=n.intervalType===O.None,d={organizationId:e,projectSecureId:t,...l,...o&&o.length>0&&{dimensions:o.join(`,`)},...s&&{startTime:s.toISOString()},...c&&{endTime:c.toISOString()},...u&&{pageSize:void 0,pageNumber:void 0}},f=await a?.query({endpoint:`project_logs_aggregation.json`,params:d});if(!f)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#a?.info({message:`Successfully retrieved ${f.length} aggregated data points`,category:`LogsSink`});let p=f.map(e=>r(e,!0)).map(e=>{let t={...e};for(let e of Y)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:u?foldTimeBuckets(p):p}}catch(e){return a?.isReady()?this.#a?.warning({message:`Failed to query for logs stats aggregate, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{data:[]}}}async getDimensions(e,t,n,r){let i=this.#o(r);try{this.#a?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n,engine:r}});let{dimensions:a,startTime:o,endTime:s,maxValues:c,...l}=n,u={organizationId:e,projectSecureId:t,...l,dimensions:a.join(`,`),...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...c&&{maxValuesPerDim:c}},d=await i?.query({endpoint:`project_logs_dimensions.json`,params:u});if(!d)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{};this.#a?.info({message:`Successfully retrieved ${d.length} dimension facets`,category:`LogsSink`});let f={};for(let e of d)Y.includes(e.dimension)?f[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):f[e.dimension]=e.values;return f}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats dimensions, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{}}}async getSourceUsage(e,t,n,r){let i=this.#o(r);try{this.#a?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n,engine:r}});let{startTime:a,endTime:o,sourceType:s}=n,c={organizationId:e,projectSecureId:t,...s&&{sourceType:Array.isArray(s)?s.join(`,`):s},...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await i?.query({endpoint:`project_source_usage.json`,params:c});return l?(this.#a?.info({message:`Successfully retrieved ${l.length} source usage records`,category:`LogsSink`}),l.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),[])}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),[]}}#l(e){return(this.#n??k)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#l(e);if(!n)throw this.#a?.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.#a?.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.#a?.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.#a?.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.#u(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#u(e,t,n,r){if(!t)throw this.#a?.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.#a?.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.#a?.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.#a?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.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},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,connectorVersion:`2`,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}buildPlatformLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`platform`,eventId:e.eventId??x(),eventType:e.eventType,service:e.service,organizationId:e.organizationId,...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.accountSecureId!==void 0&&{accountSecureId:e.accountSecureId},...e.userId!==void 0&&{userId:e.userId},...e.action!==void 0&&{action:e.action},...e.subAction!==void 0&&{subAction:e.subAction},...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},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeSerialize(e.details)},startTime:e.startTime??n,...t.endTime!==void 0&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},eventTime:n}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof S){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#a?.error({message:`Failed to validate ${n} log from the query engine`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Log data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,xe)}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 S?this.#a?.warning({message:`Log validation failed before sending to Tinybird, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#a?.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 W;case`step`:return G;case`unified`:return K;case`provider`:return q;case`platform`:return J}}};const X={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`},defender:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...X.logs,...e?.logs},advanced:{...X.advanced,...e?.advanced},defender:{...X.defender,...e?.defender},datasets:{...X.datasets,...e?.datasets}}}const buildHttpClient=e=>{try{return new ie({logger:e})}catch(t){let n=t;e?.error({message:`Error building http client: ${n.message}`,error:n,code:`BuildHttpClientError`,category:`buildHttpClient`});return}},Z=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${Z}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${Z}${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`),Q=e(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=Q(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=Q(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})},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,reconstruct=async e=>{let a=Date.now();if(!(a-i<3e4)){i=a;try{let i=r;r=await t(),Promise.resolve().then(()=>i.close()).catch(()=>void 0),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`})}}},send=async e=>{try{return await r.send(e)}catch(e){throw await reconstruct(e),e}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;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}},buildInternalKafkaClient=async(e,t)=>{if(!e)return;let{bootstrapBrokers:n,region:r,clientId:i,...a}=e;return buildKafkaClient({bootstrapBrokers:n,clientId:i??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:r,logger:t})},...a},t)},buildS3Client=(e,t)=>{try{return new y(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var $=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getHttpClient:n=buildHttpClient,getS3Client:r=buildS3Client,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f}){this.name=`OlapClient`,this.#c=e,this.#l=a??i,this.#u=t,this.#d=o,this.#h=s,this.#f=l,this.#p=u,this.#m=d,this.#t=n(f),this.#n=r(c,f),this.#r=f}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getHttpClient:n=buildHttpClient,getS3Client:r=buildS3Client,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f}){let p=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f});return await p.initialize(),p}async initialize(){this.#e=await this.#c(this.#l,this.#r);let e=this.#d?{producer:await this.#u(this.#d,this.#r)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#i=new LogsSink(t,this.#t,this.#f,this.#r,this.#p,e,this.#h),this.#a=new AdvancedSink(this.#n,this.#m?.advanced,this.#r),this.#o=new DefenderSink(this.#n,this.#m?.defender,this.#r),this.#s=new DatasetsSink(this.#m?.datasets,this.#r),await this.#i?.initialize(),await this.#a?.initialize(),await this.#s?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:n,advanced:r,defender:i,datasets:a}=resolveOlapOptions(t);this.#r?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:n,advanced:r,defender:i,datasets:a}}});for(let t of e)s(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let o=a?.enabled&&this.#s?this.#s.sendActions(e,a).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[c,l]=await Promise.all([r?.enabled&&this.#a?this.#a.sendActions(e,r).catch(t=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),i?.enabled&&this.#o?this.#o.sendActions(e,i).catch(t=>(this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),u=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:c[t]?.expiresAt,defenderExpiresAt:l[t]?.expiresAt}})),d=n?.enabled&&this.#i?this.#i.sendActions(u,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([o,d])}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.#i&&i.push(this.#i.sendSteps(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&i.push(this.#a.sendSteps(e,r).then(()=>{}).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n);this.#r?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:n,resolvedOptions:{logs:r,advanced:i}}}),s(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let a={advancedExpiresAt:(i?.enabled&&this.#a?await this.#a.sendUnified(e,t,i).catch(e=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};r?.enabled&&this.#i&&await this.#i.sendUnified(e,t,a,r).catch(e=>{this.#r?.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.#i&&a.push(this.#i.sendProvider(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${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.#i?(r?this.#i.sendPlatform(e,a):this.#i.sendPlatform(e,t??{},a)).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#a?this.#a.sendPlatform(e,i,o).catch(e=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n,r){return this.#r?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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.#r?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#i?.getLastLogs(n,i)||(this.#r?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n,r){return this.#r?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getActions({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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,n,r){let i=await this.#i?.getAction(e,t,n,r);if(s(i)){this.#r?.debug({message:`Failed to retrieve action log for actionRunId ${n}`,category:`OlapClient`});return}return i}async getLog(e,t,n,r){this.#r?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n,engine:r}});let i=await this.getLogs(e,t,{logId:n,pageSize:1},r);if(!i||i.logs.length===0){this.#r?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let a=i.logs[0];if(a.logType===`action`||a.logType===`unified`)return a}async getStepLogs(e,t,n,r){return this.#r?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getSteps({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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,n,r,i){let a=await this.#i?.getStep(e,t,n,r,i);if(s(a)){this.#r?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return a}async getUnifiedLogs(e,t,n,r){return this.#r?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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,n,r){let i=await this.#i?.getUnifiedLog(e,t,n,r);if(s(i)){this.#r?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return i}async getProviderLogs(e,t,n,r){return this.#r?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getProviderLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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.#r?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getPlatformLogs(n)||(this.#r?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getProviderLog(e,t,n,r,i){let a=await this.#i?.getProviderLog(e,t,n,r,i);if(s(a)){this.#r?.debug({message:`Failed to retrieve provider log for requestId ${n} id ${r}`,category:`OlapClient`});return}return a}async getActionAdvancedLog(e,t,n){let r=await this.#a?.getAction(e,t,n);if(s(r)){this.#r?.debug({message:`Failed to retrieve action advanced log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getStepAdvancedLog(e,t,n,r){let i=await this.#a?.getStep(e,t,n,r);if(s(i)){this.#r?.debug({message:`Failed to retrieve step advanced log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedAdvancedLog(e,t,n){let r=await this.#a?.getUnified(e,t,n);if(s(r)){this.#r?.debug({message:`Failed to retrieve unified advanced log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderAdvancedLog(e,t,n,r){let i=await this.#a?.getProvider(e,t,n,r);if(s(i)){this.#r?.debug({message:`Failed to retrieve provider advanced log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getPlatformAdvancedLog(e,t){let n=await this.#a?.getPlatform(e,t);if(s(n)){this.#r?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});return}return n}async getDefenderLog(e,t,n){let r=await this.#o?.getAction(e,t,n);if(s(r)){this.#r?.debug({message:`Failed to retrieve defender log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLogsStatsAggregate(e,t,n,r){return this.#r?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getAggregate(e,t,n,r)??{data:[]}}async getLogsStatsDimensions(e,t,n,r){return this.#r?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getDimensions(e,t,n,r)??{}}async getSourceUsage(e,t,n,r){return this.#r?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getSourceUsage(e,t,n,r)??[]}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getHttpClient:n=buildHttpClient,getS3Client:r=buildS3Client,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f})=>$.create({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f,getOlapClient:p=buildOlapClientInstance}){return this.olapClientPromise||=p({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};export{L as AuthType,ClickHouseClient,k as DEFAULT_TOPIC_CLUSTER_MAP,pe as Dimension,O as IntervalType,D as LogType,$ as OlapClient,OlapClientManager,de as OrderBy,fe as OrderDirection,P as SourceType,I as StreamType,F as TransportType,createConfigFromEnv,createOlapQueryClient,hasErrorEntries};
|