@walkeros/server-source-aws 4.1.2 → 4.1.3-next-1780071196115

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/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @walkeros/server-source-aws
2
2
 
3
+ ## 4.1.3-next-1780071196115
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [908d6f0]
8
+ - Updated dependencies [3eb2467]
9
+ - @walkeros/core@4.1.3-next-1780071196115
10
+
3
11
  ## 4.1.2
4
12
 
5
13
  ### Patch Changes
package/dist/dev.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,r=(e,n)=>{for(var o in n)t(e,o,{get:n[o],enumerable:!0})},i={};r(i,{examples:()=>I,schemas:()=>a,sqsExamples:()=>He}),module.exports=(e=i,((e,r,i,a)=>{if(r&&"object"==typeof r||"function"==typeof r)for(let c of o(r))s.call(e,c)||c===i||t(e,c,{get:()=>r[c],enumerable:!(a=n(r,c))||a.enumerable});return e})(t({},"__esModule",{value:!0}),e));var a={};r(a,{CorsOptionsSchema:()=>f,CorsOrigin:()=>p,HttpMethod:()=>l,SettingsSchema:()=>g,settings:()=>h,sqsSettings:()=>S,sqsSetup:()=>q});var c=require("@walkeros/core/dev"),u=require("@walkeros/core/dev"),d=require("@walkeros/core/dev"),l=d.z.enum(["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"]),p=d.z.union([d.z.string(),d.z.array(d.z.string()),d.z.literal("*")]),f=d.z.object({origin:p.describe("Allowed origins (* for all, URL string, or array of URLs)").optional(),methods:d.z.array(l).describe("Allowed HTTP methods").optional(),headers:d.z.array(d.z.string()).describe("Allowed request headers").optional(),credentials:d.z.boolean().describe("Allow credentials (cookies, authorization headers)").optional(),maxAge:d.z.number().int().positive().describe("Preflight cache duration in seconds").optional()}),g=u.z.object({cors:u.z.union([u.z.boolean(),f]).describe("CORS configuration: false = disabled, true = allow all origins, object = custom configuration").default(!0),timeout:u.z.number().int().positive().max(9e5).describe("Request timeout in milliseconds (max: 900000 for Lambda)").default(3e4),enablePixelTracking:u.z.boolean().describe("Enable GET requests with 1x1 transparent GIF response for pixel tracking").default(!0),healthPath:u.z.string().describe("Health check endpoint path (e.g., /health)").default("/health")}),h=(0,c.zodToSchema)(g),m=require("@walkeros/core/dev"),y=require("@walkeros/core/dev"),w=y.z.object({queueName:y.z.string().min(1).describe("SQS queue short name (like walkeros-events). Required for both setup and runtime poll."),region:y.z.string().describe("AWS region (like eu-central-1). Default: eu-central-1.").optional(),queueUrl:y.z.string().url().describe("Optional pre-resolved queue URL. When set, init skips the GetQueueUrl lookup.").optional(),client:y.z.any().describe("Pre-configured AWS SQSClient instance. Bypasses construction when supplied.").optional(),config:y.z.any().describe("AWS SDK SQSClientConfig (credentials, endpoint overrides, retries).").optional(),decoder:y.z.enum(["json","text","raw"]).describe("Decoder for the message body. json (default) parses JSON, text forwards UTF-8, raw forwards a Buffer.").optional(),maxMessages:y.z.number().int().min(1).max(10).describe("SQS receive batch size. Cap 10. Default: 10.").optional(),waitTimeSeconds:y.z.number().int().min(0).max(20).describe("Long-poll duration in seconds. Cap 20. Default: 20.").optional(),visibilityTimeout:y.z.number().int().nonnegative().describe("Per-receive visibility timeout override. Default: queue-configured value.").optional(),shutdownTimeoutMs:y.z.number().int().positive().describe("Graceful shutdown timeout in milliseconds. Default: 30000. After this window, destroy() force-closes.").optional(),onPushError:y.z.enum(["nack","ack"]).describe("Behavior when forwarding to the collector throws. nack (default) skips DeleteMessage so the message redelivers; ack drops it.").optional()}),b=require("@walkeros/core/dev"),v=b.z.record(b.z.string(),b.z.string()),k=b.z.object({region:b.z.string().min(1).describe("AWS region.").optional(),fifoQueue:b.z.boolean().describe("FIFO queue with content-based deduplication. Auto-appends .fifo suffix to the queue name.").optional(),visibilityTimeoutSeconds:b.z.number().int().nonnegative().describe("Visibility timeout in seconds. Default: 30.").optional(),messageRetentionSeconds:b.z.number().int().positive().describe("Message retention period in seconds. Default: 345600 (4 days).").optional(),maximumMessageSize:b.z.number().int().min(1024).max(262144).describe("Max message size in bytes. Default: 262144 (256 KB).").optional(),kmsMasterKeyId:b.z.string().describe("KMS key alias or ID for at-rest encryption.").optional(),deadLetterQueue:b.z.object({arn:b.z.string().describe("ARN of an existing DLQ. Mutually exclusive with create: true.").optional(),create:b.z.boolean().describe("Create a sibling DLQ named <queueName>-dlq. Default: false.").optional(),maxReceiveCount:b.z.number().int().min(1).max(1e3).describe("Max receive count before message goes to DLQ. Default: 5.").optional()}).describe("Optional dead-letter queue.").optional(),tags:v.describe("Tags applied to the queue (and inherited by an auto-created DLQ).").optional(),subscribeToSnsTopic:b.z.object({topicArn:b.z.string().min(1).describe("Topic ARN to subscribe to."),rawMessageDelivery:b.z.boolean().describe("Deliver SNS messages without the SNS envelope.").optional(),filterPolicy:b.z.record(b.z.string(),b.z.unknown()).describe("SNS filter policy applied at subscription level.").optional()}).describe("Optional SNS topic subscription. Creates the subscription and the matching queue policy.").optional()}),S=(0,m.zodToSchema)(w),q=(0,m.zodToSchema)(k),I={};r(I,{createTrigger:()=>$e,env:()=>O,step:()=>D,trigger:()=>_e});var O={};r(O,{push:()=>j});var x=()=>()=>Promise.resolve({ok:!0}),C=()=>{},A={error:C,warn:C,info:C,debug:C,throw:e=>{throw"string"==typeof e?new Error(e):e},json:C,scope:()=>A},j={get push(){return x()},get command(){return x()},get elb(){return x()},logger:A},D={};r(D,{apiGatewayV1Post:()=>z,lambdaGet:()=>E,lambdaPost:()=>T});var T={title:"Lambda POST",description:"An API Gateway v2 HTTP POST with a JSON body is converted into a walker elb event.",trigger:{type:"POST"},in:{version:"2.0",requestContext:{http:{method:"POST",path:"/collect"},requestId:"req-123"},body:JSON.stringify({event:"page view",data:{title:"Home"}}),isBase64Encoded:!1},out:[["elb",{name:"page view",data:{title:"Home"}}]]},z={title:"API Gateway v1 POST",description:"A REST API Gateway v1 POST request with a JSON body is converted into a walker elb event.",trigger:{type:"POST"},in:{httpMethod:"POST",path:"/collect",requestContext:{requestId:"req-789",identity:{sourceIp:"203.0.113.42"}},queryStringParameters:null,body:JSON.stringify({event:"page view",data:{title:"Home"}}),isBase64Encoded:!1},out:[["elb",{name:"page view",data:{title:"Home"}}]]},E={title:"Lambda GET",description:"An API Gateway v2 HTTP GET with query parameters is parsed into an elb event payload.",trigger:{type:"GET"},in:{version:"2.0",requestContext:{http:{method:"GET",path:"/collect"},requestId:"req-456"},rawQueryString:"e=page+view&d=%7B%22title%22%3A%22Home%22%7D",isBase64Encoded:!1},out:[["elb",{e:"page view",d:'{"title":"Home"}'}]]},M=require("@walkeros/core"),P=require("@walkeros/core"),$=require("@walkeros/core"),_=(require("@walkeros/core"),require("@walkeros/core")),H=require("@walkeros/core"),N=require("@walkeros/core"),R=require("@walkeros/core"),B=require("@walkeros/core"),G=require("@walkeros/core"),F=require("@walkeros/core"),L=require("@walkeros/core"),K=require("@walkeros/core"),Q=require("@walkeros/core"),J={Action:"action",Actions:"actions",Config:"config",Consent:"consent",Context:"context",Custom:"custom",Destination:"destination",Elb:"elb",Globals:"globals",Hook:"hook",Init:"init",Link:"link",On:"on",Prefix:"data-elb",Ready:"ready",Run:"run",Session:"session",Shutdown:"shutdown",User:"user",Walker:"walker"};function U(e,t){const n=e.status.startedAt;return{flowId:"default",stepId:t.stepId,stepType:t.stepType,phase:t.phase,eventId:t.eventId,timestamp:new Date(t.now).toISOString(),elapsedMs:t.now-n}}function W(e,t){return e.storeId&&t.stores[e.storeId]?t.stores[e.storeId]:t.stores.__cache}function V(e){const t={};for(const[n,o]of Object.entries(e)){const e=o.config?.next;"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e)?t[n]={next:e}:t[n]={}}return t}function Y(e,t){const n=e.config||{},o=e[t];return void 0!==o?{config:{...n,[t]:o},chainValue:o}:{config:n,chainValue:void 0}}function X(e,t={}){if(!e)return[];if(Array.isArray(e))return e;const n=[],o=new Set;let s=e;for(;s&&t[s]&&!o.has(s);){o.add(s),n.push(s);const e=t[s].next;if(Array.isArray(e)){n.push(...e);break}s=e}return n}async function Z(e,t,n){if(t.init&&!t.config.init){const o=t.type||"unknown",s=e.logger.scope(`transformer:${o}`),r={collector:e,logger:s,id:n,ingest:(0,R.createIngest)(n),config:t.config,env:oe(t.config.env)};s.debug("init");const i=await(0,R.useHooks)(t.init,"TransformerInit",e.hooks,e.logger)(r);if(!1===i)return!1;t.config={...i||t.config,env:i?.env||t.config.env,init:!0},s.debug("init done")}return!0}async function ee(e,t,n,o,s,r){const i=t.type||"unknown",a=e.logger.scope(`transformer:${i}`),c={collector:e,logger:a,id:n,ingest:s,config:t.config,env:{...oe(t.config.env),...r?{respond:r}:{}}};a.debug("push",{event:o.name});const u="string"==typeof o.id?o.id:"",d=Date.now(),l=U(e,{stepId:(0,R.stepId)("transformer",n),stepType:"transformer",phase:"in",eventId:u,now:d});(0,R.emitStep)(e,l);try{const s=await(0,R.useHooks)(t.push,"TransformerPush",e.hooks,e.logger)(o,c),r=Date.now(),i=U(e,{stepId:(0,R.stepId)("transformer",n),stepType:"transformer",phase:"out",eventId:u,now:r});return i.durationMs=r-d,i.outEvent=s,(0,R.emitStep)(e,i),a.debug("push done"),s}catch(t){const o=Date.now(),s=U(e,{stepId:(0,R.stepId)("transformer",n),stepType:"transformer",phase:"error",eventId:u,now:o});throw s.durationMs=o-d,s.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},(0,R.emitStep)(e,s),t}}function te(e,t){return e?{...e,_meta:{...e._meta,path:[...e._meta.path]}}:(0,R.createIngest)(t)}async function ne(e,t,n,o,s,r,i){s||(s=(0,R.createIngest)(n[0]??"chain")),i&&s._meta&&(s._meta.chainPath=i);let a=o,c=r;for(const o of n){const r=t[o];if(!r){e.logger.warn(`Transformer not found: ${o}`);continue}if(s&&s._meta&&s._meta.path.length>256)return e.logger.error(`Max path length exceeded at ${o}`),{event:null,respond:c};if(s&&s._meta&&(s._meta.hops++,s._meta.path.push(o)),!await(0,R.tryCatchAsync)(Z,t=>{if(t instanceof R.FatalError)throw t;return e.status.failed++,e.logger.scope(`transformer:${r.type||"unknown"}`).error("transformer init failed",{transformer:o,error:t}),!1})(e,r,o))return{event:null,respond:c};if(i&&void 0!==r.config?.chainMocks?.[i]){const t=r.config.chainMocks[i];e.logger.scope(`transformer:${r.type||"unknown"}`).debug("chainMock",{chain:i}),a=t;continue}if(void 0!==r.config?.mock){e.logger.scope(`transformer:${r.type||"unknown"}`).debug("mock"),a=r.config.mock;continue}if(r.config?.disabled)continue;const u=r.config?.cache,d=u?(0,R.compileCache)(u):void 0,l=d?W(d,e):void 0;let p;if(d&&l){const e=(0,R.buildCacheContext)(s,a),t=await(0,R.checkCache)(d,l,e);if("HIT"===t?.status&&t.value){if(a=t.value,d.stop)return{event:a,respond:c,stopped:!0};continue}"MISS"===t?.status&&(p={key:t.key,ttl:t.rule.ttl})}const f=r.config.before;if(f){const n=(0,R.getNextSteps)(f,(0,R.buildCacheContext)(s,a));if(1===n.length){const o=X(n[0],V(t));if(o.length>0){const n=await ne(e,t,o,a,s,c,i);if(null===n.event)return{event:null,respond:n.respond??c};if(n.stopped)return{event:Array.isArray(n.event)?n.event[0]:n.event,respond:n.respond??c,stopped:!0};n.respond&&(c=n.respond),a=Array.isArray(n.event)?n.event[0]:n.event}}else n.length>1&&await Promise.all(n.map(n=>(0,R.tryCatchAsync)(ne,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,X(n,V(t)),a,te(s,n),void 0,i)))}const g=await(0,R.tryCatchAsync)(ee,t=>(e.logger.scope(`transformer:${r.type||"unknown"}`).error("Push failed",{error:t}),!1))(e,r,o,a,s,c);if(!1===g)return{event:null,respond:c};if(Array.isArray(g)){const r=n.slice(n.indexOf(o)+1),u=await Promise.all(g.map(async n=>{const o=n.event||a,u=te(s,"unknown");if(n.next){const s=(0,R.getNextSteps)(n.next,(0,R.buildCacheContext)(u,o));if(0===s.length)return{event:o,respond:c};if(1===s.length){const n=X(s[0],V(t));return n.length>0?ne(e,t,n,o,u,c,i):{event:o,respond:c}}return(await Promise.all(s.map(n=>(0,R.tryCatchAsync)(ne,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,X(n,V(t)),o,te(u,n),void 0,i)))).map(e=>({event:e.event,respond:void 0}))}return r.length>0?ne(e,t,r,o,u,c,i):{event:o,respond:c}}));let d=c;const l=[];for(const e of u.flat())if(null!==e)if(e&&"object"==typeof e&&"event"in e){const t=e;if(t.respond&&(d=t.respond),null===t.event)continue;Array.isArray(t.event)?l.push(...t.event):l.push(t.event)}else l.push(e);return 0===l.length?{event:null,respond:d}:1===l.length?{event:l[0],respond:d}:{event:l,respond:d}}if(g&&"object"==typeof g){const{event:n,respond:o,next:r}=g;if(o&&(c=o),void 0!==r){const o=(0,R.getNextSteps)(r,(0,R.buildCacheContext)(s,a));if(0===o.length){n&&(a=n);continue}if(1===o.length){const u=X(o[0],V(t));return u.length>0?ne(e,t,u,n||a,s,c,i):(e.logger.warn(`Branch target not found: ${JSON.stringify(r)}`),{event:null,respond:c})}return await Promise.all(o.map(o=>(0,R.tryCatchAsync)(ne,t=>(e.logger.scope("transformer:many").error(`many branch ${o} failed`,{error:t}),{event:null,respond:void 0}))(e,t,X(o,V(t)),n||a,te(s,o),void 0,i))),{event:null,respond:void 0}}n&&(a=n)}p&&l&&(0,R.storeCache)(l,p.key,a,p.ttl);const h=r.config.next,m="string"==typeof h||Array.isArray(h)&&h.every(e=>"string"==typeof e),y=void 0!==h&&!m;if((!g||"object"==typeof g&&!g.next)&&y){const n=(0,R.getNextSteps)(r.config.next,(0,R.buildCacheContext)(s,a));if(1===n.length){const o=X(n[0],V(t));return o.length>0?ne(e,t,o,a,s,c,i):{event:a,respond:c}}return n.length>1?(await Promise.all(n.map(n=>(0,R.tryCatchAsync)(ne,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,X(n,V(t)),a,te(s,n),void 0,i))),{event:null,respond:void 0}):{event:a,respond:c}}}return{event:a,respond:c}}function oe(e){return e&&(0,R.isObject)(e)?e:{}}function se(e){return"string"==typeof e||!(!Array.isArray(e)||!e.every(e=>"string"==typeof e))}async function re(e,t,n){if(!t.on||!t.queueOn?.length)return;const o=t.queueOn;t.queueOn=[];const s=n||t.config?.id||"unknown";for(const{type:n,data:r}of o)await(0,N.tryCatchAsync)(t.on,t=>{if(t instanceof N.FatalError)throw t;e.status.failed++,e.logger.scope("source").error("source on flush failed",{sourceId:s,type:n,error:t})})(n,r)}function ie(e){return Boolean(e.config.init)&&!e.config.require?.length}async function ae(e,t,n){const{code:o,config:s={},env:r={},primary:i,next:a,before:c,cache:u}=n,d=u,l=d?(0,N.compileCache)({...d,stop:d.stop??!0}):void 0,p=se(a)?X(a,V(e.transformers)):void 0,f=se(c)?X(c,V(e.transformers)):void 0,g=r.push,h=g??e.push,m=Boolean(g),y=async(n,o,r)=>{let i;const u=f??(void 0!==c?(()=>{const t=(0,N.getNextSteps)(c,(0,N.buildCacheContext)(r.ingest));return 0===t.length?[]:X(1===t.length?t[0]:t,V(e.transformers))})():[]);let d=[n];if(u.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const o=await ne(e,e.transformers,u,n,r.ingest,r.respond,`source.${t}.before`);if(null===o.event)return{ok:!0};if(o.stopped)return o.respond&&(r.respond=o.respond),{ok:!0};o.respond&&(r.respond=o.respond),d=Array.isArray(o.event)?o.event:[o.event]}if(l){const t=W(l,e);if(t){const n=(0,N.buildCacheContext)(r.ingest),o=await(0,N.checkCache)(l,t,n);if(o){if("HIT"===o.status&&void 0!==o.value&&l.stop){let t=o.value;return o.rule.update&&(t=await(0,N.applyUpdate)(t,o.rule.update,{...n,cache:{status:"HIT"}},e)),r.respond?.(t),{ok:!0}}if("MISS"===o.status&&l.stop&&r.respond){const s=r.respond,a=o.rule.update,c={...n,cache:{status:"MISS"}},u=o.key,d=o.rule.ttl,l=n=>{(0,N.storeCache)(t,u,n,d),a?i=(async()=>{const t=await(0,N.applyUpdate)(n,a,c,e);s(t)})():s(n)};r.respond=l}"MISS"!==o.status||l.stop||(0,N.storeCache)(t,o.key,!0,o.rule.ttl)}}}const g=p?{kind:"single",preChain:p}:void 0!==a?(()=>{const t=(0,N.getNextSteps)(a,(0,N.buildCacheContext)(r.ingest));return 0===t.length?{kind:"single",preChain:[]}:1===t.length?{kind:"single",preChain:X(t[0],V(e.transformers))}:{kind:"many",branches:t.map(t=>X(t,V(e.transformers)))}})():{kind:"single",preChain:[]};let y={ok:!0};for(const n of d)"many"===g.kind?(await Promise.all(g.branches.map((i,a)=>(0,N.tryCatchAsync)(async()=>m?h(n):h(n,{...o,id:t,ingest:te(r.ingest,`${t}.${a}`),respond:void 0,mapping:s,preChain:i}),t=>(e.logger.scope("source:many").error(`many branch ${a} failed`,{error:t}),{ok:!0}))())),y={ok:!0}):y=m?await h(n):await h(n,{...o,id:t,ingest:r.ingest,respond:r.respond,mapping:s,preChain:g.preChain});return i&&await i,y},w=async n=>{const o=(0,N.createIngest)(t);if(!s.ingest||void 0===n)return o;const r=await(0,N.getMappingValue)(n,s.ingest,{collector:e});return{...o,...r,_meta:o._meta}},b=e.logger.scope("source").scope(t),v={command:e.command,sources:e.sources,elb:e.sources.elb.push,logger:b,...r,push:async(e,n={})=>{const o={ingest:(0,N.createIngest)(t),respond:void 0};return y(e,n,o)}},k={collector:e,logger:b,id:t,config:s,env:v,withScope:async(e,t,n)=>{const o={ingest:await w(e),respond:t};return n({...v,push:(e,t={})=>y(e,t,o),ingest:o.ingest,respond:o.respond})}},S=await(0,N.tryCatchAsync)(o,n=>{if(n instanceof N.FatalError)throw n;e.status.failed++,e.logger.scope("source").error("source factory failed",{sourceId:t,error:n})})(k);if(!S)return;const q=S.type||"unknown",I=e.logger.scope(q).scope(t);return v.logger=I,i&&(S.config={...S.config,primary:i}),S}function ce(e,t,n,o){if(n instanceof _.FatalError)throw n;e.logger.scope("on").error("on callback failed",{kind:t,...o,error:n})}function ue(e,t){return{collector:e,logger:e.logger.scope("on").scope(String(t))}}function de(e,t,n,o,s){if(!t.on)return;const r=t.type||"unknown",i=e.logger.scope(r).scope("on").scope(o),a={collector:e,logger:i,id:n,config:t.config,data:s,env:Ce(t.env,t.config.env)};(0,H.tryCatch)(t.on,t=>ce(e,"destination",t,{destId:n,type:o}))(o,a)}function le(e,t,n,o){let s;switch(t){case J.Consent:s=o||e.consent;break;case J.Session:s=e.session;break;case J.User:s=o||e.user;break;case J.Custom:s=o||e.custom;break;case J.Globals:s=o||e.globals;break;case J.Config:s=o||e.config;break;case J.Ready:case J.Run:default:s=void 0}if(n.length)switch(t){case J.Consent:!function(e,t,n){const o=n||e.consent,s=ue(e,J.Consent);t.forEach(t=>{Object.keys(o).filter(e=>e in t).forEach(n=>{(0,H.tryCatch)(t[n],t=>ce(e,"consent",t,{key:n}))(o,s)})})}(e,n,o);break;case J.Ready:!function(e,t){if(!e.allowed)return;const n=ue(e,J.Ready);t.forEach(t=>{(0,H.tryCatch)(t,t=>ce(e,"ready",t))(void 0,n)})}(e,n);break;case J.Run:!function(e,t){if(!e.allowed)return;const n=ue(e,J.Run);t.forEach(t=>{(0,H.tryCatch)(t,t=>ce(e,"run",t))(void 0,n)})}(e,n);break;case J.Session:!function(e,t){if(!e.session)return;const n=ue(e,J.Session);t.forEach(t=>{(0,H.tryCatch)(t,t=>ce(e,"session",t))(e.session,n)})}(e,n);break;default:{const o=ue(e,t);n.forEach(n=>{"function"==typeof n&&(0,H.tryCatch)(n,n=>ce(e,"generic",n,{type:t}))(s,o)});break}}}function pe(e,t,n,o){if(!Number.isFinite(n.max)||n.max<=0)throw new Error(`pushBounded: max must be > 0 (got ${n.max})`);if("dropNewest"===(n.onOverflow??"dropOldest"))return e.length>=n.max?(o&&o([t]),{appended:!1,dropped:1}):(e.push(t),{appended:!0,dropped:0});const s=[];for(;e.length>=n.max;)s.push(e.shift());return e.push(t),s.length>0&&o&&o(s),{appended:!0,dropped:s.length}}var fe=new WeakMap;function ge(e,t,n,o){fe.get(e)||(fe.set(e,!0),t.warn(n,o))}function he(e){fe.delete(e)}var me=Object.freeze({batched:!0});function ye(e){return e===me}function we(e){return void 0===e?{}:"number"==typeof e?{wait:e}:{wait:e.wait,size:e.size,age:e.age}}function be(e,t){return e.status.destinations[t]||(e.status.destinations[t]={count:0,failed:0,duration:0,queuePushSize:0,dlqSize:0}),e.status.destinations[t]}function ve(e,t,n,o){e.dropped[t]||(e.dropped[t]={});const s=e.dropped[t];return s[n]=(s[n]??0)+o,s[n]}function ke(e,t,n){if(!e)return[];if(Array.isArray(e)&&e.every(e=>"string"==typeof e))return X(e,t);if("string"==typeof e)return X(e,t);const o=(0,$.getNextSteps)(e,(0,$.buildCacheContext)(n));return 0===o.length?[]:1===o.length?X(o[0],t):X(o,t)}async function Se(e,t,n={},o){const{allowed:s,consent:r,globals:i,user:a}=e;if(!s)return Oe({ok:!1});if(t){const n=e.config.queueMax;if(void 0===n)throw new Error("Collector.Config.queueMax is undefined; defaults must be seeded by collector()");const o=pe(e.queue,t,{max:n});if(o.dropped>0){const t=ve(e.status,(0,$.stepId)("collector"),"queue",o.dropped);ge(e.queue,e.logger,"collector.queue overflow; oldest events dropped",{buffer:"queue",cap:n,droppedCount:t})}else e.queue.length<n&&he(e.queue);e.status.in++}o||(o=e.destinations);const c=e.transformers?V(e.transformers):{},u=await Promise.all(Object.entries(o||{}).map(async([o,s])=>{if(s.config.disabled)return{id:o,destination:s,skipped:!0};let u=(s.queuePush||[]).map(e=>({...e,consent:r}));s.queuePush=[],t&&u.push((0,$.clone)(t));const d=n.ingest?{...n.ingest,_meta:{...n.ingest._meta,path:[...n.ingest._meta.path]}}:(0,$.createIngest)("unknown");if(!u.length&&!s.queueOn?.length)return{id:o,destination:s,skipped:!0};if(!u.length&&s.queueOn?.length){let t=!1;try{t=await qe(e,s,o)}catch(t){e.status.failed++;const n=s.type||"unknown";e.logger.scope(n).error("destination init failed",{error:t instanceof Error?t.message:String(t)})}return{id:o,destination:s,skipped:!t}}const l=[],p=u.filter(t=>{const n=(0,$.getGrantedConsent)(s.config.consent,r,t.consent);if(n)return t.consent=n,l.push(t),!1;const i=U(e,{stepId:(0,$.stepId)("destination",o),stepType:"destination",phase:"skip",eventId:"string"==typeof t.id?t.id:"",now:Date.now()});return i.skipReason="consent",r&&(i.consent={...r}),s.config.consent&&(i.meta={required:{...s.config.consent}}),(0,$.emitStep)(e,i),!0});if(p.length>0){const t=s.queuePush,n=s.config.id||o,r={max:s.config.queueMax??1e3};let i=0;for(const e of p)i+=pe(t,e,r).dropped;if(i>0){be(e,n);const o=ve(e.status,(0,$.stepId)("destination",n),"queue",i);ge(t,e.logger.scope(s.type||"unknown"),"destination.queuePush overflow; oldest events dropped",{buffer:"queuePush",destination:n,cap:r.max,droppedCount:o})}else t.length<r.max&&he(t)}if(!l.length)return{id:o,destination:s,queue:u};let f,g,h=!1;try{h=await qe(e,s,o)}catch(t){e.status.failed++;const n=s.type||"unknown";e.logger.scope(n).error("destination init failed",{error:t instanceof Error?t.message:String(t)})}if(!h)return{id:o,destination:s,queue:u};s.dlq||(s.dlq=[]);const m=ke(s.config.before,c,d),y=s.config.next,w=s.config?.cache,b=w?(0,$.compileCache)(w):void 0,v=b?W(b,e):void 0;let k=0,S=0;return await Promise.all(l.map(async t=>{let r;if(t.globals=(0,$.assign)(i,t.globals),t.user=(0,$.assign)(a,t.user),b?.stop&&v){const e=(0,$.buildCacheContext)(d,t),n=await(0,$.checkCache)(b,v,e);if("HIT"===n?.status)return t;"MISS"===n?.status&&(r={key:n.key,ttl:n.rule.ttl})}let u=t,l=n.respond;if(m.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const s=await ne(e,e.transformers,m,t,d,n.respond,`destination.${o}.before`);if(null===s.event)return t;s.respond&&(l=s.respond),u=Array.isArray(s.event)?s.event[0]:s.event}if(b&&!b.stop&&v){const e=(0,$.buildCacheContext)(d,u),n=await(0,$.checkCache)(b,v,e);if("HIT"===n?.status)return t;"MISS"===n?.status&&(r={key:n.key,ttl:n.rule.ttl})}const p=Date.now();let h=!1;const w=await(0,$.tryCatchAsync)(Ie,t=>{const n=s.type||"unknown";e.logger.scope(n).error("Push failed",{error:t,event:u.name}),f=t,h=!0;const r=s.dlq,i=s.config.id||o,a={max:s.config.dlqMax??100},c=pe(r,[u,t],a);if(c.dropped>0){be(e,i);const t=ve(e.status,(0,$.stepId)("destination",i),"dlq",c.dropped);ge(r,e.logger.scope(s.type||"unknown"),"destination.dlq overflow; oldest entries dropped",{buffer:"dlq",destination:i,cap:a.max,droppedCount:t})}else r.length<a.max&&he(r)})(e,s,o,u,d,l);if(k+=Date.now()-p,r&&v&&void 0===s.config.mock&&(0,$.storeCache)(v,r.key,w??!0,r.ttl),void 0===w||ye(w)||(g=w),ye(w)&&S++,!h&&y){void 0!==w&&(d._response=w);const t=ke(y,c,d);if(t.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const n=await ne(e,e.transformers,t,u,d,l,`destination.${o}.next`);n.respond&&(l=n.respond)}}return t})),{id:o,destination:s,error:f,response:g,totalDuration:k,batchedCount:S,allowedCount:l.length}})),d={},l={},p={};for(const t of u){if(t.skipped)continue;const n=t.destination,o={type:n.type||"unknown",data:t.response};be(e,t.id);const s=e.status.destinations[t.id],r=Date.now();if(s.queuePushSize=n.queuePush?.length??0,s.dlqSize=n.dlq?.length??0,t.error)o.error=t.error,p[t.id]=o,s.failed++,s.lastAt=r,s.duration+=t.totalDuration||0,e.status.failed++;else if(t.queue&&t.queue.length)l[t.id]=o;else{const n=t.batchedCount??0,i=t.allowedCount??0;(Math.max(0,i-n)>0||0===i)&&(d[t.id]=o,s.count++,s.lastAt=r,s.duration+=t.totalDuration||0,e.status.out++)}}return Oe({event:t,...Object.keys(d).length&&{done:d},...Object.keys(l).length&&{queued:l},...Object.keys(p).length&&{failed:p}})}async function qe(e,t,n){if(t.init&&!t.config.init){const o=t.type||"unknown",s=e.logger.scope(o),r={collector:e,logger:s,id:n,config:t.config,env:Ce(t.env,t.config.env)};s.debug("init");const i=Date.now();let a;(0,$.emitStep)(e,U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"init",eventId:"",now:i}));try{a=await(0,$.useHooks)(t.init,"DestinationInit",e.hooks,e.logger)(r)}catch(t){const o=Date.now(),s=U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"error",eventId:"",now:o});throw s.durationMs=o-i,s.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},(0,$.emitStep)(e,s),t}if(!1===a)return a;if(t.config={...a||t.config,init:!0},t.queueOn?.length){const o=t.queueOn;t.queueOn=[];for(const{type:s,data:r}of o)de(e,t,n,s,r)}s.debug("init done")}return!0}async function Ie(e,t,n,o,s,r){const{config:i}=t,a=await(0,$.processEventMapping)(o,i,e);if(a.ignore)return!1;const c=t.type||"unknown",u=e.logger.scope(c),d={collector:e,logger:u,id:n,config:i,data:a.data,rule:a.mapping,ingest:s,env:{...Ce(t.env,i.env),...r?{respond:r}:{}}};if(void 0!==i.mock)return u.debug("mock",{event:a.event.name}),i.mock;const l=a.mapping,p=a.mappingKey||"* *";if(l?.batch&&t.pushBatch&&void 0===i.mock){if(t.batches=t.batches||{},!t.batches[p]){const o={key:p,entries:[],events:[],data:[]},s=we(l.batch),r=we(i.batch),a=s.wait??r.wait??3e4,c=s.size??r.size??1e3,d=s.age??r.age??3e4,f=Ce(t.env,i.env),g=(0,$.debounce)(async()=>{const o=t.batches[p].batched;if(0===o.entries.length)return;const s={key:o.key,entries:o.entries,events:o.events,data:o.data};o.entries=[],o.events=[],o.data=[];const r=s.entries[0],a={collector:e,logger:u,id:n,config:i,data:void 0,rule:r.rule,ingest:r.ingest,env:{...f,...r.respond?{respond:r.respond}:{}}};u.debug("push batch",{events:s.entries.length});const c=t.config.id||n,d=be(e,c),l=Date.now(),g=U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"flush",eventId:"",now:l});g.batch={size:s.entries.length,index:0},(0,$.emitStep)(e,g);let h=!0;await(0,$.tryCatchAsync)((0,$.useHooks)(t.pushBatch,"DestinationPushBatch",e.hooks,e.logger),o=>{h=!1;const r=Date.now(),i=U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"error",eventId:"",now:r});i.durationMs=r-l,i.error=o instanceof Error?{name:o.name,message:o.message}:{message:String(o)},i.batch={size:s.entries.length,index:0},(0,$.emitStep)(e,i);const a=t.dlq=t.dlq||[],p={max:t.config.dlqMax??100};let f=0;for(const e of s.entries)f+=pe(a,[e.event,o],p).dropped;if(f>0){const t=ve(e.status,(0,$.stepId)("destination",c),"dlq",f);ge(a,u,"destination.dlq overflow; oldest entries dropped",{buffer:"dlq",destination:c,cap:p.max,droppedCount:t})}else a.length<p.max&&he(a);d.failed+=s.entries.length,d.dlqSize=a.length,e.status.failed+=s.entries.length,u.error("Push batch failed",{error:o instanceof Error?o.message:String(o),entries:s.entries.length})})(s,a),u.debug("push batch done"),d.inFlightBatch=Math.max(0,(d.inFlightBatch??0)-s.entries.length),h&&(d.count+=s.entries.length,d.lastAt=Date.now(),e.status.out+=s.entries.length)},{wait:a,size:c,age:d});t.batches[p]={batched:o,batchFn:()=>{g()},flush:async()=>{await g.flush()}}}const o=t.batches[p];o.batched.entries.push({event:a.event,ingest:s,respond:r,rule:l,data:a.data}),o.batched.events.push(a.event),(0,$.isDefined)(a.data)&&o.batched.data.push(a.data);const c=t.config.id||n,d=be(e,c);return d.inFlightBatch=(d.inFlightBatch??0)+1,o.batchFn(),me}{u.debug("push",{event:a.event.name});const o="string"==typeof a.event.id?a.event.id:"",s=Date.now(),r=U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"in",eventId:o,now:s});a.mappingKey&&(r.mappingKey=a.mappingKey),a.event.consent&&(r.consent={...a.event.consent}),(0,$.emitStep)(e,r);try{const r=await(0,$.useHooks)(t.push,"DestinationPush",e.hooks,e.logger)(a.event,d),i=Date.now(),c=U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"out",eventId:o,now:i});return c.durationMs=i-s,c.outEvent=r,a.mappingKey&&(c.mappingKey=a.mappingKey),(0,$.emitStep)(e,c),u.debug("push done"),r}catch(t){const r=Date.now(),i=U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"error",eventId:o,now:r});throw i.durationMs=r-s,i.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},a.mappingKey&&(i.mappingKey=a.mappingKey),(0,$.emitStep)(e,i),t}}}function Oe(e){return{ok:!e?.failed,...e}}function xe(e){const{code:t,config:n={},env:o={},cache:s}=e,{config:r}=Y(e,"before"),{config:i}=Y({...e,config:r},"next"),a={...t.config,...n,...i};s&&(a.cache=s);const c=Ce(t.env,o);return{...t,config:a,env:c}}function Ce(e,t){return e||t?t?e&&(0,$.isObject)(e)&&(0,$.isObject)(t)?{...e,...t}:t:e:{}}async function Ae(e,t,n){const o=Object.entries(e).map(async([e,o])=>{const s=o.destroy;if(!s)return;const r=o.type||"unknown",i=n.scope(r),a={id:e,config:o.config,env:o.env??{},logger:i};try{await Promise.race([s(a),new Promise((n,o)=>setTimeout(()=>o(new Error(`${t} '${e}' destroy timed out`)),5e3))])}catch(n){i.error(`${t} '${e}' destroy failed: ${n}`)}});await Promise.allSettled(o)}async function je(e,t,n){let o,s,r=!1;switch(t){case J.Config:(0,G.isObject)(n)&&((0,B.assign)(e.config,n,{shallow:!1}),s=n,r=!0);break;case J.Consent:if((0,G.isObject)(n)){const{update:t}=function(e,t){const n={};return Object.entries(t).forEach(([e,t])=>{n[e]=!!t}),e.consent=(0,M.assign)(e.consent,n),{update:n}}(e,n);s=t,r=!0}break;case J.Custom:(0,G.isObject)(n)&&(e.custom=(0,B.assign)(e.custom,n),s=n,r=!0);break;case J.Destination:(0,G.isObject)(n)&&"code"in n&&(0,G.isObject)(n.code)&&(o=await async function(e,t){const{code:n,config:o={},env:s={},before:r,next:i,cache:a}=t;if(!(0,$.isFunction)(n.push))return Oe({ok:!1,failed:{invalid:{type:"invalid",error:"Destination code must have a push method"}}});const c=o||{init:!1};let u=r?{...c,before:r}:{...c};i&&(u={...u,next:i}),a&&(u={...u,cache:a});const d={...n,config:u,env:Ce(n.env,s)};let l=d.config.id;if(!l)do{l=(0,$.getId)(5,"abcdefghijklmnopqrstuvwxyz")}while(e.destinations[l]);return e.destinations[l]=d,!1!==d.config.queue&&(d.queuePush=[...e.queue]),Se(e,void 0,{},{[l]:d})}(e,n));break;case J.Globals:(0,G.isObject)(n)&&(e.globals=(0,B.assign)(e.globals,n),s=n,r=!0);break;case J.Hook:if((0,G.isObject)(n)&&(0,B.isString)(n.name)&&(0,B.isFunction)(n.fn)){const{name:t,fn:o}=n;e.hooks[t]=o,s=n,r=!0}break;case J.On:if((0,G.isObject)(n)&&(0,B.isString)(n.type)){const{type:t,rules:o}=n;await async function(e,t,n){const o=e.on,s=o[t]||[],r=(0,_.isArray)(n)?n:[n];r.forEach(e=>{s.push(e)}),o[t]=s,le(e,t,r)}(e,t,o)}break;case J.Ready:r=!0;break;case J.Run:o=await async function(e,t){return e.allowed=!0,e.timing=Date.now(),t&&(t.consent&&(e.consent=(0,B.assign)(e.consent,t.consent)),t.user&&(e.user=(0,B.assign)(e.user,t.user)),t.globals&&(e.globals=(0,B.assign)(e.config.globalsStatic||{},t.globals)),t.custom&&(e.custom=(0,B.assign)(e.custom,t.custom))),Object.values(e.destinations).forEach(e=>{e.queuePush=[]}),e.queue=[],e.round++,await Se(e)}(e,n),r=!0;break;case J.Session:r=!0;break;case J.Shutdown:await async function(e){const t=e.logger;await Ae(e.sources,"source",t),await Ae(e.destinations,"destination",t),await Ae(e.transformers,"transformer",t),await Ae(e.stores,"store",t)}(e);break;case J.User:(0,G.isObject)(n)&&((0,B.assign)(e.user,n,{shallow:!1}),s=n,r=!0)}return r&&(await async function(e,t,n,o){let s,r=n||[];switch(n||(r=e.on[t]||[]),t){case J.Consent:s=o||e.consent;break;case J.Session:s=e.session;break;case J.User:s=o||e.user;break;case J.Custom:s=o||e.custom;break;case J.Globals:s=o||e.globals;break;case J.Config:s=o||e.config;break;case J.Ready:case J.Run:default:s=void 0}let i=!1;for(const[n,o]of Object.entries(e.sources)){if(o.config.require?.length){const e=o.config.require.indexOf(t);-1!==e&&o.config.require.splice(e,1)}o.on&&(ie(o)?!1===await(0,H.tryCatchAsync)(o.on,o=>ce(e,"source",o,{sourceId:n,type:t}))(t,s)&&(i=!0):(o.queueOn=o.queueOn||[],o.queueOn.push({type:t,data:s})))}Object.entries(e.destinations).forEach(([n,o])=>{if(o.on){if(!o.config.init)return o.queueOn=o.queueOn||[],void o.queueOn.push({type:t,data:s});de(e,o,n,t,s)}});for(const[t,n]of Object.entries(e.sources))ie(n)&&n.queueOn?.length&&await re(e,n,t);return Object.keys(e.pending.destinations).length>0&&await async function(e,t){for(const[n,o]of Object.entries(e.pending.destinations)){if(!e.pending.destinations[n]||e.destinations[n])continue;const s=o.config?.require;if(!s)continue;const r=s.indexOf(t);if(-1===r)continue;if(s.splice(r,1),s.length>0)continue;delete e.pending.destinations[n];const i=xe(o);!1!==i.config.queue&&(i.queuePush=[...e.queue]),e.destinations[n]=i}}(e,t),le(e,t,r,o),!i}(e,t,void 0,s),o=await Se(e)),o||Oe({ok:!0})}function De(e,t){if(!t.name)throw new Error("Event name is required");const[n,o]=t.name.split(" ");if(!n||!o)throw new Error("Event name is invalid");const{timestamp:s=Date.now(),name:r=`${n} ${o}`,data:i={},context:a={},globals:c=e.globals,custom:u={},user:d=e.user,nested:l=[],consent:p=e.consent,id:f=(0,B.getSpanId)(),trigger:g="",entity:h=n,action:m=o,timing:y=0,source:w={type:"collector",schema:"4"}}=t;return{name:r,data:i,context:a,globals:c,custom:u,user:d,nested:l,consent:p,id:f,trigger:g,entity:h,action:m,timestamp:s,timing:y,source:w}}function Te(e={}){const t=e.maxEntries??1e4,n=e.lowWaterMark??.8,o=e.sweepIntervalMs??6e4,s=Math.floor(t*n),r=new Map,i={hits:0,misses:0,populates:0,writes:0,deletes:0,evictions_entries:0,evictions_ttl:0};let a;return o>0&&(a=setInterval(function(){const e=Date.now();let t=0;for(const[n,o]of r)void 0!==o.expires&&o.expires<=e&&(r.delete(n),t++);i.evictions_ttl+=t},o),a&&"function"==typeof a.unref&&a.unref()),{type:"memory",config:{},get(e){const t=r.get(e);if(t)return void 0!==t.expires&&t.expires<=Date.now()?(r.delete(e),i.evictions_ttl++,void i.misses++):(r.delete(e),r.set(e,t),i.hits++,t.value);i.misses++},set(e,n,o){const a=!r.has(e);a||r.delete(e),r.set(e,{value:n,expires:void 0!==o?Date.now()+o:void 0}),i.writes++,a&&i.populates++,r.size>t&&function(){if(r.size<=t)return;const e=r.size-s;let n=0;for(const t of r.keys()){if(n>=e)break;r.delete(t),n++}i.evictions_entries+=n}()},delete(e){r.delete(e)&&i.deletes++},get counters(){return{...i}},destroy(){void 0!==a&&(clearInterval(a),a=void 0),r.clear()}}}function ze(e,t){const{cacheConfig:n,cacheStore:o,namespace:s,logger:r,storeId:i,collector:a}=t,c=(e,t)=>{if(!a)return;const n=U(a,{stepId:`store.${i}`,stepType:"store",phase:"in",eventId:"",now:Date.now()});n.meta={op:"cache",cached:"hit"===t,status:t,key:e},(0,Q.emitStep)(a,n)},u={hits:0,misses:0,populates:0,writes:0,deletes:0,inflight_dedups:0},d=n.rules.map(e=>({match:e.match?(0,Q.compileMatcher)(e.match):()=>!0,ttl:e.ttl})),l=e=>`${s}:${e}`;function p(e,t){const n=void 0===t?{key:e}:{key:e,value:t};return d.find(e=>e.match(n))}const f=new Map;return{type:e.type,config:e.config,setup:e.setup,get counters(){return{...u}},async get(t){const n=l(t),s=await o.get(n);if(void 0!==s)return u.hits++,c(t,"hit"),s;const r=f.get(n);if(r)return u.inflight_dedups++,c(t,"hit"),r;u.misses++,c(t,"miss");const i=(async()=>{try{const s=await e.get(t);if(void 0===s)return;const r=p(t,s);if(r)try{await o.set(n,s,1e3*r.ttl),u.populates++}catch(e){g("set",t,e)}return s}finally{f.delete(n)}})();return f.set(n,i),i},async set(t,n,s){u.writes++,await e.set(t,n,s);const r=p(t,n);if(r)try{await o.set(l(t),n,1e3*r.ttl)}catch(e){g("set",t,e)}},async delete(t){u.deletes++,await e.delete(t);try{await o.delete(l(t))}catch(e){g("delete",t,e)}}};function g(e,t,n){const o=`store-cache(${i}): cache ${e} failed for "${t}"; backing succeeded, continuing`;r?r.warn(o,{error:n}):console.warn(o,n)}}function Ee(e,t,n){const o=`store.${n}`,s=(0,K.useHooks)(t.get,"StoreGet",e.hooks,e.logger),r=(0,K.useHooks)(t.set,"StoreSet",e.hooks,e.logger),i=(0,K.useHooks)(t.delete,"StoreDelete",e.hooks,e.logger);t.get=async t=>{const n=Date.now(),r=U(e,{stepId:o,stepType:"store",phase:"in",eventId:"",now:n});r.meta={op:"get",key:t},(0,K.emitStep)(e,r);try{const r=await s(t),i=Date.now(),a=U(e,{stepId:o,stepType:"store",phase:"out",eventId:"",now:i});return a.durationMs=i-n,a.meta={op:"get",key:t},(0,K.emitStep)(e,a),r}catch(s){const r=Date.now(),i=U(e,{stepId:o,stepType:"store",phase:"error",eventId:"",now:r});throw i.durationMs=r-n,i.meta={op:"get",key:t},i.error=s instanceof Error?{name:s.name,message:s.message}:{message:String(s)},(0,K.emitStep)(e,i),s}},t.set=async(t,n,s)=>{const i=Date.now(),a=U(e,{stepId:o,stepType:"store",phase:"in",eventId:"",now:i});a.meta={op:"set",key:t},(0,K.emitStep)(e,a);try{await r(t,n,s);const a=Date.now(),c=U(e,{stepId:o,stepType:"store",phase:"out",eventId:"",now:a});c.durationMs=a-i,c.meta={op:"set",key:t},(0,K.emitStep)(e,c)}catch(n){const s=Date.now(),r=U(e,{stepId:o,stepType:"store",phase:"error",eventId:"",now:s});throw r.durationMs=s-i,r.meta={op:"set",key:t},r.error=n instanceof Error?{name:n.name,message:n.message}:{message:String(n)},(0,K.emitStep)(e,r),n}},t.delete=async t=>{const n=Date.now(),s=U(e,{stepId:o,stepType:"store",phase:"in",eventId:"",now:n});s.meta={op:"delete",key:t},(0,K.emitStep)(e,s);try{await i(t);const s=Date.now(),r=U(e,{stepId:o,stepType:"store",phase:"out",eventId:"",now:s});r.durationMs=s-n,r.meta={op:"delete",key:t},(0,K.emitStep)(e,r)}catch(s){const r=Date.now(),i=U(e,{stepId:o,stepType:"store",phase:"error",eventId:"",now:r});throw i.durationMs=r-n,i.meta={op:"delete",key:t},i.error=s instanceof Error?{name:s.name,message:s.message}:{message:String(s)},(0,K.emitStep)(e,i),s}}}async function Me(e){const t=(0,P.assign)({globalsStatic:{},sessionStatic:{},run:!0,queueMax:1e3},e,{merge:!1,extend:!1}),n={level:e.logger?.level,handler:e.logger?.handler},o=(0,P.createLogger)(n),s={...t.globalsStatic,...e.globals},r={allowed:!1,config:t,consent:e.consent||{},custom:e.custom||{},destinations:{},transformers:{},stores:{},globals:s,hooks:e.hooks||{},observers:new Set,logger:o,on:{},queue:[],round:0,session:void 0,status:{startedAt:Date.now(),in:0,out:0,failed:0,sources:{},destinations:{},dropped:{}},timing:Date.now(),user:e.user||{},sources:{},pending:{destinations:{}},push:void 0,command:void 0};var i,a;r.push=function(e,t){const n=(0,F.useHooks)(async(n,o={})=>await(0,F.tryCatchAsync)(async()=>{const s=Date.now(),{id:r,ingest:i,respond:a,mapping:c,preChain:u,include:d,exclude:l}=o;let p=a,f=n;const g=d||l?function(e,t,n){let o=e;return t&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>t.includes(e)))),n&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>!n.includes(e)))),o}(e.destinations,d,l):void 0,h=i??(0,F.createIngest)(r||"unknown");if(c){const t=await(0,F.processEventMapping)(f,c,e);if(t.ignore)return Oe({ok:!0});if(c.consent&&!(0,F.getGrantedConsent)(c.consent,e.consent,t.event.consent))return Oe({ok:!0});f=t.event}if(u?.length&&e.transformers&&Object.keys(e.transformers).length>0){const n=await ne(e,e.transformers,u,f,h,p,r?`source.${r}.next`:void 0);if(null===n.event)return Oe({ok:!0});if(n.stopped)return n.respond&&(p=n.respond),Oe({ok:!0});if(n.respond&&(p=n.respond),Array.isArray(n.event)){const o=await Promise.all(n.event.map(async n=>{const o=t(n),s=De(e,o);return Se(e,s,{id:r,ingest:h,respond:p},g)}));if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const t=e.status.sources[r];t.count+=n.event.length,t.lastAt=Date.now(),t.duration+=Date.now()-s}return o[0]??Oe({ok:!0})}f=n.event}const m=t(f),y=De(e,m),w=await Se(e,y,{id:r,ingest:h,respond:p},g);if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const t=e.status.sources[r];t.count++,t.lastAt=Date.now(),t.duration+=Date.now()-s}return w},t=>{if(t instanceof F.FatalError)throw t;return e.status.failed++,e.logger.error("push failed",{event:n,ingest:o.ingest,error:t}),Oe({ok:!1})})(),"Push",e.hooks,e.logger);return async(t,o)=>{const s="string"==typeof t.id?t.id:"",r=Date.now();(0,F.emitStep)(e,U(e,{stepId:"collector.push",stepType:"collector",phase:"in",eventId:s,now:r}));try{const i=await n(t,o),a=Date.now(),c=U(e,{stepId:"collector.push",stepType:"collector",phase:"out",eventId:s,now:a});return c.durationMs=a-r,c.outEvent=i,(0,F.emitStep)(e,c),i}catch(t){const n=Date.now(),o=U(e,{stepId:"collector.push",stepType:"collector",phase:"error",eventId:s,now:n});throw o.durationMs=n-r,o.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},(0,F.emitStep)(e,o),t}}}(r,e=>({timing:Math.round((Date.now()-r.timing)/10)/100,source:{type:"collector",schema:"4",version:"4.1.2"},...e})),r.command=(i=r,a=je,(0,L.useHooks)(async(e,t,n)=>await(0,L.tryCatchAsync)(async()=>await a(i,e,t,n),n=>{if(n instanceof L.FatalError)throw n;return i.status.failed++,i.logger.error("command failed",{command:e,data:t,error:n}),Oe({ok:!1})})(),"Command",i.hooks,i.logger));const c=e.stores||{};return r.stores=await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{code:t,config:r={},env:i={}}=s,a=e.logger.scope("store").scope(o),c={collector:e,logger:a,id:o,config:r,env:i},u=await t(c);n[o]=u}const o=t,s=function(e){const t={};for(const n of Object.keys(e))t[n]="WHITE";const n=[],o=[];function s(r){const i=t[r];if("BLACK"===i)return;if("GRAY"===i){const e=o.indexOf(r),t=o.slice(-1===e?0:e).concat(r).join(" -> ");throw new Error(`Cycle in cache.store chain: ${t}`)}t[r]="GRAY",o.push(r);const a=e[r].cache?.store;if(void 0!==a){if(!(a in e))throw new Error(`Store "${r}" cache.store references "${a}", which is not declared in flow.stores`);s(a)}o.pop(),t[r]="BLACK",n.push(r)}for(const n of Object.keys(e))"WHITE"===t[n]&&s(n);return n}(o);for(const t of s){const s=o[t].cache;if(!s)continue;let r,i;void 0!==s.store?(r=n[s.store],i=s.store):(n.__cache||(n.__cache=Te()),r=n.__cache,i="__cache");const a=s.namespace??t;e.logger.scope("store-cache").scope(t).info(`store "${t}" caches with namespace "${a}:" via ${i}`),n[t]=ze(n[t],{storeId:t,cacheConfig:s,cacheStore:r,namespace:a,logger:e.logger.scope("store-cache").scope(t),collector:e})}for(const[t,o]of Object.entries(n))"__cache"!==t&&Ee(e,o,t);return n}(r,c),function(e,t,n){const o=new Map;for(const[n,s]of Object.entries(e))t[n]&&o.set(s,t[n]);if(0!==o.size)for(const e of[n.transformers,n.destinations,n.sources])if(e)for(const t of Object.values(e))s(t.env);function s(e){if(e)for(const[t,n]of Object.entries(e))if("object"==typeof n&&null!==n){const s=o.get(n);s&&(e[t]=s)}}}(c,r.stores,e),r.stores.__cache||(r.stores.__cache=Te()),r.destinations=await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t))s.config?.require?.length?e.pending.destinations[o]=s:n[o]=xe(s);return n}(r,e.destinations||{}),r.transformers=await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{code:t,env:r={}}=s,i=(0,R.validateStepEntry)(s,"Transformer");if(!i.ok){e.logger.warn(`Transformer ${o} invalid (${i.code}): ${i.reason}. Skipping.`);continue}const{config:a}=Y(s,"before"),{config:c}=Y({...s,config:a},"next"),u=Object.keys(r).length>0?{...c,env:r}:c,{cache:d}=s,l=d?{...u,cache:d}:u,p=e.logger.scope("transformer").scope(o),f={collector:e,logger:p,id:o,ingest:(0,R.createIngest)(o),config:l,env:r},g=t??(e=>{const t=s.mapping;if(t){const n=[];if(void 0!==t.data&&n.push("data"),t.mapping)for(const[e,o]of Object.entries(t.mapping))if("object"==typeof o&&null!==o)for(const[t,s]of Object.entries(o)){if("object"!=typeof s||null===s)continue;const o=s;void 0!==o.data&&n.push(`mapping[${e}][${t}].data`),void 0!==o.silent&&n.push(`mapping[${e}][${t}].silent`)}return n.length>0&&e.collector.logger.warn(`Transformer ${o}: \`${n.join(", ")}\` ignored at transformer position (only event-mutating fields apply).`),{type:"pass",config:e.config,push:async n=>{const o=await(0,R.processEventMapping)(n,t,e.collector);return!o.ignore&&{event:o.event}}}}return{type:"pass",config:e.config,push:e=>({event:e})}}),h=await g(f);void 0!==s.before&&void 0===h.config?.before&&(h.config={...h.config??{},before:s.before}),void 0!==s.next&&void 0===h.config?.next&&(h.config={...h.config??{},next:s.next}),n[o]=h}return n}(r,e.transformers||{}),r}async function Pe(e){e=e||{};const t=await Me(e),n=(o=t,{type:"elb",config:{},push:async(e,t,n,s,r)=>{if("string"==typeof e&&e.startsWith("walker ")){const n=e.replace("walker ","");return o.command(n,t)}let i;if("string"==typeof e)i={name:e},t&&"object"==typeof t&&!Array.isArray(t)&&(i.data=t);else{if(!e||"object"!=typeof e)return Oe({ok:!1});i=e,t&&"object"==typeof t&&!Array.isArray(t)&&(i.data={...i.data||{},...t})}return n&&"object"==typeof n&&(i.context=n),s&&Array.isArray(s)&&(i.nested=s),r&&"object"==typeof r&&(i.custom=r),o.push(i)}});var o;t.sources.elb=n,await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const t=await ae(e,o,s);if(!t)continue;const r=s.config?.require;t.config={...t.config,init:!1,...r?{require:[...r]}:{}},n[o]=t}Object.assign(e.sources,n);for(const t of Object.keys(n)){const n=e.sources[t];let o=!1;n.init&&await(0,N.tryCatchAsync)(n.init.bind(n),n=>{if(n instanceof N.FatalError)throw n;o=!0,e.status.failed++,e.logger.scope("source").error("source init failed",{sourceId:t,error:n})})(),o||(n.config.init=!0,ie(n)&&await re(e,n,t))}return n}(t,e.sources||{});const{consent:s,user:r,globals:i,custom:a}=e;s&&await t.command("consent",s),r&&await t.command("user",r),i&&Object.assign(t.globals,i),a&&Object.assign(t.custom,a),t.config.run&&await t.command("run");let c=n.push;const u=Object.values(t.sources).filter(e=>"elb"!==e.type),d=u.find(e=>e.config.primary);return d?c=d.push:u.length>0&&(c=u[0].push),{collector:t,elb:c}}var $e=async e=>{let t;return{get flow(){return t},trigger:()=>async n=>{if(!t){const n=await Pe(e);t={collector:n.collector,elb:n.elb}}const o=function(e){for(const t of Object.values(e.sources||{}))if("lambda"===t.type)return t}(t.collector);if(!o)throw new Error("Lambda source not found in collector");const s={awsRequestId:`test-${Date.now()}`},r=o.push,i=await r(n,s);let a;try{a=JSON.parse(i.body||"{}")}catch{a=i.body}const c={};if(i.headers)for(const[e,t]of Object.entries(i.headers))void 0!==t&&(c[e]=String(t));return{statusCode:i.statusCode,body:a,headers:c}}}};function _e(e){return async t=>{const n={...t};if(n.body&&"string"==typeof n.body){const e=JSON.parse(n.body);e.name&&!e.event&&(n.body=JSON.stringify({...e,event:e.name,name:void 0}))}return e.push(n,{awsRequestId:"test-req"})}}var He={};r(He,{createTrigger:()=>Ye,env:()=>Ne,step:()=>Ke});var Ne={};r(Ne,{push:()=>Fe,simulation:()=>Le});var Re=()=>{},Be={error:Re,warn:Re,info:Re,debug:Re,throw:e=>{throw"string"==typeof e?new Error(e):e},json:Re,scope:()=>Be},Ge=()=>()=>Promise.resolve({ok:!0}),Fe={get push(){return Ge()},get command(){return Ge()},get elb(){return Ge()},logger:Be},Le=["AWS.SQSClient"],Ke={};r(Ke,{decoderText:()=>Ue,malformedJson:()=>We,orderComplete:()=>Je,pageView:()=>Qe});var Qe={title:"Page view from SQS",description:"A standard SQS message body containing a walker elb event payload as JSON.",in:{MessageId:"m-1",Body:JSON.stringify({event:"page view",data:{title:"Documentation",url:"https://example.com/docs"}})},out:[["message.ack","m-1"]]},Je={title:"Order complete from SQS",description:"Order complete event flowing through the long-poll loop.",in:{MessageId:"m-2",Body:JSON.stringify({event:"order complete",data:{id:"ORD-500",total:199.99,currency:"EUR"}})},out:[["message.ack","m-2"]]},Ue={title:"Text decoder",description:'When decoder is "text", the body string flows under data.payload.',in:{MessageId:"m-3",Body:"raw text payload"},out:[["message.ack","m-3"]]},We={title:"Malformed JSON nacks",description:"Default decoder is JSON. A malformed body throws DecoderError; the source nacks (skips DeleteMessage) so the message redelivers.",in:{MessageId:"m-4",Body:"{not json"},out:[["message.nack","m-4"]]};function Ve(e){if("object"!=typeof e||null===e)return!1;const t=e;return"sqs"===t.type&&"function"==typeof t.push}var Ye=async e=>{let t;return{get flow(){return t},trigger:()=>async n=>{if(!t){const n=await Pe(e);t={collector:n.collector,elb:n.elb}}const o=function(e){for(const t of Object.values(e.sources??{}))if(Ve(t))return t}(t.collector);if(!o)throw new Error("sqs source not registered in collector, ensure it is configured in sources");const s={MessageId:n.MessageId,Body:n.Body,ReceiptHandle:n.ReceiptHandle,Attributes:n.Attributes,MessageAttributes:n.MessageAttributes},r=await o.push(s),i=[];return r&&"object"==typeof r&&(r.acked&&i.push(["message.ack",n.MessageId]),r.nacked&&i.push(["message.nack",n.MessageId])),i}}};//# sourceMappingURL=dev.js.map
1
+ "use strict";var e,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,r=(e,n)=>{for(var o in n)t(e,o,{get:n[o],enumerable:!0})},i={};r(i,{examples:()=>I,schemas:()=>a,sqsExamples:()=>Ne}),module.exports=(e=i,((e,r,i,a)=>{if(r&&"object"==typeof r||"function"==typeof r)for(let c of o(r))s.call(e,c)||c===i||t(e,c,{get:()=>r[c],enumerable:!(a=n(r,c))||a.enumerable});return e})(t({},"__esModule",{value:!0}),e));var a={};r(a,{CorsOptionsSchema:()=>f,CorsOrigin:()=>p,HttpMethod:()=>l,SettingsSchema:()=>g,settings:()=>h,sqsSettings:()=>S,sqsSetup:()=>q});var c=require("@walkeros/core/dev"),u=require("@walkeros/core/dev"),d=require("@walkeros/core/dev"),l=d.z.enum(["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"]),p=d.z.union([d.z.string(),d.z.array(d.z.string()),d.z.literal("*")]),f=d.z.object({origin:p.describe("Allowed origins (* for all, URL string, or array of URLs)").optional(),methods:d.z.array(l).describe("Allowed HTTP methods").optional(),headers:d.z.array(d.z.string()).describe("Allowed request headers").optional(),credentials:d.z.boolean().describe("Allow credentials (cookies, authorization headers)").optional(),maxAge:d.z.number().int().positive().describe("Preflight cache duration in seconds").optional()}),g=u.z.object({cors:u.z.union([u.z.boolean(),f]).describe("CORS configuration: false = disabled, true = allow all origins, object = custom configuration").default(!0),timeout:u.z.number().int().positive().max(9e5).describe("Request timeout in milliseconds (max: 900000 for Lambda)").default(3e4),enablePixelTracking:u.z.boolean().describe("Enable GET requests with 1x1 transparent GIF response for pixel tracking").default(!0),healthPath:u.z.string().describe("Health check endpoint path (e.g., /health)").default("/health")}),h=(0,c.zodToSchema)(g),m=require("@walkeros/core/dev"),y=require("@walkeros/core/dev"),w=y.z.object({queueName:y.z.string().min(1).describe("SQS queue short name (like walkeros-events). Required for both setup and runtime poll."),region:y.z.string().describe("AWS region (like eu-central-1). Default: eu-central-1.").optional(),queueUrl:y.z.string().url().describe("Optional pre-resolved queue URL. When set, init skips the GetQueueUrl lookup.").optional(),client:y.z.any().describe("Pre-configured AWS SQSClient instance. Bypasses construction when supplied.").optional(),config:y.z.any().describe("AWS SDK SQSClientConfig (credentials, endpoint overrides, retries).").optional(),decoder:y.z.enum(["json","text","raw"]).describe("Decoder for the message body. json (default) parses JSON, text forwards UTF-8, raw forwards a Buffer.").optional(),maxMessages:y.z.number().int().min(1).max(10).describe("SQS receive batch size. Cap 10. Default: 10.").optional(),waitTimeSeconds:y.z.number().int().min(0).max(20).describe("Long-poll duration in seconds. Cap 20. Default: 20.").optional(),visibilityTimeout:y.z.number().int().nonnegative().describe("Per-receive visibility timeout override. Default: queue-configured value.").optional(),shutdownTimeoutMs:y.z.number().int().positive().describe("Graceful shutdown timeout in milliseconds. Default: 30000. After this window, destroy() force-closes.").optional(),onPushError:y.z.enum(["nack","ack"]).describe("Behavior when forwarding to the collector throws. nack (default) skips DeleteMessage so the message redelivers; ack drops it.").optional()}),v=require("@walkeros/core/dev"),b=v.z.record(v.z.string(),v.z.string()),k=v.z.object({region:v.z.string().min(1).describe("AWS region.").optional(),fifoQueue:v.z.boolean().describe("FIFO queue with content-based deduplication. Auto-appends .fifo suffix to the queue name.").optional(),visibilityTimeoutSeconds:v.z.number().int().nonnegative().describe("Visibility timeout in seconds. Default: 30.").optional(),messageRetentionSeconds:v.z.number().int().positive().describe("Message retention period in seconds. Default: 345600 (4 days).").optional(),maximumMessageSize:v.z.number().int().min(1024).max(262144).describe("Max message size in bytes. Default: 262144 (256 KB).").optional(),kmsMasterKeyId:v.z.string().describe("KMS key alias or ID for at-rest encryption.").optional(),deadLetterQueue:v.z.object({arn:v.z.string().describe("ARN of an existing DLQ. Mutually exclusive with create: true.").optional(),create:v.z.boolean().describe("Create a sibling DLQ named <queueName>-dlq. Default: false.").optional(),maxReceiveCount:v.z.number().int().min(1).max(1e3).describe("Max receive count before message goes to DLQ. Default: 5.").optional()}).describe("Optional dead-letter queue.").optional(),tags:b.describe("Tags applied to the queue (and inherited by an auto-created DLQ).").optional(),subscribeToSnsTopic:v.z.object({topicArn:v.z.string().min(1).describe("Topic ARN to subscribe to."),rawMessageDelivery:v.z.boolean().describe("Deliver SNS messages without the SNS envelope.").optional(),filterPolicy:v.z.record(v.z.string(),v.z.unknown()).describe("SNS filter policy applied at subscription level.").optional()}).describe("Optional SNS topic subscription. Creates the subscription and the matching queue policy.").optional()}),S=(0,m.zodToSchema)(w),q=(0,m.zodToSchema)(k),I={};r(I,{createTrigger:()=>_e,env:()=>O,step:()=>D,trigger:()=>He});var O={};r(O,{push:()=>j});var x=()=>()=>Promise.resolve({ok:!0}),C=()=>{},A={error:C,warn:C,info:C,debug:C,throw:e=>{throw"string"==typeof e?new Error(e):e},json:C,scope:()=>A},j={get push(){return x()},get command(){return x()},get elb(){return x()},logger:A},D={};r(D,{apiGatewayV1Post:()=>z,lambdaGet:()=>E,lambdaPost:()=>T});var T={title:"Lambda POST",description:"An API Gateway v2 HTTP POST with a JSON body is converted into a walker elb event.",trigger:{type:"POST"},in:{version:"2.0",requestContext:{http:{method:"POST",path:"/collect"},requestId:"req-123"},body:JSON.stringify({event:"page view",data:{title:"Home"}}),isBase64Encoded:!1},out:[["elb",{name:"page view",data:{title:"Home"}}]]},z={title:"API Gateway v1 POST",description:"A REST API Gateway v1 POST request with a JSON body is converted into a walker elb event.",trigger:{type:"POST"},in:{httpMethod:"POST",path:"/collect",requestContext:{requestId:"req-789",identity:{sourceIp:"203.0.113.42"}},queryStringParameters:null,body:JSON.stringify({event:"page view",data:{title:"Home"}}),isBase64Encoded:!1},out:[["elb",{name:"page view",data:{title:"Home"}}]]},E={title:"Lambda GET",description:"An API Gateway v2 HTTP GET with query parameters is parsed into an elb event payload.",trigger:{type:"GET"},in:{version:"2.0",requestContext:{http:{method:"GET",path:"/collect"},requestId:"req-456"},rawQueryString:"e=page+view&d=%7B%22title%22%3A%22Home%22%7D",isBase64Encoded:!1},out:[["elb",{e:"page view",d:'{"title":"Home"}'}]]},M=require("@walkeros/core"),P=require("@walkeros/core"),$=require("@walkeros/core"),_=(require("@walkeros/core"),require("@walkeros/core")),H=require("@walkeros/core"),N=require("@walkeros/core"),R=require("@walkeros/core"),B=require("@walkeros/core"),G=require("@walkeros/core"),F=require("@walkeros/core"),L=require("@walkeros/core"),K=require("@walkeros/core"),Q=require("@walkeros/core"),J={Action:"action",Actions:"actions",Config:"config",Consent:"consent",Context:"context",Custom:"custom",Destination:"destination",Elb:"elb",Globals:"globals",Hook:"hook",Init:"init",Link:"link",On:"on",Prefix:"data-elb",Ready:"ready",Run:"run",Session:"session",Shutdown:"shutdown",User:"user",Walker:"walker"};function U(e,t){const n=e.status.startedAt;return{flowId:"default",stepId:t.stepId,stepType:t.stepType,phase:t.phase,eventId:t.eventId,timestamp:new Date(t.now).toISOString(),elapsedMs:t.now-n}}function W(e,t){return e.storeId&&t.stores[e.storeId]?t.stores[e.storeId]:t.stores.__cache}function V(e,t){return e?t.stores[e]:t.stores.__cache}function Y(e){const t={};for(const[n,o]of Object.entries(e)){const e=o.config?.next;"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e)?t[n]={next:e}:t[n]={}}return t}function X(e,t){const n=e.config||{},o=e[t];return void 0!==o?{config:{...n,[t]:o},chainValue:o}:{config:n,chainValue:void 0}}function Z(e,t={}){if(!e)return[];if(Array.isArray(e))return e;const n=[],o=new Set;let s=e;for(;s&&t[s]&&!o.has(s);){o.add(s),n.push(s);const e=t[s].next;if(Array.isArray(e)){n.push(...e);break}s=e}return n}async function ee(e,t,n){if(t.init&&!t.config.init){const o=t.type||"unknown",s=e.logger.scope(`transformer:${o}`),r={collector:e,logger:s,id:n,ingest:(0,R.createIngest)(n),config:t.config,env:se(t.config.env)};s.debug("init");const i=await(0,R.useHooks)(t.init,"TransformerInit",e.hooks,e.logger)(r);if(!1===i)return!1;t.config={...i||t.config,env:i?.env||t.config.env,init:!0},s.debug("init done")}return!0}async function te(e,t,n,o,s,r){const i=t.type||"unknown",a=e.logger.scope(`transformer:${i}`),c={collector:e,logger:a,id:n,ingest:s,config:t.config,env:{...se(t.config.env),...r?{respond:r}:{}}};a.debug("push",{event:o.name});const u="string"==typeof o.id?o.id:"",d=Date.now(),l=U(e,{stepId:(0,R.stepId)("transformer",n),stepType:"transformer",phase:"in",eventId:u,now:d});(0,R.emitStep)(e,l);try{const s=await(0,R.useHooks)(t.push,"TransformerPush",e.hooks,e.logger)(o,c),r=Date.now(),i=U(e,{stepId:(0,R.stepId)("transformer",n),stepType:"transformer",phase:"out",eventId:u,now:r});return i.durationMs=r-d,i.outEvent=s,(0,R.emitStep)(e,i),a.debug("push done"),s}catch(t){const o=Date.now(),s=U(e,{stepId:(0,R.stepId)("transformer",n),stepType:"transformer",phase:"error",eventId:u,now:o});throw s.durationMs=o-d,s.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},(0,R.emitStep)(e,s),t}}function ne(e,t){return e?{...e,_meta:{...e._meta,path:[...e._meta.path]}}:(0,R.createIngest)(t)}async function oe(e,t,n,o,s,r,i){s||(s=(0,R.createIngest)(n[0]??"chain")),i&&s._meta&&(s._meta.chainPath=i);let a=o,c=r;for(const o of n){const r=t[o];if(!r){e.logger.warn(`Transformer not found: ${o}`);continue}if(s&&s._meta&&s._meta.path.length>256)return e.logger.error(`Max path length exceeded at ${o}`),{event:null,respond:c};if(s&&s._meta&&(s._meta.hops++,s._meta.path.push(o)),!await(0,R.tryCatchAsync)(ee,t=>{if(t instanceof R.FatalError)throw t;return e.status.failed++,e.logger.scope(`transformer:${r.type||"unknown"}`).error("transformer init failed",{transformer:o,error:t}),!1})(e,r,o))return{event:null,respond:c};if(i&&void 0!==r.config?.chainMocks?.[i]){const t=r.config.chainMocks[i];e.logger.scope(`transformer:${r.type||"unknown"}`).debug("chainMock",{chain:i}),a=t;continue}if(void 0!==r.config?.mock){e.logger.scope(`transformer:${r.type||"unknown"}`).debug("mock"),a=r.config.mock;continue}if(r.config?.disabled)continue;const u=r.config?.cache,d=u?(0,R.compileCache)(u):void 0,l=d?W(d,e):void 0,p=r.config?.state?(0,R.compileState)(r.config.state):void 0,f=p?.filter(e=>"get"===e.mode),g=p?.filter(e=>"set"===e.mode);let h;if(d&&l){const e=(0,R.buildCacheContext)(s,a),t=await(0,R.checkCache)(d,l,e);if("HIT"===t?.status&&t.value){if(a=t.value,d.stop)return{event:a,respond:c,stopped:!0};continue}"MISS"===t?.status&&(h={key:t.key,ttl:t.rule.ttl})}const m=r.config.before;if(m){const n=(0,R.getNextSteps)(m,(0,R.buildCacheContext)(s,a));if(1===n.length){const o=Z(n[0],Y(t));if(o.length>0){const n=await oe(e,t,o,a,s,c,i);if(null===n.event)return{event:null,respond:n.respond??c};if(n.stopped)return{event:Array.isArray(n.event)?n.event[0]:n.event,respond:n.respond??c,stopped:!0};n.respond&&(c=n.respond),a=Array.isArray(n.event)?n.event[0]:n.event}}else n.length>1&&await Promise.all(n.map(n=>(0,R.tryCatchAsync)(oe,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,Z(n,Y(t)),a,ne(s,n),void 0,i)))}f&&f.length>0&&(a=await(0,R.applyState)(f,t=>V(t,e),a,e));const y=await(0,R.tryCatchAsync)(te,t=>(e.logger.scope(`transformer:${r.type||"unknown"}`).error("Push failed",{error:t}),!1))(e,r,o,a,s,c);if(!1===y)return{event:null,respond:c};if(Array.isArray(y)){const r=n.slice(n.indexOf(o)+1),u=await Promise.all(y.map(async n=>{const o=n.event||a,u=ne(s,"unknown");if(n.next){const s=(0,R.getNextSteps)(n.next,(0,R.buildCacheContext)(u,o));if(0===s.length)return{event:o,respond:c};if(1===s.length){const n=Z(s[0],Y(t));return n.length>0?oe(e,t,n,o,u,c,i):{event:o,respond:c}}return(await Promise.all(s.map(n=>(0,R.tryCatchAsync)(oe,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,Z(n,Y(t)),o,ne(u,n),void 0,i)))).map(e=>({event:e.event,respond:void 0}))}return r.length>0?oe(e,t,r,o,u,c,i):{event:o,respond:c}}));let d=c;const l=[];for(const e of u.flat())if(null!==e)if(e&&"object"==typeof e&&"event"in e){const t=e;if(t.respond&&(d=t.respond),null===t.event)continue;Array.isArray(t.event)?l.push(...t.event):l.push(t.event)}else l.push(e);return 0===l.length?{event:null,respond:d}:1===l.length?{event:l[0],respond:d}:{event:l,respond:d}}if(y&&"object"==typeof y){const{event:n,respond:o,next:r}=y;if(o&&(c=o),void 0!==r){const o=(0,R.getNextSteps)(r,(0,R.buildCacheContext)(s,a));if(0===o.length){n&&(a=n);continue}if(1===o.length){const u=Z(o[0],Y(t));return u.length>0?oe(e,t,u,n||a,s,c,i):(e.logger.warn(`Branch target not found: ${JSON.stringify(r)}`),{event:null,respond:c})}return await Promise.all(o.map(o=>(0,R.tryCatchAsync)(oe,t=>(e.logger.scope("transformer:many").error(`many branch ${o} failed`,{error:t}),{event:null,respond:void 0}))(e,t,Z(o,Y(t)),n||a,ne(s,o),void 0,i))),{event:null,respond:void 0}}n&&(a=n)}g&&g.length>0&&(a=await(0,R.applyState)(g,t=>V(t,e),a,e)),h&&l&&(0,R.storeCache)(l,h.key,a,h.ttl);const w=r.config.next,v="string"==typeof w||Array.isArray(w)&&w.every(e=>"string"==typeof e),b=void 0!==w&&!v;if((!y||"object"==typeof y&&!y.next)&&b){const n=(0,R.getNextSteps)(r.config.next,(0,R.buildCacheContext)(s,a));if(1===n.length){const o=Z(n[0],Y(t));return o.length>0?oe(e,t,o,a,s,c,i):{event:a,respond:c}}return n.length>1?(await Promise.all(n.map(n=>(0,R.tryCatchAsync)(oe,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,Z(n,Y(t)),a,ne(s,n),void 0,i))),{event:null,respond:void 0}):{event:a,respond:c}}}return{event:a,respond:c}}function se(e){return e&&(0,R.isObject)(e)?e:{}}function re(e){return"string"==typeof e||!(!Array.isArray(e)||!e.every(e=>"string"==typeof e))}async function ie(e,t,n){if(!t.on||!t.queueOn?.length)return;const o=t.queueOn;t.queueOn=[];const s=n||t.config?.id||"unknown";for(const{type:n,data:r}of o)await(0,N.tryCatchAsync)(t.on,t=>{if(t instanceof N.FatalError)throw t;e.status.failed++,e.logger.scope("source").error("source on flush failed",{sourceId:s,type:n,error:t})})(n,r)}function ae(e){return Boolean(e.config.init)&&!e.config.require?.length}async function ce(e,t,n){const{code:o,config:s={},env:r={},primary:i,next:a,before:c,cache:u}=n,d=s.state??n.state,l=d?(0,N.compileState)(d):void 0,p=u,f=p?(0,N.compileCache)({...p,stop:p.stop??!0}):void 0,g=re(a)?Z(a,Y(e.transformers)):void 0,h=re(c)?Z(c,Y(e.transformers)):void 0,m=r.push,y=m??e.push,w=Boolean(m),v=async(n,o,r)=>{let i;const u=h??(void 0!==c?(()=>{const t=(0,N.getNextSteps)(c,(0,N.buildCacheContext)(r.ingest));return 0===t.length?[]:Z(1===t.length?t[0]:t,Y(e.transformers))})():[]);let d=[n];if(u.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const o=await oe(e,e.transformers,u,n,r.ingest,r.respond,`source.${t}.before`);if(null===o.event)return{ok:!0};if(o.stopped)return o.respond&&(r.respond=o.respond),{ok:!0};o.respond&&(r.respond=o.respond),d=Array.isArray(o.event)?o.event:[o.event]}if(f){const t=W(f,e);if(t){const n=(0,N.buildCacheContext)(r.ingest),o=await(0,N.checkCache)(f,t,n);if(o){if("HIT"===o.status&&void 0!==o.value&&f.stop){let t=o.value;return o.rule.update&&(t=await(0,N.applyUpdate)(t,o.rule.update,{...n,cache:{status:"HIT"}},e)),r.respond?.(t),{ok:!0}}if("MISS"===o.status&&f.stop&&r.respond){const s=r.respond,a=o.rule.update,c={...n,cache:{status:"MISS"}},u=o.key,d=o.rule.ttl,l=n=>{(0,N.storeCache)(t,u,n,d),a?i=(async()=>{const t=await(0,N.applyUpdate)(n,a,c,e);s(t)})():s(n)};r.respond=l}"MISS"!==o.status||f.stop||(0,N.storeCache)(t,o.key,!0,o.rule.ttl)}}}const p=g?{kind:"single",preChain:g}:void 0!==a?(()=>{const t=(0,N.getNextSteps)(a,(0,N.buildCacheContext)(r.ingest));return 0===t.length?{kind:"single",preChain:[]}:1===t.length?{kind:"single",preChain:Z(t[0],Y(e.transformers))}:{kind:"many",branches:t.map(t=>Z(t,Y(e.transformers)))}})():{kind:"single",preChain:[]};l&&l.length>0&&(d=await Promise.all(d.map(t=>(0,N.applyState)(l,t=>V(t,e),t,e))));let m={ok:!0};for(const n of d)"many"===p.kind?(await Promise.all(p.branches.map((i,a)=>(0,N.tryCatchAsync)(async()=>w?y(n):y(n,{...o,id:t,ingest:ne(r.ingest,`${t}.${a}`),respond:void 0,mapping:s,preChain:i}),t=>(e.logger.scope("source:many").error(`many branch ${a} failed`,{error:t}),{ok:!0}))())),m={ok:!0}):m=w?await y(n):await y(n,{...o,id:t,ingest:r.ingest,respond:r.respond,mapping:s,preChain:p.preChain});return i&&await i,m},b=async n=>{const o=(0,N.createIngest)(t);if(!s.ingest||void 0===n)return o;const r=await(0,N.getMappingValue)(n,s.ingest,{collector:e});return{...o,...r,_meta:o._meta}},k=e.logger.scope("source").scope(t),S={command:e.command,sources:e.sources,elb:e.sources.elb.push,logger:k,...r,push:async(e,n={})=>{const o={ingest:(0,N.createIngest)(t),respond:void 0};return v(e,n,o)}},q={collector:e,logger:k,id:t,config:s,env:S,withScope:async(e,t,n)=>{const o={ingest:await b(e),respond:t};return n({...S,push:(e,t={})=>v(e,t,o),ingest:o.ingest,respond:o.respond})}},I=await(0,N.tryCatchAsync)(o,n=>{if(n instanceof N.FatalError)throw n;e.status.failed++,e.logger.scope("source").error("source factory failed",{sourceId:t,error:n})})(q);if(!I)return;const O=I.type||"unknown",x=e.logger.scope(O).scope(t);return S.logger=x,i&&(I.config={...I.config,primary:i}),I}function ue(e,t,n,o){if(n instanceof _.FatalError)throw n;e.logger.scope("on").error("on callback failed",{kind:t,...o,error:n})}function de(e,t){return{collector:e,logger:e.logger.scope("on").scope(String(t))}}function le(e,t,n,o,s){if(!t.on)return;const r=t.type||"unknown",i=e.logger.scope(r).scope("on").scope(o),a={collector:e,logger:i,id:n,config:t.config,data:s,env:Ae(t.env,t.config.env)};(0,H.tryCatch)(t.on,t=>ue(e,"destination",t,{destId:n,type:o}))(o,a)}function pe(e,t,n,o){let s;switch(t){case J.Consent:s=o||e.consent;break;case J.Session:s=e.session;break;case J.User:s=o||e.user;break;case J.Custom:s=o||e.custom;break;case J.Globals:s=o||e.globals;break;case J.Config:s=o||e.config;break;case J.Ready:case J.Run:default:s=void 0}if(n.length)switch(t){case J.Consent:!function(e,t,n){const o=n||e.consent,s=de(e,J.Consent);t.forEach(t=>{Object.keys(o).filter(e=>e in t).forEach(n=>{(0,H.tryCatch)(t[n],t=>ue(e,"consent",t,{key:n}))(o,s)})})}(e,n,o);break;case J.Ready:!function(e,t){if(!e.allowed)return;const n=de(e,J.Ready);t.forEach(t=>{(0,H.tryCatch)(t,t=>ue(e,"ready",t))(void 0,n)})}(e,n);break;case J.Run:!function(e,t){if(!e.allowed)return;const n=de(e,J.Run);t.forEach(t=>{(0,H.tryCatch)(t,t=>ue(e,"run",t))(void 0,n)})}(e,n);break;case J.Session:!function(e,t){if(!e.session)return;const n=de(e,J.Session);t.forEach(t=>{(0,H.tryCatch)(t,t=>ue(e,"session",t))(e.session,n)})}(e,n);break;default:{const o=de(e,t);n.forEach(n=>{"function"==typeof n&&(0,H.tryCatch)(n,n=>ue(e,"generic",n,{type:t}))(s,o)});break}}}function fe(e,t,n,o){if(!Number.isFinite(n.max)||n.max<=0)throw new Error(`pushBounded: max must be > 0 (got ${n.max})`);if("dropNewest"===(n.onOverflow??"dropOldest"))return e.length>=n.max?(o&&o([t]),{appended:!1,dropped:1}):(e.push(t),{appended:!0,dropped:0});const s=[];for(;e.length>=n.max;)s.push(e.shift());return e.push(t),s.length>0&&o&&o(s),{appended:!0,dropped:s.length}}var ge=new WeakMap;function he(e,t,n,o){ge.get(e)||(ge.set(e,!0),t.warn(n,o))}function me(e){ge.delete(e)}var ye=Object.freeze({batched:!0});function we(e){return e===ye}function ve(e){return void 0===e?{}:"number"==typeof e?{wait:e}:{wait:e.wait,size:e.size,age:e.age}}function be(e,t){return e.status.destinations[t]||(e.status.destinations[t]={count:0,failed:0,duration:0,queuePushSize:0,dlqSize:0}),e.status.destinations[t]}function ke(e,t,n,o){e.dropped[t]||(e.dropped[t]={});const s=e.dropped[t];return s[n]=(s[n]??0)+o,s[n]}function Se(e,t,n){if(!e)return[];if(Array.isArray(e)&&e.every(e=>"string"==typeof e))return Z(e,t);if("string"==typeof e)return Z(e,t);const o=(0,$.getNextSteps)(e,(0,$.buildCacheContext)(n));return 0===o.length?[]:1===o.length?Z(o[0],t):Z(o,t)}async function qe(e,t,n={},o){const{allowed:s,consent:r,globals:i,user:a}=e;if(!s)return xe({ok:!1});if(t){const n=e.config.queueMax;if(void 0===n)throw new Error("Collector.Config.queueMax is undefined; defaults must be seeded by collector()");const o=fe(e.queue,t,{max:n});if(o.dropped>0){const t=ke(e.status,(0,$.stepId)("collector"),"queue",o.dropped);he(e.queue,e.logger,"collector.queue overflow; oldest events dropped",{buffer:"queue",cap:n,droppedCount:t})}else e.queue.length<n&&me(e.queue);e.status.in++}o||(o=e.destinations);const c=e.transformers?Y(e.transformers):{},u=await Promise.all(Object.entries(o||{}).map(async([o,s])=>{if(s.config.disabled)return{id:o,destination:s,skipped:!0};let u=(s.queuePush||[]).map(e=>({...e,consent:r}));s.queuePush=[],t&&u.push((0,$.clone)(t));const d=n.ingest?{...n.ingest,_meta:{...n.ingest._meta,path:[...n.ingest._meta.path]}}:(0,$.createIngest)("unknown");if(!u.length&&!s.queueOn?.length)return{id:o,destination:s,skipped:!0};if(!u.length&&s.queueOn?.length){let t=!1;try{t=await Ie(e,s,o)}catch(t){e.status.failed++;const n=s.type||"unknown";e.logger.scope(n).error("destination init failed",{error:t instanceof Error?t.message:String(t)})}return{id:o,destination:s,skipped:!t}}const l=[],p=u.filter(t=>{const n=(0,$.getGrantedConsent)(s.config.consent,r,t.consent);if(n)return t.consent=n,l.push(t),!1;const i=U(e,{stepId:(0,$.stepId)("destination",o),stepType:"destination",phase:"skip",eventId:"string"==typeof t.id?t.id:"",now:Date.now()});return i.skipReason="consent",r&&(i.consent={...r}),s.config.consent&&(i.meta={required:{...s.config.consent}}),(0,$.emitStep)(e,i),!0});if(p.length>0){const t=s.queuePush,n=s.config.id||o,r={max:s.config.queueMax??1e3};let i=0;for(const e of p)i+=fe(t,e,r).dropped;if(i>0){be(e,n);const o=ke(e.status,(0,$.stepId)("destination",n),"queue",i);he(t,e.logger.scope(s.type||"unknown"),"destination.queuePush overflow; oldest events dropped",{buffer:"queuePush",destination:n,cap:r.max,droppedCount:o})}else t.length<r.max&&me(t)}if(!l.length)return{id:o,destination:s,queue:u};let f,g,h=!1;try{h=await Ie(e,s,o)}catch(t){e.status.failed++;const n=s.type||"unknown";e.logger.scope(n).error("destination init failed",{error:t instanceof Error?t.message:String(t)})}if(!h)return{id:o,destination:s,queue:u};s.dlq||(s.dlq=[]);const m=Se(s.config.before,c,d),y=s.config.next,w=s.config?.cache,v=w?(0,$.compileCache)(w):void 0,b=v?W(v,e):void 0,k=s.config?.state?(0,$.compileState)(s.config.state):void 0,S=k?.filter(e=>"get"===e.mode),q=k?.filter(e=>"set"===e.mode);let I=0,O=0;return await Promise.all(l.map(async t=>{let r;if(t.globals=(0,$.assign)(i,t.globals),t.user=(0,$.assign)(a,t.user),v?.stop&&b){const e=(0,$.buildCacheContext)(d,t),n=await(0,$.checkCache)(v,b,e);if("HIT"===n?.status)return t;"MISS"===n?.status&&(r={key:n.key,ttl:n.rule.ttl})}let u=t,l=n.respond;if(m.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const s=await oe(e,e.transformers,m,t,d,n.respond,`destination.${o}.before`);if(null===s.event)return t;s.respond&&(l=s.respond),u=Array.isArray(s.event)?s.event[0]:s.event}if(v&&!v.stop&&b){const e=(0,$.buildCacheContext)(d,u),n=await(0,$.checkCache)(v,b,e);if("HIT"===n?.status)return t;"MISS"===n?.status&&(r={key:n.key,ttl:n.rule.ttl})}S&&S.length>0&&u&&(u=await(0,$.applyState)(S,t=>V(t,e),u,e));const p=Date.now();let h=!1;const w=await(0,$.tryCatchAsync)(Oe,t=>{const n=s.type||"unknown";e.logger.scope(n).error("Push failed",{error:t,event:u.name}),f=t,h=!0;const r=s.dlq,i=s.config.id||o,a={max:s.config.dlqMax??100},c=fe(r,[u,t],a);if(c.dropped>0){be(e,i);const t=ke(e.status,(0,$.stepId)("destination",i),"dlq",c.dropped);he(r,e.logger.scope(s.type||"unknown"),"destination.dlq overflow; oldest entries dropped",{buffer:"dlq",destination:i,cap:a.max,droppedCount:t})}else r.length<a.max&&me(r)})(e,s,o,u,d,l);if(I+=Date.now()-p,r&&b&&void 0===s.config.mock&&(0,$.storeCache)(b,r.key,w??!0,r.ttl),!h&&q&&q.length>0&&u&&(u=await(0,$.applyState)(q,t=>V(t,e),u,e)),void 0===w||we(w)||(g=w),we(w)&&O++,!h&&y){void 0!==w&&(d._response=w);const t=Se(y,c,d);if(t.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const n=await oe(e,e.transformers,t,u,d,l,`destination.${o}.next`);n.respond&&(l=n.respond)}}return t})),{id:o,destination:s,error:f,response:g,totalDuration:I,batchedCount:O,allowedCount:l.length}})),d={},l={},p={};for(const t of u){if(t.skipped)continue;const n=t.destination,o={type:n.type||"unknown",data:t.response};be(e,t.id);const s=e.status.destinations[t.id],r=Date.now();if(s.queuePushSize=n.queuePush?.length??0,s.dlqSize=n.dlq?.length??0,t.error)o.error=t.error,p[t.id]=o,s.failed++,s.lastAt=r,s.duration+=t.totalDuration||0,e.status.failed++;else if(t.queue&&t.queue.length)l[t.id]=o;else{const n=t.batchedCount??0,i=t.allowedCount??0;(Math.max(0,i-n)>0||0===i)&&(d[t.id]=o,s.count++,s.lastAt=r,s.duration+=t.totalDuration||0,e.status.out++)}}return xe({event:t,...Object.keys(d).length&&{done:d},...Object.keys(l).length&&{queued:l},...Object.keys(p).length&&{failed:p}})}async function Ie(e,t,n){if(t.init&&!t.config.init){const o=t.type||"unknown",s=e.logger.scope(o),r={collector:e,logger:s,id:n,config:t.config,env:Ae(t.env,t.config.env)};s.debug("init");const i=Date.now();let a;(0,$.emitStep)(e,U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"init",eventId:"",now:i}));try{a=await(0,$.useHooks)(t.init,"DestinationInit",e.hooks,e.logger)(r)}catch(t){const o=Date.now(),s=U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"error",eventId:"",now:o});throw s.durationMs=o-i,s.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},(0,$.emitStep)(e,s),t}if(!1===a)return a;if(t.config={...a||t.config,init:!0},t.queueOn?.length){const o=t.queueOn;t.queueOn=[];for(const{type:s,data:r}of o)le(e,t,n,s,r)}s.debug("init done")}return!0}async function Oe(e,t,n,o,s,r){const{config:i}=t,a=await(0,$.processEventMapping)(o,i,e);if(a.ignore)return!1;const c=t.type||"unknown",u=e.logger.scope(c),d={collector:e,logger:u,id:n,config:i,data:a.data,rule:a.mapping,ingest:s,env:{...Ae(t.env,i.env),...r?{respond:r}:{}}};if(void 0!==i.mock)return u.debug("mock",{event:a.event.name}),i.mock;const l=a.mapping,p=a.mappingKey||"* *";if(l?.batch&&t.pushBatch&&void 0===i.mock){if(t.batches=t.batches||{},!t.batches[p]){const o={key:p,entries:[],events:[],data:[]},s=ve(l.batch),r=ve(i.batch),a=s.wait??r.wait??3e4,c=s.size??r.size??1e3,d=s.age??r.age??3e4,f=Ae(t.env,i.env),g=(0,$.debounce)(async()=>{const o=t.batches[p].batched;if(0===o.entries.length)return;const s={key:o.key,entries:o.entries,events:o.events,data:o.data};o.entries=[],o.events=[],o.data=[];const r=s.entries[0],a={collector:e,logger:u,id:n,config:i,data:void 0,rule:r.rule,ingest:r.ingest,env:{...f,...r.respond?{respond:r.respond}:{}}};u.debug("push batch",{events:s.entries.length});const c=t.config.id||n,d=be(e,c),l=Date.now(),g=U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"flush",eventId:"",now:l});g.batch={size:s.entries.length,index:0},(0,$.emitStep)(e,g);let h=!0;await(0,$.tryCatchAsync)((0,$.useHooks)(t.pushBatch,"DestinationPushBatch",e.hooks,e.logger),o=>{h=!1;const r=Date.now(),i=U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"error",eventId:"",now:r});i.durationMs=r-l,i.error=o instanceof Error?{name:o.name,message:o.message}:{message:String(o)},i.batch={size:s.entries.length,index:0},(0,$.emitStep)(e,i);const a=t.dlq=t.dlq||[],p={max:t.config.dlqMax??100};let f=0;for(const e of s.entries)f+=fe(a,[e.event,o],p).dropped;if(f>0){const t=ke(e.status,(0,$.stepId)("destination",c),"dlq",f);he(a,u,"destination.dlq overflow; oldest entries dropped",{buffer:"dlq",destination:c,cap:p.max,droppedCount:t})}else a.length<p.max&&me(a);d.failed+=s.entries.length,d.dlqSize=a.length,e.status.failed+=s.entries.length,u.error("Push batch failed",{error:o instanceof Error?o.message:String(o),entries:s.entries.length})})(s,a),u.debug("push batch done"),d.inFlightBatch=Math.max(0,(d.inFlightBatch??0)-s.entries.length),h&&(d.count+=s.entries.length,d.lastAt=Date.now(),e.status.out+=s.entries.length)},{wait:a,size:c,age:d});t.batches[p]={batched:o,batchFn:()=>{g()},flush:async()=>{await g.flush()}}}const o=t.batches[p];o.batched.entries.push({event:a.event,ingest:s,respond:r,rule:l,data:a.data}),o.batched.events.push(a.event),(0,$.isDefined)(a.data)&&o.batched.data.push(a.data);const c=t.config.id||n,d=be(e,c);return d.inFlightBatch=(d.inFlightBatch??0)+1,o.batchFn(),ye}{u.debug("push",{event:a.event.name});const o="string"==typeof a.event.id?a.event.id:"",s=Date.now(),r=U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"in",eventId:o,now:s});a.mappingKey&&(r.mappingKey=a.mappingKey),a.event.consent&&(r.consent={...a.event.consent}),(0,$.emitStep)(e,r);try{const r=await(0,$.useHooks)(t.push,"DestinationPush",e.hooks,e.logger)(a.event,d),i=Date.now(),c=U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"out",eventId:o,now:i});return c.durationMs=i-s,c.outEvent=r,a.mappingKey&&(c.mappingKey=a.mappingKey),(0,$.emitStep)(e,c),u.debug("push done"),r}catch(t){const r=Date.now(),i=U(e,{stepId:(0,$.stepId)("destination",n),stepType:"destination",phase:"error",eventId:o,now:r});throw i.durationMs=r-s,i.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},a.mappingKey&&(i.mappingKey=a.mappingKey),(0,$.emitStep)(e,i),t}}}function xe(e){return{ok:!e?.failed,...e}}function Ce(e){const{code:t,config:n={},env:o={},cache:s,state:r}=e,{config:i}=X(e,"before"),{config:a}=X({...e,config:i},"next"),c={...t.config,...n,...a};s&&(c.cache=s),void 0!==r&&void 0===c.state&&(c.state=r);const u=Ae(t.env,o);return{...t,config:c,env:u}}function Ae(e,t){return e||t?t?e&&(0,$.isObject)(e)&&(0,$.isObject)(t)?{...e,...t}:t:e:{}}async function je(e,t,n){const o=Object.entries(e).map(async([e,o])=>{const s=o.destroy;if(!s)return;const r=o.type||"unknown",i=n.scope(r),a={id:e,config:o.config,env:o.env??{},logger:i};try{await Promise.race([s(a),new Promise((n,o)=>setTimeout(()=>o(new Error(`${t} '${e}' destroy timed out`)),5e3))])}catch(n){i.error(`${t} '${e}' destroy failed: ${n}`)}});await Promise.allSettled(o)}async function De(e,t,n){let o,s,r=!1;switch(t){case J.Config:(0,G.isObject)(n)&&((0,B.assign)(e.config,n,{shallow:!1}),s=n,r=!0);break;case J.Consent:if((0,G.isObject)(n)){const{update:t}=function(e,t){const n={};return Object.entries(t).forEach(([e,t])=>{n[e]=!!t}),e.consent=(0,M.assign)(e.consent,n),{update:n}}(e,n);s=t,r=!0}break;case J.Custom:(0,G.isObject)(n)&&(e.custom=(0,B.assign)(e.custom,n),s=n,r=!0);break;case J.Destination:(0,G.isObject)(n)&&"code"in n&&(0,G.isObject)(n.code)&&(o=await async function(e,t){const{code:n,config:o={},env:s={},before:r,next:i,cache:a,state:c}=t;if(!(0,$.isFunction)(n.push))return xe({ok:!1,failed:{invalid:{type:"invalid",error:"Destination code must have a push method"}}});const u=o||{init:!1};let d=r?{...u,before:r}:{...u};i&&(d={...d,next:i}),a&&(d={...d,cache:a}),void 0!==c&&void 0===d.state&&(d={...d,state:c});const l={...n,config:d,env:Ae(n.env,s)};let p=l.config.id;if(!p)do{p=(0,$.getId)(5,"abcdefghijklmnopqrstuvwxyz")}while(e.destinations[p]);return e.destinations[p]=l,!1!==l.config.queue&&(l.queuePush=[...e.queue]),qe(e,void 0,{},{[p]:l})}(e,n));break;case J.Globals:(0,G.isObject)(n)&&(e.globals=(0,B.assign)(e.globals,n),s=n,r=!0);break;case J.Hook:if((0,G.isObject)(n)&&(0,B.isString)(n.name)&&(0,B.isFunction)(n.fn)){const{name:t,fn:o}=n;e.hooks[t]=o,s=n,r=!0}break;case J.On:if((0,G.isObject)(n)&&(0,B.isString)(n.type)){const{type:t,rules:o}=n;await async function(e,t,n){const o=e.on,s=o[t]||[],r=(0,_.isArray)(n)?n:[n];r.forEach(e=>{s.push(e)}),o[t]=s,pe(e,t,r)}(e,t,o)}break;case J.Ready:r=!0;break;case J.Run:o=await async function(e,t){return e.allowed=!0,e.timing=Date.now(),t&&(t.consent&&(e.consent=(0,B.assign)(e.consent,t.consent)),t.user&&(e.user=(0,B.assign)(e.user,t.user)),t.globals&&(e.globals=(0,B.assign)(e.config.globalsStatic||{},t.globals)),t.custom&&(e.custom=(0,B.assign)(e.custom,t.custom))),Object.values(e.destinations).forEach(e=>{e.queuePush=[]}),e.queue=[],e.round++,await qe(e)}(e,n),r=!0;break;case J.Session:r=!0;break;case J.Shutdown:await async function(e){const t=e.logger;await je(e.sources,"source",t),await je(e.destinations,"destination",t),await je(e.transformers,"transformer",t),await je(e.stores,"store",t)}(e);break;case J.User:(0,G.isObject)(n)&&((0,B.assign)(e.user,n,{shallow:!1}),s=n,r=!0)}return r&&(await async function(e,t,n,o){let s,r=n||[];switch(n||(r=e.on[t]||[]),t){case J.Consent:s=o||e.consent;break;case J.Session:s=e.session;break;case J.User:s=o||e.user;break;case J.Custom:s=o||e.custom;break;case J.Globals:s=o||e.globals;break;case J.Config:s=o||e.config;break;case J.Ready:case J.Run:default:s=void 0}let i=!1;for(const[n,o]of Object.entries(e.sources)){if(o.config.require?.length){const e=o.config.require.indexOf(t);-1!==e&&o.config.require.splice(e,1)}o.on&&(ae(o)?!1===await(0,H.tryCatchAsync)(o.on,o=>ue(e,"source",o,{sourceId:n,type:t}))(t,s)&&(i=!0):(o.queueOn=o.queueOn||[],o.queueOn.push({type:t,data:s})))}Object.entries(e.destinations).forEach(([n,o])=>{if(o.on){if(!o.config.init)return o.queueOn=o.queueOn||[],void o.queueOn.push({type:t,data:s});le(e,o,n,t,s)}});for(const[t,n]of Object.entries(e.sources))ae(n)&&n.queueOn?.length&&await ie(e,n,t);return Object.keys(e.pending.destinations).length>0&&await async function(e,t){for(const[n,o]of Object.entries(e.pending.destinations)){if(!e.pending.destinations[n]||e.destinations[n])continue;const s=o.config?.require;if(!s)continue;const r=s.indexOf(t);if(-1===r)continue;if(s.splice(r,1),s.length>0)continue;delete e.pending.destinations[n];const i=Ce(o);!1!==i.config.queue&&(i.queuePush=[...e.queue]),e.destinations[n]=i}}(e,t),pe(e,t,r,o),!i}(e,t,void 0,s),o=await qe(e)),o||xe({ok:!0})}function Te(e,t){if(!t.name)throw new Error("Event name is required");const[n,o]=t.name.split(" ");if(!n||!o)throw new Error("Event name is invalid");const{timestamp:s=Date.now(),name:r=`${n} ${o}`,data:i={},context:a={},globals:c=e.globals,custom:u={},user:d=e.user,nested:l=[],consent:p=e.consent,id:f=(0,B.getSpanId)(),trigger:g="",entity:h=n,action:m=o,timing:y=0,source:w={type:"collector",schema:"4"}}=t;return{name:r,data:i,context:a,globals:c,custom:u,user:d,nested:l,consent:p,id:f,trigger:g,entity:h,action:m,timestamp:s,timing:y,source:w}}function ze(e={}){const t=e.maxEntries??1e4,n=e.lowWaterMark??.8,o=e.sweepIntervalMs??6e4,s=Math.floor(t*n),r=new Map,i={hits:0,misses:0,populates:0,writes:0,deletes:0,evictions_entries:0,evictions_ttl:0};let a;return o>0&&(a=setInterval(function(){const e=Date.now();let t=0;for(const[n,o]of r)void 0!==o.expires&&o.expires<=e&&(r.delete(n),t++);i.evictions_ttl+=t},o),a&&"function"==typeof a.unref&&a.unref()),{type:"memory",config:{},get(e){const t=r.get(e);if(t)return void 0!==t.expires&&t.expires<=Date.now()?(r.delete(e),i.evictions_ttl++,void i.misses++):(r.delete(e),r.set(e,t),i.hits++,t.value);i.misses++},set(e,n,o){const a=!r.has(e);a||r.delete(e),r.set(e,{value:n,expires:void 0!==o?Date.now()+o:void 0}),i.writes++,a&&i.populates++,r.size>t&&function(){if(r.size<=t)return;const e=r.size-s;let n=0;for(const t of r.keys()){if(n>=e)break;r.delete(t),n++}i.evictions_entries+=n}()},delete(e){r.delete(e)&&i.deletes++},get counters(){return{...i}},destroy(){void 0!==a&&(clearInterval(a),a=void 0),r.clear()}}}function Ee(e,t){const{cacheConfig:n,cacheStore:o,namespace:s,logger:r,storeId:i,collector:a}=t,c=(e,t)=>{if(!a)return;const n=U(a,{stepId:`store.${i}`,stepType:"store",phase:"in",eventId:"",now:Date.now()});n.meta={op:"cache",cached:"hit"===t,status:t,key:e},(0,Q.emitStep)(a,n)},u={hits:0,misses:0,populates:0,writes:0,deletes:0,inflight_dedups:0},d=n.rules.map(e=>({match:e.match?(0,Q.compileMatcher)(e.match):()=>!0,ttl:e.ttl})),l=e=>`${s}:${e}`;function p(e,t){const n=void 0===t?{key:e}:{key:e,value:t};return d.find(e=>e.match(n))}const f=new Map;return{type:e.type,config:e.config,setup:e.setup,get counters(){return{...u}},async get(t){const n=l(t),s=await o.get(n);if(void 0!==s)return u.hits++,c(t,"hit"),s;const r=f.get(n);if(r)return u.inflight_dedups++,c(t,"hit"),r;u.misses++,c(t,"miss");const i=(async()=>{try{const s=await e.get(t);if(void 0===s)return;const r=p(t,s);if(r)try{await o.set(n,s,1e3*r.ttl),u.populates++}catch(e){g("set",t,e)}return s}finally{f.delete(n)}})();return f.set(n,i),i},async set(t,n,s){u.writes++,await e.set(t,n,s);const r=p(t,n);if(r)try{await o.set(l(t),n,1e3*r.ttl)}catch(e){g("set",t,e)}},async delete(t){u.deletes++,await e.delete(t);try{await o.delete(l(t))}catch(e){g("delete",t,e)}}};function g(e,t,n){const o=`store-cache(${i}): cache ${e} failed for "${t}"; backing succeeded, continuing`;r?r.warn(o,{error:n}):console.warn(o,n)}}function Me(e,t,n){const o=`store.${n}`,s=(0,K.useHooks)(t.get,"StoreGet",e.hooks,e.logger),r=(0,K.useHooks)(t.set,"StoreSet",e.hooks,e.logger),i=(0,K.useHooks)(t.delete,"StoreDelete",e.hooks,e.logger);t.get=async t=>{const n=Date.now(),r=U(e,{stepId:o,stepType:"store",phase:"in",eventId:"",now:n});r.meta={op:"get",key:t},(0,K.emitStep)(e,r);try{const r=await s(t),i=Date.now(),a=U(e,{stepId:o,stepType:"store",phase:"out",eventId:"",now:i});return a.durationMs=i-n,a.meta={op:"get",key:t},(0,K.emitStep)(e,a),r}catch(s){const r=Date.now(),i=U(e,{stepId:o,stepType:"store",phase:"error",eventId:"",now:r});throw i.durationMs=r-n,i.meta={op:"get",key:t},i.error=s instanceof Error?{name:s.name,message:s.message}:{message:String(s)},(0,K.emitStep)(e,i),s}},t.set=async(t,n,s)=>{const i=Date.now(),a=U(e,{stepId:o,stepType:"store",phase:"in",eventId:"",now:i});a.meta={op:"set",key:t},(0,K.emitStep)(e,a);try{await r(t,n,s);const a=Date.now(),c=U(e,{stepId:o,stepType:"store",phase:"out",eventId:"",now:a});c.durationMs=a-i,c.meta={op:"set",key:t},(0,K.emitStep)(e,c)}catch(n){const s=Date.now(),r=U(e,{stepId:o,stepType:"store",phase:"error",eventId:"",now:s});throw r.durationMs=s-i,r.meta={op:"set",key:t},r.error=n instanceof Error?{name:n.name,message:n.message}:{message:String(n)},(0,K.emitStep)(e,r),n}},t.delete=async t=>{const n=Date.now(),s=U(e,{stepId:o,stepType:"store",phase:"in",eventId:"",now:n});s.meta={op:"delete",key:t},(0,K.emitStep)(e,s);try{await i(t);const s=Date.now(),r=U(e,{stepId:o,stepType:"store",phase:"out",eventId:"",now:s});r.durationMs=s-n,r.meta={op:"delete",key:t},(0,K.emitStep)(e,r)}catch(s){const r=Date.now(),i=U(e,{stepId:o,stepType:"store",phase:"error",eventId:"",now:r});throw i.durationMs=r-n,i.meta={op:"delete",key:t},i.error=s instanceof Error?{name:s.name,message:s.message}:{message:String(s)},(0,K.emitStep)(e,i),s}}}async function Pe(e){const t=(0,P.assign)({globalsStatic:{},sessionStatic:{},run:!0,queueMax:1e3},e,{merge:!1,extend:!1}),n={level:e.logger?.level,handler:e.logger?.handler},o=(0,P.createLogger)(n),s={...t.globalsStatic,...e.globals},r={allowed:!1,config:t,consent:e.consent||{},custom:e.custom||{},destinations:{},transformers:{},stores:{},globals:s,hooks:e.hooks||{},observers:new Set,logger:o,on:{},queue:[],round:0,session:void 0,status:{startedAt:Date.now(),in:0,out:0,failed:0,sources:{},destinations:{},dropped:{}},timing:Date.now(),user:e.user||{},sources:{},pending:{destinations:{}},push:void 0,command:void 0};var i,a;r.push=function(e,t){const n=(0,F.useHooks)(async(n,o={})=>await(0,F.tryCatchAsync)(async()=>{const s=Date.now(),{id:r,ingest:i,respond:a,mapping:c,preChain:u,include:d,exclude:l}=o;let p=a,f=n;const g=d||l?function(e,t,n){let o=e;return t&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>t.includes(e)))),n&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>!n.includes(e)))),o}(e.destinations,d,l):void 0,h=i??(0,F.createIngest)(r||"unknown");if(c){const t=await(0,F.processEventMapping)(f,c,e);if(t.ignore)return xe({ok:!0});if(c.consent&&!(0,F.getGrantedConsent)(c.consent,e.consent,t.event.consent))return xe({ok:!0});f=t.event}if(u?.length&&e.transformers&&Object.keys(e.transformers).length>0){const n=await oe(e,e.transformers,u,f,h,p,r?`source.${r}.next`:void 0);if(null===n.event)return xe({ok:!0});if(n.stopped)return n.respond&&(p=n.respond),xe({ok:!0});if(n.respond&&(p=n.respond),Array.isArray(n.event)){const o=await Promise.all(n.event.map(async n=>{const o=t(n),s=Te(e,o);return qe(e,s,{id:r,ingest:h,respond:p},g)}));if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const t=e.status.sources[r];t.count+=n.event.length,t.lastAt=Date.now(),t.duration+=Date.now()-s}return o[0]??xe({ok:!0})}f=n.event}const m=t(f),y=Te(e,m),w=await qe(e,y,{id:r,ingest:h,respond:p},g);if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const t=e.status.sources[r];t.count++,t.lastAt=Date.now(),t.duration+=Date.now()-s}return w},t=>{if(t instanceof F.FatalError)throw t;return e.status.failed++,e.logger.error("push failed",{event:n,ingest:o.ingest,error:t}),xe({ok:!1})})(),"Push",e.hooks,e.logger);return async(t,o)=>{const s="string"==typeof t.id?t.id:"",r=Date.now();(0,F.emitStep)(e,U(e,{stepId:"collector.push",stepType:"collector",phase:"in",eventId:s,now:r}));try{const i=await n(t,o),a=Date.now(),c=U(e,{stepId:"collector.push",stepType:"collector",phase:"out",eventId:s,now:a});return c.durationMs=a-r,c.outEvent=i,(0,F.emitStep)(e,c),i}catch(t){const n=Date.now(),o=U(e,{stepId:"collector.push",stepType:"collector",phase:"error",eventId:s,now:n});throw o.durationMs=n-r,o.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},(0,F.emitStep)(e,o),t}}}(r,e=>({timing:Math.round((Date.now()-r.timing)/10)/100,source:{type:"collector",schema:"4",version:"4.1.3-next-1780071196115"},...e})),r.command=(i=r,a=De,(0,L.useHooks)(async(e,t,n)=>await(0,L.tryCatchAsync)(async()=>await a(i,e,t,n),n=>{if(n instanceof L.FatalError)throw n;return i.status.failed++,i.logger.error("command failed",{command:e,data:t,error:n}),xe({ok:!1})})(),"Command",i.hooks,i.logger));const c=e.stores||{};return r.stores=await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{code:t,config:r={},env:i={}}=s,a=e.logger.scope("store").scope(o),c={collector:e,logger:a,id:o,config:r,env:i},u=await t(c);n[o]=u}const o=t,s=function(e){const t={};for(const n of Object.keys(e))t[n]="WHITE";const n=[],o=[];function s(r){const i=t[r];if("BLACK"===i)return;if("GRAY"===i){const e=o.indexOf(r),t=o.slice(-1===e?0:e).concat(r).join(" -> ");throw new Error(`Cycle in cache.store chain: ${t}`)}t[r]="GRAY",o.push(r);const a=e[r].cache?.store;if(void 0!==a){if(!(a in e))throw new Error(`Store "${r}" cache.store references "${a}", which is not declared in flow.stores`);s(a)}o.pop(),t[r]="BLACK",n.push(r)}for(const n of Object.keys(e))"WHITE"===t[n]&&s(n);return n}(o);for(const t of s){const s=o[t].cache;if(!s)continue;let r,i;void 0!==s.store?(r=n[s.store],i=s.store):(n.__cache||(n.__cache=ze()),r=n.__cache,i="__cache");const a=s.namespace??t;e.logger.scope("store-cache").scope(t).info(`store "${t}" caches with namespace "${a}:" via ${i}`),n[t]=Ee(n[t],{storeId:t,cacheConfig:s,cacheStore:r,namespace:a,logger:e.logger.scope("store-cache").scope(t),collector:e})}for(const[t,o]of Object.entries(n))"__cache"!==t&&Me(e,o,t);return n}(r,c),function(e,t,n){const o=new Map;for(const[n,s]of Object.entries(e))t[n]&&o.set(s,t[n]);if(0!==o.size)for(const e of[n.transformers,n.destinations,n.sources])if(e)for(const t of Object.values(e))s(t.env);function s(e){if(e)for(const[t,n]of Object.entries(e))if("object"==typeof n&&null!==n){const s=o.get(n);s&&(e[t]=s)}}}(c,r.stores,e),r.stores.__cache||(r.stores.__cache=ze()),r.destinations=await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t))s.config?.require?.length?e.pending.destinations[o]=s:n[o]=Ce(s);return n}(r,e.destinations||{}),r.transformers=await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{code:t,env:r={}}=s,i=(0,R.validateStepEntry)(s,"Transformer");if(!i.ok){e.logger.warn(`Transformer ${o} invalid (${i.code}): ${i.reason}. Skipping.`);continue}const{config:a}=X(s,"before"),{config:c}=X({...s,config:a},"next"),u=Object.keys(r).length>0?{...c,env:r}:c,{cache:d}=s,l=d?{...u,cache:d}:u,{state:p}=s,f=void 0!==p&&void 0===l.state?{...l,state:p}:l,g=e.logger.scope("transformer").scope(o),h={collector:e,logger:g,id:o,ingest:(0,R.createIngest)(o),config:f,env:r},m=t??(e=>{const t=s.mapping;if(t){const n=[];if(void 0!==t.data&&n.push("data"),t.mapping)for(const[e,o]of Object.entries(t.mapping))if("object"==typeof o&&null!==o)for(const[t,s]of Object.entries(o)){if("object"!=typeof s||null===s)continue;const o=s;void 0!==o.data&&n.push(`mapping[${e}][${t}].data`),void 0!==o.silent&&n.push(`mapping[${e}][${t}].silent`)}return n.length>0&&e.collector.logger.warn(`Transformer ${o}: \`${n.join(", ")}\` ignored at transformer position (only event-mutating fields apply).`),{type:"pass",config:e.config,push:async n=>{const o=await(0,R.processEventMapping)(n,t,e.collector);return!o.ignore&&{event:o.event}}}}return{type:"pass",config:e.config,push:e=>({event:e})}}),y=await m(h);void 0!==s.before&&void 0===y.config?.before&&(y.config={...y.config??{},before:s.before}),void 0!==s.next&&void 0===y.config?.next&&(y.config={...y.config??{},next:s.next}),n[o]=y}return n}(r,e.transformers||{}),r}async function $e(e){e=e||{};const t=await Pe(e),n=(o=t,{type:"elb",config:{},push:async(e,t,n,s,r)=>{if("string"==typeof e&&e.startsWith("walker ")){const n=e.replace("walker ","");return o.command(n,t)}let i;if("string"==typeof e)i={name:e},t&&"object"==typeof t&&!Array.isArray(t)&&(i.data=t);else{if(!e||"object"!=typeof e)return xe({ok:!1});i=e,t&&"object"==typeof t&&!Array.isArray(t)&&(i.data={...i.data||{},...t})}return n&&"object"==typeof n&&(i.context=n),s&&Array.isArray(s)&&(i.nested=s),r&&"object"==typeof r&&(i.custom=r),o.push(i)}});var o;t.sources.elb=n,await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const t=await ce(e,o,s);if(!t)continue;const r=s.config?.require;t.config={...t.config,init:!1,...r?{require:[...r]}:{}},n[o]=t}Object.assign(e.sources,n);for(const t of Object.keys(n)){const n=e.sources[t];let o=!1;n.init&&await(0,N.tryCatchAsync)(n.init.bind(n),n=>{if(n instanceof N.FatalError)throw n;o=!0,e.status.failed++,e.logger.scope("source").error("source init failed",{sourceId:t,error:n})})(),o||(n.config.init=!0,ae(n)&&await ie(e,n,t))}return n}(t,e.sources||{});const{consent:s,user:r,globals:i,custom:a}=e;s&&await t.command("consent",s),r&&await t.command("user",r),i&&Object.assign(t.globals,i),a&&Object.assign(t.custom,a),t.config.run&&await t.command("run");let c=n.push;const u=Object.values(t.sources).filter(e=>"elb"!==e.type),d=u.find(e=>e.config.primary);return d?c=d.push:u.length>0&&(c=u[0].push),{collector:t,elb:c}}var _e=async e=>{let t;return{get flow(){return t},trigger:()=>async n=>{if(!t){const n=await $e(e);t={collector:n.collector,elb:n.elb}}const o=function(e){for(const t of Object.values(e.sources||{}))if("lambda"===t.type)return t}(t.collector);if(!o)throw new Error("Lambda source not found in collector");const s={awsRequestId:`test-${Date.now()}`},r=o.push,i=await r(n,s);let a;try{a=JSON.parse(i.body||"{}")}catch{a=i.body}const c={};if(i.headers)for(const[e,t]of Object.entries(i.headers))void 0!==t&&(c[e]=String(t));return{statusCode:i.statusCode,body:a,headers:c}}}};function He(e){return async t=>{const n={...t};if(n.body&&"string"==typeof n.body){const e=JSON.parse(n.body);e.name&&!e.event&&(n.body=JSON.stringify({...e,event:e.name,name:void 0}))}return e.push(n,{awsRequestId:"test-req"})}}var Ne={};r(Ne,{createTrigger:()=>Xe,env:()=>Re,step:()=>Qe});var Re={};r(Re,{push:()=>Le,simulation:()=>Ke});var Be=()=>{},Ge={error:Be,warn:Be,info:Be,debug:Be,throw:e=>{throw"string"==typeof e?new Error(e):e},json:Be,scope:()=>Ge},Fe=()=>()=>Promise.resolve({ok:!0}),Le={get push(){return Fe()},get command(){return Fe()},get elb(){return Fe()},logger:Ge},Ke=["AWS.SQSClient"],Qe={};r(Qe,{decoderText:()=>We,malformedJson:()=>Ve,orderComplete:()=>Ue,pageView:()=>Je});var Je={title:"Page view from SQS",description:"A standard SQS message body containing a walker elb event payload as JSON.",in:{MessageId:"m-1",Body:JSON.stringify({event:"page view",data:{title:"Documentation",url:"https://example.com/docs"}})},out:[["message.ack","m-1"]]},Ue={title:"Order complete from SQS",description:"Order complete event flowing through the long-poll loop.",in:{MessageId:"m-2",Body:JSON.stringify({event:"order complete",data:{id:"ORD-500",total:199.99,currency:"EUR"}})},out:[["message.ack","m-2"]]},We={title:"Text decoder",description:'When decoder is "text", the body string flows under data.payload.',in:{MessageId:"m-3",Body:"raw text payload"},out:[["message.ack","m-3"]]},Ve={title:"Malformed JSON nacks",description:"Default decoder is JSON. A malformed body throws DecoderError; the source nacks (skips DeleteMessage) so the message redelivers.",in:{MessageId:"m-4",Body:"{not json"},out:[["message.nack","m-4"]]};function Ye(e){if("object"!=typeof e||null===e)return!1;const t=e;return"sqs"===t.type&&"function"==typeof t.push}var Xe=async e=>{let t;return{get flow(){return t},trigger:()=>async n=>{if(!t){const n=await $e(e);t={collector:n.collector,elb:n.elb}}const o=function(e){for(const t of Object.values(e.sources??{}))if(Ye(t))return t}(t.collector);if(!o)throw new Error("sqs source not registered in collector, ensure it is configured in sources");const s={MessageId:n.MessageId,Body:n.Body,ReceiptHandle:n.ReceiptHandle,Attributes:n.Attributes,MessageAttributes:n.MessageAttributes},r=await o.push(s),i=[];return r&&"object"==typeof r&&(r.acked&&i.push(["message.ack",n.MessageId]),r.nacked&&i.push(["message.nack",n.MessageId])),i}}};//# sourceMappingURL=dev.js.map
package/dist/dev.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/dev.ts","../src/schemas.ts","../src/lambda/schemas/index.ts","../src/lambda/schemas/settings.ts","../src/lambda/schemas/primitives.ts","../src/sqs/schemas/index.ts","../src/sqs/schemas/settings.ts","../src/sqs/schemas/setup.ts","../src/lambda/examples/index.ts","../src/lambda/examples/env.ts","../src/lambda/examples/step.ts","../src/lambda/examples/trigger.ts","../src/sqs/examples/index.ts","../src/sqs/examples/env.ts","../src/sqs/examples/step.ts","../src/sqs/examples/trigger.ts"],"sourcesContent":["export * as schemas from './schemas';\nexport * as examples from './lambda/examples';\nexport * as sqsExamples from './sqs/examples';\n","// Lambda (default sub-source).\nexport { settings, SettingsSchema, type Settings } from './lambda/schemas';\nexport * from './lambda/schemas/primitives';\n\n// SQS sub-source. Prefixed so the website's <Configuration> snippet can\n// remap data.schemas.sqsSettings / sqsSetup onto data.schemas.settings.\nexport { settings as sqsSettings } from './sqs/schemas';\nexport { setup as sqsSetup } from './sqs/schemas';\n","import { zodToSchema } from '@walkeros/core/dev';\nimport { SettingsSchema } from './settings';\n\n// Export primitives\nexport * from './primitives';\n\n// Export Zod schemas and types\nexport { SettingsSchema, type Settings } from './settings';\n\n// JSON Schema exports (for website PropertyTable and documentation tools)\nexport const settings = zodToSchema(SettingsSchema);\n","import { z } from '@walkeros/core/dev';\nimport { CorsOptionsSchema } from './primitives';\n\n/**\n * AWS Lambda source settings schema\n */\nexport const SettingsSchema = z.object({\n cors: z\n .union([z.boolean(), CorsOptionsSchema])\n .describe(\n 'CORS configuration: false = disabled, true = allow all origins, object = custom configuration',\n )\n .default(true),\n\n timeout: z\n .number()\n .int()\n .positive()\n .max(900000) // AWS Lambda max timeout: 15 minutes\n .describe('Request timeout in milliseconds (max: 900000 for Lambda)')\n .default(30000),\n\n enablePixelTracking: z\n .boolean()\n .describe(\n 'Enable GET requests with 1x1 transparent GIF response for pixel tracking',\n )\n .default(true),\n\n healthPath: z\n .string()\n .describe('Health check endpoint path (e.g., /health)')\n .default('/health'),\n});\n\nexport type Settings = z.infer<typeof SettingsSchema>;\n","import { z } from '@walkeros/core/dev';\n\n/**\n * HTTP methods enum\n */\nexport const HttpMethod = z.enum([\n 'GET',\n 'POST',\n 'PUT',\n 'PATCH',\n 'DELETE',\n 'OPTIONS',\n 'HEAD',\n]);\n\n/**\n * CORS origin configuration\n * Accepts:\n * - '*' for all origins\n * - Single URL string\n * - Array of URL strings\n */\nexport const CorsOrigin = z.union([\n z.string(),\n z.array(z.string()),\n z.literal('*'),\n]);\n\n/**\n * CORS options schema\n * Configuration for Cross-Origin Resource Sharing\n */\nexport const CorsOptionsSchema = z.object({\n origin: CorsOrigin.describe(\n 'Allowed origins (* for all, URL string, or array of URLs)',\n ).optional(),\n\n methods: z.array(HttpMethod).describe('Allowed HTTP methods').optional(),\n\n headers: z.array(z.string()).describe('Allowed request headers').optional(),\n\n credentials: z\n .boolean()\n .describe('Allow credentials (cookies, authorization headers)')\n .optional(),\n\n maxAge: z\n .number()\n .int()\n .positive()\n .describe('Preflight cache duration in seconds')\n .optional(),\n});\n\nexport type CorsOptions = z.infer<typeof CorsOptionsSchema>;\n","import { zodToSchema } from '@walkeros/core/dev';\nimport { SettingsSchema } from './settings';\nimport { SetupSchema } from './setup';\n\nexport { SettingsSchema, type Settings } from './settings';\nexport { SetupSchema, type Setup } from './setup';\n\n// JSON Schema exports (for website PropertyTable + MCP package_get).\nexport const settings = zodToSchema(SettingsSchema);\nexport const setup = zodToSchema(SetupSchema);\n","import { z } from '@walkeros/core/dev';\n\n/**\n * AWS SQS source settings schema.\n *\n * Required: queueName. All other fields optional with sensible defaults\n * applied at runtime by `getConfig`.\n */\nexport const SettingsSchema = z.object({\n queueName: z\n .string()\n .min(1)\n .describe(\n 'SQS queue short name (like walkeros-events). Required for both setup and runtime poll.',\n ),\n region: z\n .string()\n .describe('AWS region (like eu-central-1). Default: eu-central-1.')\n .optional(),\n queueUrl: z\n .string()\n .url()\n .describe(\n 'Optional pre-resolved queue URL. When set, init skips the GetQueueUrl lookup.',\n )\n .optional(),\n client: z\n .any()\n .describe(\n 'Pre-configured AWS SQSClient instance. Bypasses construction when supplied.',\n )\n .optional(),\n config: z\n .any()\n .describe(\n 'AWS SDK SQSClientConfig (credentials, endpoint overrides, retries).',\n )\n .optional(),\n decoder: z\n .enum(['json', 'text', 'raw'])\n .describe(\n 'Decoder for the message body. json (default) parses JSON, text forwards UTF-8, raw forwards a Buffer.',\n )\n .optional(),\n maxMessages: z\n .number()\n .int()\n .min(1)\n .max(10)\n .describe('SQS receive batch size. Cap 10. Default: 10.')\n .optional(),\n waitTimeSeconds: z\n .number()\n .int()\n .min(0)\n .max(20)\n .describe('Long-poll duration in seconds. Cap 20. Default: 20.')\n .optional(),\n visibilityTimeout: z\n .number()\n .int()\n .nonnegative()\n .describe(\n 'Per-receive visibility timeout override. Default: queue-configured value.',\n )\n .optional(),\n shutdownTimeoutMs: z\n .number()\n .int()\n .positive()\n .describe(\n 'Graceful shutdown timeout in milliseconds. Default: 30000. After this window, destroy() force-closes.',\n )\n .optional(),\n onPushError: z\n .enum(['nack', 'ack'])\n .describe(\n 'Behavior when forwarding to the collector throws. nack (default) skips DeleteMessage so the message redelivers; ack drops it.',\n )\n .optional(),\n});\n\nexport type Settings = z.infer<typeof SettingsSchema>;\n","import { z } from '@walkeros/core/dev';\n\n/**\n * AWS SQS source setup schema.\n *\n * Provisioning options for `walkeros setup source.<id>`. Authoritative-apply:\n * declared state is written via a single CreateQueueCommand; non-declared\n * tags or attributes are left untouched.\n */\nconst TagsSchema = z.record(z.string(), z.string());\n\nexport const SetupSchema = z.object({\n region: z.string().min(1).describe('AWS region.').optional(),\n fifoQueue: z\n .boolean()\n .describe(\n 'FIFO queue with content-based deduplication. Auto-appends .fifo suffix to the queue name.',\n )\n .optional(),\n visibilityTimeoutSeconds: z\n .number()\n .int()\n .nonnegative()\n .describe('Visibility timeout in seconds. Default: 30.')\n .optional(),\n messageRetentionSeconds: z\n .number()\n .int()\n .positive()\n .describe('Message retention period in seconds. Default: 345600 (4 days).')\n .optional(),\n maximumMessageSize: z\n .number()\n .int()\n .min(1024)\n .max(262144)\n .describe('Max message size in bytes. Default: 262144 (256 KB).')\n .optional(),\n kmsMasterKeyId: z\n .string()\n .describe('KMS key alias or ID for at-rest encryption.')\n .optional(),\n deadLetterQueue: z\n .object({\n arn: z\n .string()\n .describe(\n 'ARN of an existing DLQ. Mutually exclusive with create: true.',\n )\n .optional(),\n create: z\n .boolean()\n .describe('Create a sibling DLQ named <queueName>-dlq. Default: false.')\n .optional(),\n maxReceiveCount: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .describe('Max receive count before message goes to DLQ. Default: 5.')\n .optional(),\n })\n .describe('Optional dead-letter queue.')\n .optional(),\n tags: TagsSchema.describe(\n 'Tags applied to the queue (and inherited by an auto-created DLQ).',\n ).optional(),\n subscribeToSnsTopic: z\n .object({\n topicArn: z.string().min(1).describe('Topic ARN to subscribe to.'),\n rawMessageDelivery: z\n .boolean()\n .describe('Deliver SNS messages without the SNS envelope.')\n .optional(),\n filterPolicy: z\n .record(z.string(), z.unknown())\n .describe('SNS filter policy applied at subscription level.')\n .optional(),\n })\n .describe(\n 'Optional SNS topic subscription. Creates the subscription and the matching queue policy.',\n )\n .optional(),\n});\n\nexport type Setup = z.infer<typeof SetupSchema>;\n","export * as env from './env';\nexport * as step from './step';\nexport { createTrigger, trigger } from './trigger';\n","import type { Env } from '../types';\nimport type { Elb, Logger } from '@walkeros/core';\n\n/**\n * Example environment configurations for AWS Lambda source\n *\n * These environments provide standardized mock structures for testing\n * Lambda event handling without requiring actual Lambda deployment.\n */\n\n// Create a properly typed elb/push/command function that returns a promise with PushResult\nconst createMockElbFn = (): Elb.Fn => {\n const fn = (() =>\n Promise.resolve({\n ok: true,\n })) as Elb.Fn;\n return fn;\n};\n\n// Simple no-op logger for demo purposes\nconst noopFn = () => {};\nconst noopLogger: Logger.Instance = {\n error: noopFn,\n warn: noopFn,\n info: noopFn,\n debug: noopFn,\n throw: (message: string | Error) => {\n throw typeof message === 'string' ? new Error(message) : message;\n },\n json: noopFn,\n scope: () => noopLogger,\n};\n\n/**\n * Standard mock environment for testing Lambda source\n *\n * Use this for testing Lambda event ingestion and request/response handling\n * without requiring a real AWS Lambda environment.\n */\nexport const push: Env = {\n get push() {\n return createMockElbFn();\n },\n get command() {\n return createMockElbFn();\n },\n get elb() {\n return createMockElbFn();\n },\n logger: noopLogger,\n};\n","import type { Flow } from '@walkeros/core';\n\nexport const lambdaPost: Flow.StepExample = {\n title: 'Lambda POST',\n description:\n 'An API Gateway v2 HTTP POST with a JSON body is converted into a walker elb event.',\n trigger: { type: 'POST' },\n in: {\n version: '2.0',\n requestContext: {\n http: { method: 'POST', path: '/collect' },\n requestId: 'req-123',\n },\n body: JSON.stringify({\n event: 'page view',\n data: { title: 'Home' },\n }),\n isBase64Encoded: false,\n },\n out: [\n [\n 'elb',\n {\n name: 'page view',\n data: { title: 'Home' },\n },\n ],\n ],\n};\n\nexport const apiGatewayV1Post: Flow.StepExample = {\n title: 'API Gateway v1 POST',\n description:\n 'A REST API Gateway v1 POST request with a JSON body is converted into a walker elb event.',\n trigger: { type: 'POST' },\n in: {\n httpMethod: 'POST',\n path: '/collect',\n requestContext: {\n requestId: 'req-789',\n identity: { sourceIp: '203.0.113.42' },\n },\n queryStringParameters: null,\n body: JSON.stringify({\n event: 'page view',\n data: { title: 'Home' },\n }),\n isBase64Encoded: false,\n },\n out: [\n [\n 'elb',\n {\n name: 'page view',\n data: { title: 'Home' },\n },\n ],\n ],\n};\n\nexport const lambdaGet: Flow.StepExample = {\n title: 'Lambda GET',\n description:\n 'An API Gateway v2 HTTP GET with query parameters is parsed into an elb event payload.',\n trigger: { type: 'GET' },\n in: {\n version: '2.0',\n requestContext: {\n http: { method: 'GET', path: '/collect' },\n requestId: 'req-456',\n },\n rawQueryString: 'e=page+view&d=%7B%22title%22%3A%22Home%22%7D',\n isBase64Encoded: false,\n },\n out: [\n [\n 'elb',\n {\n e: 'page view',\n d: '{\"title\":\"Home\"}',\n },\n ],\n ],\n};\n","import type { Trigger, Collector } from '@walkeros/core';\nimport type { LambdaEvent, LambdaContext, LambdaResult } from '../types';\nimport { startFlow } from '@walkeros/collector';\n\nexport interface Content {\n [key: string]: unknown;\n}\n\nexport interface Result {\n statusCode: number;\n body: unknown;\n headers: Record<string, string>;\n}\n\n/**\n * Find the lambda source instance from the collector's registered sources.\n */\nfunction findLambdaSource(collector: Collector.Instance) {\n for (const source of Object.values(collector.sources || {})) {\n if ((source as { type?: string }).type === 'lambda') return source;\n }\n}\n\n/**\n * Lambda source createTrigger.\n *\n * Boots the collector via startFlow, then invokes the Lambda source's push()\n * with a real API Gateway event and a minimal Lambda context.\n *\n * Content is the raw Lambda event object (API Gateway v1 or v2 format).\n * Result contains statusCode, parsed body, and headers.\n *\n * @example\n * const { trigger, flow } = await createTrigger(config);\n * const result = await trigger('POST')({ version: '2.0', ... });\n * console.log(result.statusCode, result.body);\n */\nconst createTrigger: Trigger.CreateFn<Content, Result> = async (\n config: Collector.InitConfig,\n) => {\n let flow: Trigger.FlowHandle | undefined;\n\n const trigger: Trigger.Fn<Content, Result> =\n () =>\n async (content: Content): Promise<Result> => {\n // Lazy startFlow\n if (!flow) {\n const result = await startFlow(config);\n flow = { collector: result.collector, elb: result.elb };\n }\n\n const source = findLambdaSource(flow.collector);\n if (!source) throw new Error('Lambda source not found in collector');\n\n // Create minimal Lambda context\n const lambdaContext = {\n awsRequestId: `test-${Date.now()}`,\n } as unknown as LambdaContext;\n\n // Call source.push with the raw Lambda event + context\n const pushFn = (\n source as unknown as {\n push: (...args: unknown[]) => Promise<LambdaResult>;\n }\n ).push;\n const lambdaResult = await pushFn(\n content as unknown as LambdaEvent,\n lambdaContext,\n );\n\n // Parse response\n let body: unknown;\n try {\n body = JSON.parse(lambdaResult.body || '{}');\n } catch {\n body = lambdaResult.body;\n }\n\n const headers: Record<string, string> = {};\n if (lambdaResult.headers) {\n for (const [k, v] of Object.entries(lambdaResult.headers)) {\n if (v !== undefined) headers[k] = String(v);\n }\n }\n\n return {\n statusCode: lambdaResult.statusCode,\n body,\n headers,\n };\n };\n\n return {\n get flow() {\n return flow;\n },\n trigger,\n };\n};\n\n/**\n * Legacy trigger — takes a source instance directly.\n * Preserved for CLI simulate path.\n */\nfunction trigger(source: {\n push: (event: LambdaEvent, context: LambdaContext) => Promise<LambdaResult>;\n}): (content: Content) => Promise<LambdaResult> {\n return async (content: Content) => {\n const lambdaEvent = { ...(content as Record<string, unknown>) };\n\n // Adapt body format: step examples may use `name`, source expects `event`\n if (lambdaEvent.body && typeof lambdaEvent.body === 'string') {\n const body = JSON.parse(lambdaEvent.body);\n if (body.name && !body.event) {\n lambdaEvent.body = JSON.stringify({\n ...body,\n event: body.name,\n name: undefined,\n });\n }\n }\n\n const context: LambdaContext = {\n awsRequestId: 'test-req',\n } as unknown as LambdaContext;\n\n return source.push(lambdaEvent as unknown as LambdaEvent, context);\n };\n}\n\nexport { createTrigger, trigger };\n","export * as env from './env';\nexport * as step from './step';\nexport { createTrigger } from './trigger';\nexport type { Content, Result } from './trigger';\n","import type { Env } from '../types';\nimport type { Elb, Logger } from '@walkeros/core';\n\n/**\n * Example environment for the AWS SQS source.\n *\n * Tests substitute the real SDK via `jest.mock('@aws-sdk/client-sqs')` and\n * `jest.mock('@aws-sdk/client-sns')`, which is the canonical pattern: imports\n * of those modules get replaced module-wide, no env-injection plumbing\n * required at the call site.\n *\n * The `simulation` list documents which SDK identifiers the source touches\n * during a simulated run, used by the simulator to know what to stub.\n */\n\nconst noopFn = (): void => undefined;\nconst noopLogger: Logger.Instance = {\n error: noopFn,\n warn: noopFn,\n info: noopFn,\n debug: noopFn,\n throw: (message: string | Error) => {\n throw typeof message === 'string' ? new Error(message) : message;\n },\n json: noopFn,\n scope: () => noopLogger,\n};\n\nconst createMockElbFn = (): Elb.Fn => {\n const fn: Elb.Fn = () => Promise.resolve({ ok: true });\n return fn;\n};\n\n/**\n * Standard mock environment for the SQS source.\n *\n * AWS SDK constructors are intentionally absent: the canonical pattern is\n * module-level `jest.mock('@aws-sdk/client-sqs')` and -sns, not env-injection.\n */\nexport const push: Env = {\n get push() {\n return createMockElbFn();\n },\n get command() {\n return createMockElbFn();\n },\n get elb() {\n return createMockElbFn();\n },\n logger: noopLogger,\n};\n\nexport const simulation = ['AWS.SQSClient'];\n","import type { Flow } from '@walkeros/core';\n\n/**\n * SQS source step examples.\n *\n * Each `in` is a partial SQS Message-like (MessageId, Body, optional\n * ReceiptHandle). The trigger synthesizes the missing fields and dispatches\n * through the source's `push()` (the same pipeline the long-poll loop uses).\n * `out` records the terminal state recorded by the trigger as\n * `[method, ...args]` entries.\n */\n\nconst eventPayload = {\n event: 'page view',\n data: { title: 'Documentation', url: 'https://example.com/docs' },\n};\n\nconst orderPayload = {\n event: 'order complete',\n data: { id: 'ORD-500', total: 199.99, currency: 'EUR' },\n};\n\nexport const pageView: Flow.StepExample = {\n title: 'Page view from SQS',\n description:\n 'A standard SQS message body containing a walker elb event payload as JSON.',\n in: {\n MessageId: 'm-1',\n Body: JSON.stringify(eventPayload),\n },\n out: [['message.ack', 'm-1']],\n};\n\nexport const orderComplete: Flow.StepExample = {\n title: 'Order complete from SQS',\n description: 'Order complete event flowing through the long-poll loop.',\n in: {\n MessageId: 'm-2',\n Body: JSON.stringify(orderPayload),\n },\n out: [['message.ack', 'm-2']],\n};\n\nexport const decoderText: Flow.StepExample = {\n title: 'Text decoder',\n description:\n 'When decoder is \"text\", the body string flows under data.payload.',\n in: { MessageId: 'm-3', Body: 'raw text payload' },\n out: [['message.ack', 'm-3']],\n};\n\nexport const malformedJson: Flow.StepExample = {\n title: 'Malformed JSON nacks',\n description:\n 'Default decoder is JSON. A malformed body throws DecoderError; the source nacks (skips DeleteMessage) so the message redelivers.',\n in: { MessageId: 'm-4', Body: '{not json' },\n out: [['message.nack', 'm-4']],\n};\n","import type { Collector, Trigger } from '@walkeros/core';\nimport { startFlow } from '@walkeros/collector';\nimport type { SyntheticMessage, SyntheticPushResult } from '../types';\n\n/**\n * Content shape for the SQS source trigger.\n *\n * The trigger synthesizes a SyntheticMessage from this partial input and\n * dispatches it through the source's `push()` (the same pipeline the\n * long-poll loop uses).\n */\nexport interface Content {\n MessageId: string;\n Body: string;\n ReceiptHandle?: string;\n Attributes?: Record<string, string>;\n MessageAttributes?: Record<\n string,\n { DataType: string; StringValue?: string }\n >;\n}\n\n/**\n * Trigger result: the recorded ack/nack as `[method, MessageId]` entries.\n * Mirrors the destination's `[method, ...args]` recording shape.\n */\nexport type Result = Array<[string, ...unknown[]]>;\n\ninterface SqsSourceLike {\n type: string;\n push: (content?: SyntheticMessage) => Promise<SyntheticPushResult | void>;\n}\n\nfunction isSqsSource(value: unknown): value is SqsSourceLike {\n if (typeof value !== 'object' || value === null) return false;\n const candidate: { type?: unknown; push?: unknown } = value;\n return candidate.type === 'sqs' && typeof candidate.push === 'function';\n}\n\nfunction findSource(collector: Collector.Instance): SqsSourceLike | undefined {\n for (const source of Object.values(collector.sources ?? {})) {\n if (isSqsSource(source)) return source;\n }\n return undefined;\n}\n\n/**\n * SQS source createTrigger.\n *\n * Boots the collector via startFlow, finds the registered SQS source, and\n * invokes its `push()` with a synthesized message. The source dispatches the\n * synthetic message through the same handler the long-poll loop uses,\n * exercising the full decode / forward / ack-nack pipeline without touching\n * real SQS infrastructure.\n */\nexport const createTrigger: Trigger.CreateFn<Content, Result> = async (\n config: Collector.InitConfig,\n) => {\n let flow: Trigger.FlowHandle | undefined;\n\n const trigger: Trigger.Fn<Content, Result> =\n () =>\n async (content: Content): Promise<Result> => {\n if (!flow) {\n const result = await startFlow(config);\n flow = { collector: result.collector, elb: result.elb };\n }\n\n const source = findSource(flow.collector);\n if (!source) {\n throw new Error(\n 'sqs source not registered in collector, ensure it is configured in sources',\n );\n }\n\n const synthetic: SyntheticMessage = {\n MessageId: content.MessageId,\n Body: content.Body,\n ReceiptHandle: content.ReceiptHandle,\n Attributes: content.Attributes,\n MessageAttributes: content.MessageAttributes,\n };\n\n const result = await source.push(synthetic);\n const recorded: Result = [];\n if (result && typeof result === 'object') {\n if (result.acked) recorded.push(['message.ack', content.MessageId]);\n if (result.nacked) recorded.push(['message.nack', content.MessageId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,QAAQ;AACX,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,YAA8B;AAAA,MAClC,WAAW,QAAQ;AAAA,MACnB,MAAM,QAAQ;AAAA,MACd,eAAe,QAAQ;AAAA,MACvB,YAAY,QAAQ;AAAA,MACpB,mBAAmB,QAAQ;AAAA,IAC7B;AAEA,UAAM,SAAS,MAAM,OAAO,KAAK,SAAS;AAC1C,UAAM,WAAmB,CAAC;AAC1B,QAAI,UAAU,OAAO,WAAW,UAAU;AACxC,UAAI,OAAO,MAAO,UAAS,KAAK,CAAC,eAAe,QAAQ,SAAS,CAAC;AAClE,UAAI,OAAO,OAAQ,UAAS,KAAK,CAAC,gBAAgB,QAAQ,SAAS,CAAC;AAAA,IACtE;AACA,WAAO;AAAA,EACT;AAEF,SAAO;AAAA,IACL,IAAI,OAAO;AACT,aAAO;AAAA,IACT;AAAA,IACA,SAAAD;AAAA,EACF;AACF;","names":["examples_exports","settings","import_dev","import_dev","import_dev","import_dev","SettingsSchema","import_dev","settings","SettingsSchema","trigger","k","v","examples_exports","createTrigger","env_exports","step_exports","env_exports","push","noopFn","noopLogger","createMockElbFn","step_exports","createTrigger","trigger","result"]}
1
+ {"version":3,"sources":["../src/dev.ts","../src/schemas.ts","../src/lambda/schemas/index.ts","../src/lambda/schemas/settings.ts","../src/lambda/schemas/primitives.ts","../src/sqs/schemas/index.ts","../src/sqs/schemas/settings.ts","../src/sqs/schemas/setup.ts","../src/lambda/examples/index.ts","../src/lambda/examples/env.ts","../src/lambda/examples/step.ts","../src/lambda/examples/trigger.ts","../src/sqs/examples/index.ts","../src/sqs/examples/env.ts","../src/sqs/examples/step.ts","../src/sqs/examples/trigger.ts"],"sourcesContent":["export * as schemas from './schemas';\nexport * as examples from './lambda/examples';\nexport * as sqsExamples from './sqs/examples';\n","// Lambda (default sub-source).\nexport { settings, SettingsSchema, type Settings } from './lambda/schemas';\nexport * from './lambda/schemas/primitives';\n\n// SQS sub-source. Prefixed so the website's <Configuration> snippet can\n// remap data.schemas.sqsSettings / sqsSetup onto data.schemas.settings.\nexport { settings as sqsSettings } from './sqs/schemas';\nexport { setup as sqsSetup } from './sqs/schemas';\n","import { zodToSchema } from '@walkeros/core/dev';\nimport { SettingsSchema } from './settings';\n\n// Export primitives\nexport * from './primitives';\n\n// Export Zod schemas and types\nexport { SettingsSchema, type Settings } from './settings';\n\n// JSON Schema exports (for website PropertyTable and documentation tools)\nexport const settings = zodToSchema(SettingsSchema);\n","import { z } from '@walkeros/core/dev';\nimport { CorsOptionsSchema } from './primitives';\n\n/**\n * AWS Lambda source settings schema\n */\nexport const SettingsSchema = z.object({\n cors: z\n .union([z.boolean(), CorsOptionsSchema])\n .describe(\n 'CORS configuration: false = disabled, true = allow all origins, object = custom configuration',\n )\n .default(true),\n\n timeout: z\n .number()\n .int()\n .positive()\n .max(900000) // AWS Lambda max timeout: 15 minutes\n .describe('Request timeout in milliseconds (max: 900000 for Lambda)')\n .default(30000),\n\n enablePixelTracking: z\n .boolean()\n .describe(\n 'Enable GET requests with 1x1 transparent GIF response for pixel tracking',\n )\n .default(true),\n\n healthPath: z\n .string()\n .describe('Health check endpoint path (e.g., /health)')\n .default('/health'),\n});\n\nexport type Settings = z.infer<typeof SettingsSchema>;\n","import { z } from '@walkeros/core/dev';\n\n/**\n * HTTP methods enum\n */\nexport const HttpMethod = z.enum([\n 'GET',\n 'POST',\n 'PUT',\n 'PATCH',\n 'DELETE',\n 'OPTIONS',\n 'HEAD',\n]);\n\n/**\n * CORS origin configuration\n * Accepts:\n * - '*' for all origins\n * - Single URL string\n * - Array of URL strings\n */\nexport const CorsOrigin = z.union([\n z.string(),\n z.array(z.string()),\n z.literal('*'),\n]);\n\n/**\n * CORS options schema\n * Configuration for Cross-Origin Resource Sharing\n */\nexport const CorsOptionsSchema = z.object({\n origin: CorsOrigin.describe(\n 'Allowed origins (* for all, URL string, or array of URLs)',\n ).optional(),\n\n methods: z.array(HttpMethod).describe('Allowed HTTP methods').optional(),\n\n headers: z.array(z.string()).describe('Allowed request headers').optional(),\n\n credentials: z\n .boolean()\n .describe('Allow credentials (cookies, authorization headers)')\n .optional(),\n\n maxAge: z\n .number()\n .int()\n .positive()\n .describe('Preflight cache duration in seconds')\n .optional(),\n});\n\nexport type CorsOptions = z.infer<typeof CorsOptionsSchema>;\n","import { zodToSchema } from '@walkeros/core/dev';\nimport { SettingsSchema } from './settings';\nimport { SetupSchema } from './setup';\n\nexport { SettingsSchema, type Settings } from './settings';\nexport { SetupSchema, type Setup } from './setup';\n\n// JSON Schema exports (for website PropertyTable + MCP package_get).\nexport const settings = zodToSchema(SettingsSchema);\nexport const setup = zodToSchema(SetupSchema);\n","import { z } from '@walkeros/core/dev';\n\n/**\n * AWS SQS source settings schema.\n *\n * Required: queueName. All other fields optional with sensible defaults\n * applied at runtime by `getConfig`.\n */\nexport const SettingsSchema = z.object({\n queueName: z\n .string()\n .min(1)\n .describe(\n 'SQS queue short name (like walkeros-events). Required for both setup and runtime poll.',\n ),\n region: z\n .string()\n .describe('AWS region (like eu-central-1). Default: eu-central-1.')\n .optional(),\n queueUrl: z\n .string()\n .url()\n .describe(\n 'Optional pre-resolved queue URL. When set, init skips the GetQueueUrl lookup.',\n )\n .optional(),\n client: z\n .any()\n .describe(\n 'Pre-configured AWS SQSClient instance. Bypasses construction when supplied.',\n )\n .optional(),\n config: z\n .any()\n .describe(\n 'AWS SDK SQSClientConfig (credentials, endpoint overrides, retries).',\n )\n .optional(),\n decoder: z\n .enum(['json', 'text', 'raw'])\n .describe(\n 'Decoder for the message body. json (default) parses JSON, text forwards UTF-8, raw forwards a Buffer.',\n )\n .optional(),\n maxMessages: z\n .number()\n .int()\n .min(1)\n .max(10)\n .describe('SQS receive batch size. Cap 10. Default: 10.')\n .optional(),\n waitTimeSeconds: z\n .number()\n .int()\n .min(0)\n .max(20)\n .describe('Long-poll duration in seconds. Cap 20. Default: 20.')\n .optional(),\n visibilityTimeout: z\n .number()\n .int()\n .nonnegative()\n .describe(\n 'Per-receive visibility timeout override. Default: queue-configured value.',\n )\n .optional(),\n shutdownTimeoutMs: z\n .number()\n .int()\n .positive()\n .describe(\n 'Graceful shutdown timeout in milliseconds. Default: 30000. After this window, destroy() force-closes.',\n )\n .optional(),\n onPushError: z\n .enum(['nack', 'ack'])\n .describe(\n 'Behavior when forwarding to the collector throws. nack (default) skips DeleteMessage so the message redelivers; ack drops it.',\n )\n .optional(),\n});\n\nexport type Settings = z.infer<typeof SettingsSchema>;\n","import { z } from '@walkeros/core/dev';\n\n/**\n * AWS SQS source setup schema.\n *\n * Provisioning options for `walkeros setup source.<id>`. Authoritative-apply:\n * declared state is written via a single CreateQueueCommand; non-declared\n * tags or attributes are left untouched.\n */\nconst TagsSchema = z.record(z.string(), z.string());\n\nexport const SetupSchema = z.object({\n region: z.string().min(1).describe('AWS region.').optional(),\n fifoQueue: z\n .boolean()\n .describe(\n 'FIFO queue with content-based deduplication. Auto-appends .fifo suffix to the queue name.',\n )\n .optional(),\n visibilityTimeoutSeconds: z\n .number()\n .int()\n .nonnegative()\n .describe('Visibility timeout in seconds. Default: 30.')\n .optional(),\n messageRetentionSeconds: z\n .number()\n .int()\n .positive()\n .describe('Message retention period in seconds. Default: 345600 (4 days).')\n .optional(),\n maximumMessageSize: z\n .number()\n .int()\n .min(1024)\n .max(262144)\n .describe('Max message size in bytes. Default: 262144 (256 KB).')\n .optional(),\n kmsMasterKeyId: z\n .string()\n .describe('KMS key alias or ID for at-rest encryption.')\n .optional(),\n deadLetterQueue: z\n .object({\n arn: z\n .string()\n .describe(\n 'ARN of an existing DLQ. Mutually exclusive with create: true.',\n )\n .optional(),\n create: z\n .boolean()\n .describe('Create a sibling DLQ named <queueName>-dlq. Default: false.')\n .optional(),\n maxReceiveCount: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .describe('Max receive count before message goes to DLQ. Default: 5.')\n .optional(),\n })\n .describe('Optional dead-letter queue.')\n .optional(),\n tags: TagsSchema.describe(\n 'Tags applied to the queue (and inherited by an auto-created DLQ).',\n ).optional(),\n subscribeToSnsTopic: z\n .object({\n topicArn: z.string().min(1).describe('Topic ARN to subscribe to.'),\n rawMessageDelivery: z\n .boolean()\n .describe('Deliver SNS messages without the SNS envelope.')\n .optional(),\n filterPolicy: z\n .record(z.string(), z.unknown())\n .describe('SNS filter policy applied at subscription level.')\n .optional(),\n })\n .describe(\n 'Optional SNS topic subscription. Creates the subscription and the matching queue policy.',\n )\n .optional(),\n});\n\nexport type Setup = z.infer<typeof SetupSchema>;\n","export * as env from './env';\nexport * as step from './step';\nexport { createTrigger, trigger } from './trigger';\n","import type { Env } from '../types';\nimport type { Elb, Logger } from '@walkeros/core';\n\n/**\n * Example environment configurations for AWS Lambda source\n *\n * These environments provide standardized mock structures for testing\n * Lambda event handling without requiring actual Lambda deployment.\n */\n\n// Create a properly typed elb/push/command function that returns a promise with PushResult\nconst createMockElbFn = (): Elb.Fn => {\n const fn = (() =>\n Promise.resolve({\n ok: true,\n })) as Elb.Fn;\n return fn;\n};\n\n// Simple no-op logger for demo purposes\nconst noopFn = () => {};\nconst noopLogger: Logger.Instance = {\n error: noopFn,\n warn: noopFn,\n info: noopFn,\n debug: noopFn,\n throw: (message: string | Error) => {\n throw typeof message === 'string' ? new Error(message) : message;\n },\n json: noopFn,\n scope: () => noopLogger,\n};\n\n/**\n * Standard mock environment for testing Lambda source\n *\n * Use this for testing Lambda event ingestion and request/response handling\n * without requiring a real AWS Lambda environment.\n */\nexport const push: Env = {\n get push() {\n return createMockElbFn();\n },\n get command() {\n return createMockElbFn();\n },\n get elb() {\n return createMockElbFn();\n },\n logger: noopLogger,\n};\n","import type { Flow } from '@walkeros/core';\n\nexport const lambdaPost: Flow.StepExample = {\n title: 'Lambda POST',\n description:\n 'An API Gateway v2 HTTP POST with a JSON body is converted into a walker elb event.',\n trigger: { type: 'POST' },\n in: {\n version: '2.0',\n requestContext: {\n http: { method: 'POST', path: '/collect' },\n requestId: 'req-123',\n },\n body: JSON.stringify({\n event: 'page view',\n data: { title: 'Home' },\n }),\n isBase64Encoded: false,\n },\n out: [\n [\n 'elb',\n {\n name: 'page view',\n data: { title: 'Home' },\n },\n ],\n ],\n};\n\nexport const apiGatewayV1Post: Flow.StepExample = {\n title: 'API Gateway v1 POST',\n description:\n 'A REST API Gateway v1 POST request with a JSON body is converted into a walker elb event.',\n trigger: { type: 'POST' },\n in: {\n httpMethod: 'POST',\n path: '/collect',\n requestContext: {\n requestId: 'req-789',\n identity: { sourceIp: '203.0.113.42' },\n },\n queryStringParameters: null,\n body: JSON.stringify({\n event: 'page view',\n data: { title: 'Home' },\n }),\n isBase64Encoded: false,\n },\n out: [\n [\n 'elb',\n {\n name: 'page view',\n data: { title: 'Home' },\n },\n ],\n ],\n};\n\nexport const lambdaGet: Flow.StepExample = {\n title: 'Lambda GET',\n description:\n 'An API Gateway v2 HTTP GET with query parameters is parsed into an elb event payload.',\n trigger: { type: 'GET' },\n in: {\n version: '2.0',\n requestContext: {\n http: { method: 'GET', path: '/collect' },\n requestId: 'req-456',\n },\n rawQueryString: 'e=page+view&d=%7B%22title%22%3A%22Home%22%7D',\n isBase64Encoded: false,\n },\n out: [\n [\n 'elb',\n {\n e: 'page view',\n d: '{\"title\":\"Home\"}',\n },\n ],\n ],\n};\n","import type { Trigger, Collector } from '@walkeros/core';\nimport type { LambdaEvent, LambdaContext, LambdaResult } from '../types';\nimport { startFlow } from '@walkeros/collector';\n\nexport interface Content {\n [key: string]: unknown;\n}\n\nexport interface Result {\n statusCode: number;\n body: unknown;\n headers: Record<string, string>;\n}\n\n/**\n * Find the lambda source instance from the collector's registered sources.\n */\nfunction findLambdaSource(collector: Collector.Instance) {\n for (const source of Object.values(collector.sources || {})) {\n if ((source as { type?: string }).type === 'lambda') return source;\n }\n}\n\n/**\n * Lambda source createTrigger.\n *\n * Boots the collector via startFlow, then invokes the Lambda source's push()\n * with a real API Gateway event and a minimal Lambda context.\n *\n * Content is the raw Lambda event object (API Gateway v1 or v2 format).\n * Result contains statusCode, parsed body, and headers.\n *\n * @example\n * const { trigger, flow } = await createTrigger(config);\n * const result = await trigger('POST')({ version: '2.0', ... });\n * console.log(result.statusCode, result.body);\n */\nconst createTrigger: Trigger.CreateFn<Content, Result> = async (\n config: Collector.InitConfig,\n) => {\n let flow: Trigger.FlowHandle | undefined;\n\n const trigger: Trigger.Fn<Content, Result> =\n () =>\n async (content: Content): Promise<Result> => {\n // Lazy startFlow\n if (!flow) {\n const result = await startFlow(config);\n flow = { collector: result.collector, elb: result.elb };\n }\n\n const source = findLambdaSource(flow.collector);\n if (!source) throw new Error('Lambda source not found in collector');\n\n // Create minimal Lambda context\n const lambdaContext = {\n awsRequestId: `test-${Date.now()}`,\n } as unknown as LambdaContext;\n\n // Call source.push with the raw Lambda event + context\n const pushFn = (\n source as unknown as {\n push: (...args: unknown[]) => Promise<LambdaResult>;\n }\n ).push;\n const lambdaResult = await pushFn(\n content as unknown as LambdaEvent,\n lambdaContext,\n );\n\n // Parse response\n let body: unknown;\n try {\n body = JSON.parse(lambdaResult.body || '{}');\n } catch {\n body = lambdaResult.body;\n }\n\n const headers: Record<string, string> = {};\n if (lambdaResult.headers) {\n for (const [k, v] of Object.entries(lambdaResult.headers)) {\n if (v !== undefined) headers[k] = String(v);\n }\n }\n\n return {\n statusCode: lambdaResult.statusCode,\n body,\n headers,\n };\n };\n\n return {\n get flow() {\n return flow;\n },\n trigger,\n };\n};\n\n/**\n * Legacy trigger — takes a source instance directly.\n * Preserved for CLI simulate path.\n */\nfunction trigger(source: {\n push: (event: LambdaEvent, context: LambdaContext) => Promise<LambdaResult>;\n}): (content: Content) => Promise<LambdaResult> {\n return async (content: Content) => {\n const lambdaEvent = { ...(content as Record<string, unknown>) };\n\n // Adapt body format: step examples may use `name`, source expects `event`\n if (lambdaEvent.body && typeof lambdaEvent.body === 'string') {\n const body = JSON.parse(lambdaEvent.body);\n if (body.name && !body.event) {\n lambdaEvent.body = JSON.stringify({\n ...body,\n event: body.name,\n name: undefined,\n });\n }\n }\n\n const context: LambdaContext = {\n awsRequestId: 'test-req',\n } as unknown as LambdaContext;\n\n return source.push(lambdaEvent as unknown as LambdaEvent, context);\n };\n}\n\nexport { createTrigger, trigger };\n","export * as env from './env';\nexport * as step from './step';\nexport { createTrigger } from './trigger';\nexport type { Content, Result } from './trigger';\n","import type { Env } from '../types';\nimport type { Elb, Logger } from '@walkeros/core';\n\n/**\n * Example environment for the AWS SQS source.\n *\n * Tests substitute the real SDK via `jest.mock('@aws-sdk/client-sqs')` and\n * `jest.mock('@aws-sdk/client-sns')`, which is the canonical pattern: imports\n * of those modules get replaced module-wide, no env-injection plumbing\n * required at the call site.\n *\n * The `simulation` list documents which SDK identifiers the source touches\n * during a simulated run, used by the simulator to know what to stub.\n */\n\nconst noopFn = (): void => undefined;\nconst noopLogger: Logger.Instance = {\n error: noopFn,\n warn: noopFn,\n info: noopFn,\n debug: noopFn,\n throw: (message: string | Error) => {\n throw typeof message === 'string' ? new Error(message) : message;\n },\n json: noopFn,\n scope: () => noopLogger,\n};\n\nconst createMockElbFn = (): Elb.Fn => {\n const fn: Elb.Fn = () => Promise.resolve({ ok: true });\n return fn;\n};\n\n/**\n * Standard mock environment for the SQS source.\n *\n * AWS SDK constructors are intentionally absent: the canonical pattern is\n * module-level `jest.mock('@aws-sdk/client-sqs')` and -sns, not env-injection.\n */\nexport const push: Env = {\n get push() {\n return createMockElbFn();\n },\n get command() {\n return createMockElbFn();\n },\n get elb() {\n return createMockElbFn();\n },\n logger: noopLogger,\n};\n\nexport const simulation = ['AWS.SQSClient'];\n","import type { Flow } from '@walkeros/core';\n\n/**\n * SQS source step examples.\n *\n * Each `in` is a partial SQS Message-like (MessageId, Body, optional\n * ReceiptHandle). The trigger synthesizes the missing fields and dispatches\n * through the source's `push()` (the same pipeline the long-poll loop uses).\n * `out` records the terminal state recorded by the trigger as\n * `[method, ...args]` entries.\n */\n\nconst eventPayload = {\n event: 'page view',\n data: { title: 'Documentation', url: 'https://example.com/docs' },\n};\n\nconst orderPayload = {\n event: 'order complete',\n data: { id: 'ORD-500', total: 199.99, currency: 'EUR' },\n};\n\nexport const pageView: Flow.StepExample = {\n title: 'Page view from SQS',\n description:\n 'A standard SQS message body containing a walker elb event payload as JSON.',\n in: {\n MessageId: 'm-1',\n Body: JSON.stringify(eventPayload),\n },\n out: [['message.ack', 'm-1']],\n};\n\nexport const orderComplete: Flow.StepExample = {\n title: 'Order complete from SQS',\n description: 'Order complete event flowing through the long-poll loop.',\n in: {\n MessageId: 'm-2',\n Body: JSON.stringify(orderPayload),\n },\n out: [['message.ack', 'm-2']],\n};\n\nexport const decoderText: Flow.StepExample = {\n title: 'Text decoder',\n description:\n 'When decoder is \"text\", the body string flows under data.payload.',\n in: { MessageId: 'm-3', Body: 'raw text payload' },\n out: [['message.ack', 'm-3']],\n};\n\nexport const malformedJson: Flow.StepExample = {\n title: 'Malformed JSON nacks',\n description:\n 'Default decoder is JSON. A malformed body throws DecoderError; the source nacks (skips DeleteMessage) so the message redelivers.',\n in: { MessageId: 'm-4', Body: '{not json' },\n out: [['message.nack', 'm-4']],\n};\n","import type { Collector, Trigger } from '@walkeros/core';\nimport { startFlow } from '@walkeros/collector';\nimport type { SyntheticMessage, SyntheticPushResult } from '../types';\n\n/**\n * Content shape for the SQS source trigger.\n *\n * The trigger synthesizes a SyntheticMessage from this partial input and\n * dispatches it through the source's `push()` (the same pipeline the\n * long-poll loop uses).\n */\nexport interface Content {\n MessageId: string;\n Body: string;\n ReceiptHandle?: string;\n Attributes?: Record<string, string>;\n MessageAttributes?: Record<\n string,\n { DataType: string; StringValue?: string }\n >;\n}\n\n/**\n * Trigger result: the recorded ack/nack as `[method, MessageId]` entries.\n * Mirrors the destination's `[method, ...args]` recording shape.\n */\nexport type Result = Array<[string, ...unknown[]]>;\n\ninterface SqsSourceLike {\n type: string;\n push: (content?: SyntheticMessage) => Promise<SyntheticPushResult | void>;\n}\n\nfunction isSqsSource(value: unknown): value is SqsSourceLike {\n if (typeof value !== 'object' || value === null) return false;\n const candidate: { type?: unknown; push?: unknown } = value;\n return candidate.type === 'sqs' && typeof candidate.push === 'function';\n}\n\nfunction findSource(collector: Collector.Instance): SqsSourceLike | undefined {\n for (const source of Object.values(collector.sources ?? {})) {\n if (isSqsSource(source)) return source;\n }\n return undefined;\n}\n\n/**\n * SQS source createTrigger.\n *\n * Boots the collector via startFlow, finds the registered SQS source, and\n * invokes its `push()` with a synthesized message. The source dispatches the\n * synthetic message through the same handler the long-poll loop uses,\n * exercising the full decode / forward / ack-nack pipeline without touching\n * real SQS infrastructure.\n */\nexport const createTrigger: Trigger.CreateFn<Content, Result> = async (\n config: Collector.InitConfig,\n) => {\n let flow: Trigger.FlowHandle | undefined;\n\n const trigger: Trigger.Fn<Content, Result> =\n () =>\n async (content: Content): Promise<Result> => {\n if (!flow) {\n const result = await startFlow(config);\n flow = { collector: result.collector, elb: result.elb };\n }\n\n const source = findSource(flow.collector);\n if (!source) {\n throw new Error(\n 'sqs source not registered in collector, ensure it is configured in sources',\n );\n }\n\n const synthetic: SyntheticMessage = {\n MessageId: content.MessageId,\n Body: content.Body,\n ReceiptHandle: content.ReceiptHandle,\n Attributes: content.Attributes,\n MessageAttributes: content.MessageAttributes,\n };\n\n const result = await source.push(synthetic);\n const recorded: Result = [];\n if (result && typeof result === 'object') {\n if (result.acked) recorded.push(['message.ack', content.MessageId]);\n if (result.nacked) recorded.push(['message.nack', content.MessageId]);\n }\n return recorded;\n };\n\n return {\n get flow() {\n return flow;\n },\n trigger,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAAC;AAAA,EAAA;AAAA;;;ACAA,IAAAC,cAA4B;;;ACA5B,IAAAC,cAAkB;;;ACAlB,iBAAkB;AAKX,IAAM,aAAa,aAAE,KAAK;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;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AAK,CAAC,eAAe,QAAQ,SAAS,CAAC;AAClE,UAAI,OAAO,OAAQ,UAAS,KAAK,CAAC,gBAAgB,QAAQ,SAAS,CAAC;AAAA,IACtE;AACA,WAAO;AAAA,EACT;AAEF,SAAO;AAAA,IACL,IAAI,OAAO;AACT,aAAO;AAAA,IACT;AAAA,IACA,SAAAD;AAAA,EACF;AACF;","names":["examples_exports","settings","import_dev","import_dev","import_dev","import_dev","SettingsSchema","import_dev","settings","SettingsSchema","trigger","k","v","examples_exports","createTrigger","env_exports","step_exports","env_exports","push","noopFn","noopLogger","createMockElbFn","step_exports","createTrigger","trigger","result"]}