@seeka-labs/sdk-apps-server-host 3.7.0 → 3.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # Seeka Apps SDK - Node JS
@@ -1 +1 @@
1
- "use strict";var Ot=Object.create;var L=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var Rt=Object.getOwnPropertyNames;var Ut=Object.getPrototypeOf,Lt=Object.prototype.hasOwnProperty;var Bt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Dt=(e,t)=>{for(var n in t)L(e,n,{get:t[n],enumerable:!0})},ve=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Rt(t))!Lt.call(e,i)&&i!==n&&L(e,i,{get:()=>t[i],enumerable:!(r=_t(t,i))||r.enumerable});return e};var y=(e,t,n)=>(n=e!=null?Ot(Ut(e)):{},ve(t||!e||!e.__esModule?L(n,"default",{value:e,enumerable:!0}):n,e)),$t=e=>ve(L({},"__esModule",{value:!0}),e);var ft=Bt((Kr,gt)=>{"use strict";var Ft=Object.create,$=Object.defineProperty,qt=Object.getOwnPropertyDescriptor,Mt=Object.getOwnPropertyNames,Wt=Object.getPrototypeOf,jt=Object.prototype.hasOwnProperty,Ht=(e,t)=>{for(var n in t)$(e,n,{get:t[n],enumerable:!0})},Pe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Mt(t))!jt.call(e,i)&&i!==n&&$(e,i,{get:()=>t[i],enumerable:!(r=qt(t,i))||r.enumerable});return e},h=(e,t,n)=>(n=e!=null?Ft(Wt(e)):{},Pe(t||!e||!e.__esModule?$(n,"default",{value:e,enumerable:!0}):n,e)),Gt=e=>Pe($({},"__esModule",{value:!0}),e),we={};Ht(we,{ActivityPipelineActivityFilterSourceItemType:()=>We,ActivityPipelineActivityFilterType:()=>qe,AnalyticsLibrary:()=>He,ApiException:()=>Xe,ApiServiceProxyBase:()=>Z,AppPermissionKeys:()=>S,ClickAttributionSourcePlatform:()=>Fe,ConditionComparer:()=>Me,ConditionOperator:()=>je,ConsentMappingMatchType:()=>Ye,ContentIdentificationBehavior:()=>Ge,ConvergePipelineLoggableActivityType:()=>Be,ConvergeVendorDestinationPublishStrategy:()=>Ke,CrossDomainTrackingUtmBehavior:()=>Je,ECommerceContentType:()=>_e,ECommerceFinancialStatus:()=>Le,ECommerceFulfillmentStatus:()=>Ue,ECommercePlatform:()=>Re,IabPrivacyConsentPurposeId:()=>ze,IabPrivacyConsentPurposeIdMap:()=>or,IdentityServiceProxy:()=>Ne,IngestServiceProxy:()=>xe,PrivacyConsentType:()=>Ee,PrivacyDataControlMode:()=>Qe,RegionalConsentGrantOption:()=>Ve,ResponseResultType:()=>be,SdkLogEventLevel:()=>De,SeekaApiHelper:()=>st,SeekaAppCacheManager:()=>O,SeekaAppConfig:()=>Te,SeekaAppHelper:()=>ur,SeekaWebhookCallType:()=>$e,TrackingActivityNames:()=>D,TrackingEventSourceOriginType:()=>Oe,chunk:()=>Q,cloneDeep:()=>hr,dateToUtcDateTimeReferenceString:()=>tt,decryptText:()=>pt,emailAddress:()=>Sr,encryptText:()=>lt,generateNewSessionId:()=>B,getActivityName:()=>Vt,getActivityValue:()=>Tr,getContentIdFromProduct:()=>Nr,getContentNameFromProduct:()=>xr,getIssuer:()=>te,getNestedProperty:()=>vr,getNewAppInstallToken:()=>nt,getNewOrCachedAppInstallToken:()=>re,getRandomNumberString:()=>et,isDeepEqual:()=>Ar,isNumber:()=>yr,isValidSeekaProfileId:()=>br,last:()=>ie,lastOrDefault:()=>Ir,matchActivityPipelineFilters:()=>Cr,md5Hash:()=>rt,parseFloat:()=>ut,parseInt:()=>mr,parseMoney:()=>fr,parseStr:()=>f,phoneNumberToE164:()=>Pr,separatePersonFullName:()=>zt,setNestedProperty:()=>kr,throwOnInvalidWebhookSignature:()=>pr,urls:()=>Er,validateWebhookSignature:()=>ot,webhookSignatureHeaderName:()=>X});gt.exports=Gt(we);var Kt="3.7.0",Ce=h(require("axios")),Te=class{appId;appSecret;ingestUrl;issuerUrl;organisationId;applicationInstallId;runtime;logger;grantedPermissions;transformApiRequest;transformApiResponse;hasAnyPermissions;hasAllPermissions;hasPermission},Z=class{config;constructor(e){this.config=e}transformOptions=async e=>await this.config.transformApiRequest(e);transformResult=async(e,t,n)=>await this.config.transformApiResponse(e,t,n)},Ne=class extends Z{instance;baseUrl;jsonParseReviver=void 0;constructor(e,t,n){super(e),this.instance=n||Ce.default.create(),this.baseUrl=t??"https://api-localdev-env0-seeka.au.ngrok.io"}merge(e,t){let n=this.baseUrl+"/api/identity";n=n.replace(/[?&]$/,"");let r={data:JSON.stringify(e),method:"POST",url:n,headers:{"Content-Type":"application/json",Accept:"application/json"},cancelToken:t};return this.transformOptions(r).then(i=>this.instance.request(i)).catch(i=>{if(Ze(i)&&i.response)return i.response;throw i}).then(i=>this.transformResult(n,i,a=>this.processMerge(a)))}processMerge(e){let t=e.status,n={};if(e.headers&&typeof e.headers=="object")for(let r in e.headers)e.headers.hasOwnProperty(r)&&(n[r]=e.headers[r]);if(t===200){let r=e.data,i=null;return i=JSON.parse(r),Promise.resolve(i)}else if(t===400){let r=e.data,i=null;return i=JSON.parse(r),P("A server side error occurred.",t,r,n,i)}else if(t===401){let r=e.data,i=null;return i=JSON.parse(r),P("A server side error occurred.",t,r,n,i)}else if(t===422){let r=e.data,i=null;return i=JSON.parse(r),P("A server side error occurred.",t,r,n,i)}else if(t!==200&&t!==204){let r=e.data;return P("An unexpected server error occurred.",t,r,n)}return Promise.resolve(null)}},xe=class extends Z{instance;baseUrl;jsonParseReviver=void 0;constructor(e,t,n){super(e),this.instance=n||Ce.default.create(),this.baseUrl=t??"https://api-localdev-env0-seeka.au.ngrok.io"}batch(e,t){let n=this.baseUrl+"/api/ingest";n=n.replace(/[?&]$/,"");let r={data:JSON.stringify(e),method:"POST",url:n,headers:{"Content-Type":"application/json"},cancelToken:t};return this.transformOptions(r).then(i=>this.instance.request(i)).catch(i=>{if(Ze(i)&&i.response)return i.response;throw i}).then(i=>this.transformResult(n,i,a=>this.processBatch(a)))}processBatch(e){let t=e.status,n={};if(e.headers&&typeof e.headers=="object")for(let r in e.headers)e.headers.hasOwnProperty(r)&&(n[r]=e.headers[r]);if(t===202){let r=e.data;return Promise.resolve(null)}else if(t===400){let r=e.data,i=null;return i=JSON.parse(r),P("A server side error occurred.",t,r,n,i)}else if(t===401){let r=e.data,i=null;return i=JSON.parse(r),P("A server side error occurred.",t,r,n,i)}else if(t===422){let r=e.data,i=null;return i=JSON.parse(r),P("A server side error occurred.",t,r,n,i)}else if(t!==200&&t!==204){let r=e.data;return P("An unexpected server error occurred.",t,r,n)}return Promise.resolve(null)}},be=(e=>(e.Undefined="undefined",e.Success="success",e.Failed="failed",e))(be||{}),Ee=(e=>(e.Unknown="unknown",e.Informed="informed",e.Implied="implied",e.Explicit="explicit",e.Active="active",e.Passive="passive",e))(Ee||{}),Oe=(e=>(e.Browser="browser",e.Server="server",e.Mobile="mobile",e.Desktop="desktop",e.PhysicalStore="physicalStore",e.Email="email",e.Phone="phone",e.Chat="chat",e.Automatic="automatic",e))(Oe||{}),D=(e=>(e.Undefined="undefined",e.PageViewOrganic="pageViewOrganic",e.PageViewUtmAttributed="pageViewUtmAttributed",e.AddPaymentMethod="addPaymentMethod",e.AddToWishlist="addToWishlist",e.ContactMessage="contactMessage",e.Custom="custom",e.SyncCart="syncCart",e.Order="order",e.InitiateCheckout="initiateCheckout",e.AddToCart="addToCart",e.RemoveFromCart="removeFromCart",e.OneTimeItemPurchase="oneTimeItemPurchase",e.SubscriptionItemPurchase="subscriptionItemPurchase",e.ViewProduct="viewProduct",e.ViewPage="viewPage",e.ApplyPromotionalCode="applyPromotionalCode",e.KeywordSearch="keywordSearch",e.UserLoginSignup="userLoginSignup",e.UserLogin="userLogin",e.NewsletterSignup="newsletterSignup",e.Lead="lead",e.ChangeProductAttribute="changeProductAttribute",e.FilterItemsByAttribute="filterItemsByAttribute",e.Schedule="schedule",e.ViewContentItem="viewContentItem",e.StartTrial="startTrial",e))(D||{}),_e=(e=>(e.Undefined="undefined",e.SingleProduct="singleProduct",e.SingleVariant="singleVariant",e.Collection="collection",e))(_e||{}),Re=(e=>(e.None="none",e.BigCommerce="bigCommerce",e.Shopify="shopify",e.OrderGroove="orderGroove",e.Magento="magento",e.Generic="generic",e.WooCommerce="wooCommerce",e.Demandware="demandware",e))(Re||{}),Ue=(e=>(e.Undefined="undefined",e.Fulfilled="fulfilled",e.NoneFulfilled="noneFulfilled",e.PartiallyFulfilled="partiallyFulfilled",e.RestockedOrCancelled="restockedOrCancelled",e.Pending="pending",e))(Ue||{}),Le=(e=>(e.Undefined="undefined",e.Pending="pending",e.Authorized="authorized",e.PartiallyPaid="partiallyPaid",e.Paid="paid",e.PartiallyRefunded="partiallyRefunded",e.Refunded="refunded",e.Voided="voided",e))(Le||{}),Be=(e=>(e.Generic="generic",e.ActivityIngress="activityIngress",e.ActivityEgress="activityEgress",e.UserProfile="userProfile",e.SdkLog="sdkLog",e.Detections="detections",e.ActivityEgressFilter="activityEgressFilter",e.Diagnosis="diagnosis",e.PipelineIntegrationOutput="pipelineIntegrationOutput",e))(Be||{}),De=(e=>(e.Information="information",e.Warning="warning",e.Error="error",e.Verbose="verbose",e))(De||{}),$e=(e=>(e.None="none",e.Probe="probe",e.AppInstalled="appInstalled",e.IdentityChanged="identityChanged",e.ActivityAccepted="activityAccepted",e.AppInstallSettingsUpdated="appInstallSettingsUpdated",e.AppUninstalled="appUninstalled",e.BrowserSdkPlugin="browserSdkPlugin",e))($e||{}),Fe=(e=>(e.Unknown="unknown",e.Google="google",e.Meta="meta",e.Snapchat="snapchat",e.Pinterest="pinterest",e.TikTok="tikTok",e))(Fe||{}),qe=(e=>(e.Undefined="undefined",e.PurchaseMade="purchaseMade",e.ActivityTracked="activityTracked",e))(qe||{}),Me=(e=>(e.Undefined="undefined",e.And="and",e.Or="or",e))(Me||{}),We=(e=>(e.Undefined="undefined",e.Domain="domain",e.Pipeline="pipeline",e.Wildcard="wildcard",e.Url="url",e.PagePath="pagePath",e))(We||{}),je=(e=>(e.Undefined="undefined",e.Equals="equals",e.NotEquals="notEquals",e.Contains="contains",e.NotContains="notContains",e.StartsWith="startsWith",e.EndsWith="endsWith",e.IsNull="isNull",e.NotNull="notNull",e.IsTrue="isTrue",e.IsFalse="isFalse",e.GreaterThanOrEquals="greaterThanOrEquals",e.LessThanOrEquals="lessThanOrEquals",e.GreaterThan="greaterThan",e.LessThan="lessThan",e.Before="before",e.After="after",e.Between="between",e.In="in",e.NotIn="notIn",e.Regex="regEx",e.Any="any",e))(je||{}),He=(e=>(e.Undefined="undefined",e.Seeka="seeka",e.DynamicYield="dynamicYield",e.Segment="segment",e.FacebookPixel="facebookPixel",e.GoogleAnalytics="googleAnalytics",e.Braze="braze",e.SnapchatPixel="snapchatPixel",e.Pinterest="pinterest",e.TikTokPixel="tikTokPixel",e.GoogleAds="googleAds",e))(He||{}),Ge=(e=>(e.Default="default",e.Sku="sku",e.ProductId="productId",e.VariantId="variantId",e.ProductIdAndVariantIdUnderscore="productIdAndVariantIdUnderscore",e.VariantIdOrProductId="variantIdOrProductId",e))(Ge||{}),Ke=(e=>(e.DeliverAllTraitsAndDeliverAllEvents="deliverAllTraitsAndDeliverAllEvents",e.DeliverAllTraitsAndDeliverEventsOnlyIfMaxWeightedTraitsPresent="deliverAllTraitsAndDeliverEventsOnlyIfMaxWeightedTraitsPresent",e.DeliverMaxWeightedTraitsOnlyAndDeliverAllEvents="deliverMaxWeightedTraitsOnlyAndDeliverAllEvents",e.DeliverMaxWeightedTraitsOnlyAndDeliverEventsOnlyIfMaxWeightedTraitsPresent="deliverMaxWeightedTraitsOnlyAndDeliverEventsOnlyIfMaxWeightedTraitsPresent",e))(Ke||{}),Je=(e=>(e.None="none",e.SessionPassthrough="sessionPassthrough",e.UrlPassthrough="urlPassthrough",e))(Je||{}),Ve=(e=>(e.Unset="unset",e.Granted="granted",e.Denied="denied",e))(Ve||{}),ze=(e=>(e.Undefined="undefined",e.MeasureAdvertisingPerformance="measureAdvertisingPerformance",e))(ze||{}),Ye=(e=>(e.Undefined="undefined",e.AllOf="allOf",e.AnyOf="anyOf",e))(Ye||{}),Qe=(e=>(e.Disabled="disabled",e.Explicit="explicit",e.Implicit="implicit",e))(Qe||{}),Xe=class extends Error{message;status;response;headers;result;constructor(e,t,n,r,i){super(),this.message=e,this.status=t,this.response=n,this.headers=r,this.result=i}isApiException=!0;static isApiException(e){return e.isApiException===!0}};function P(e,t,n,r,i){throw i??new Xe(e,t,n,r,null)}function Ze(e){return e&&e.isAxiosError===!0}var E=require("openid-client"),ee=h(require("winston")),Y=h(require("memory-cache")),ke="seeka:sdk",O=class{constructor(e,t){this.appId=e,this.appInstallationId=t}appId;appInstallationId;set=async(e,t,n)=>{let r=this.getKey(e);Y.default.put(r,JSON.stringify(t),n)};getOrSet=async(e,t,n)=>{let r=this.getKey(e),i=Y.default.get(r);if(i){let s=JSON.parse(i);return n&&await n(s),s}let a=await t();return a?(Y.default.put(r,JSON.stringify(a.value),a.expiryAbsoluteMilliseconds),a.value):null};getKey=e=>this.appInstallationId?`${ke}:${this.appId}:${this.appInstallationId}:${e}`:`${ke}:${this.appId}:${e}`},Jt=h(require("crypto")),B=()=>{let e=tt(new Date),t=et();return`${e}.${t}`},Vt=e=>{let t=Object.keys(D),n=e.toLowerCase(),r=t.find(i=>i.toLowerCase()===n);return r?D[r]:"custom"},et=()=>Math.floor(Math.random()*(9999999999-1e9)+1e9).toString(),tt=e=>{let t=(e.getUTCMonth()+1).toString();t.length<2&&(t="0"+t);let n=e.getUTCDate().toString();n.length<2&&(n="0"+n);let r=e.getUTCHours().toString();r.length<2&&(r="0"+r);let i=e.getUTCMinutes().toString();i.length<2&&(i="0"+i);let a=e.getUTCSeconds().toString();return a.length<2&&(a="0"+a),`${e.getUTCFullYear()}${t}${n}.${r}${i}${a}`},rt=e=>Jt.createHash("md5").update(e).digest("hex"),zt=e=>{if(!e)return{firstName:null,lastName:null};let t=e.trim().split(" ");return t.length===1?{firstName:e,lastName:null}:t.length===2?{firstName:t[0],lastName:t[1]}:{firstName:t[0],lastName:t.slice(1).join(" ")}},Q=(e,t)=>e.reduce((n,r,i)=>{let a=Math.floor(i/t);return n[a]||(n[a]=[]),n[a].push(r),n},[]),te=async e=>{let t={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.debug("Seeka auth: getting issuer",{...t}):console.debug("Seeka auth: getting issuer",{...t});let n=new O(e.appId,e.applicationInstallId),r=rt(e.issuerUrl+"_"+e.appId),i=await n.getOrSet(r,async()=>{try{let a=await Yt(e);return!a||!a.meta||!a.raw?null:(e.logger?e.logger.verbose("Seeka auth: got issuer from remote",{...t}):console.debug("Seeka auth: got issuer from remote",{...t}),{value:a.meta,expiryAbsoluteMilliseconds:1e3*60*60})}catch(a){return e.logger?e.logger.error("Seeka auth: failed getting issuer",{...t,ex:ee.default.exceptions.getAllInfo(a)}):console.error("Seeka auth: failed getting issuer",{...t}),null}},async()=>{e.logger?e.logger.verbose("Seeka auth: got issuer from cache",{...t}):console.debug("Seeka auth: got issuer from cache",{...t})});return i===null?null:new E.Configuration(i.serverMetadata,i.clientId,e.appSecret)},Yt=async e=>{let t={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.verbose("Seeka auth: discovering issuer from remote",{...t}):console.info("Seeka auth: discovering issuer from remote",{...t});try{let n=e.appId.replace(/-/g,""),r=await(0,E.discovery)(new URL(e.issuerUrl),n,void 0,(0,E.None)(),{timeout:1e4});return e.logger?e.logger.verbose("Seeka auth: discovered issuer from remote",{...t,client_id:r.clientMetadata().client_id}):console.info("Seeka auth: discovered issuer from remote",{...t,client_id:r.clientMetadata().client_id}),{meta:{serverMetadata:r.serverMetadata(),clientMetadata:r.clientMetadata(),timeout:r.timeout,clientId:n},raw:r}}catch(n){return e.logger?e.logger.error("Seeka auth: failed discovering issuer from remote",{...t,ex:ee.default.exceptions.getAllInfo(n)}):console.error("Seeka auth: failed discovering issuer from remote",{...t,err:n}),null}},Qt=async e=>{let t={applicationId:e.appId,issuer:{url:e.issuerUrl}},n=await te(e);if(!n)return null;try{let r=await(0,E.clientCredentialsGrant)(n,{resource:n.clientMetadata().client_id}),i={...t,token:{expires_at:r.expires_at,token_type:r.token_type,scope:r.scope}};return e.logger?e.logger.verbose("Seeka auth: got client access token from server",{...i}):console.info("Seeka auth: got app client token from server",{...i}),{token_type:r.token_type,access_token:r.access_token,expires_in:r.expires_in,id_token:r.id_token,refresh_token:r.refresh_token,scope:r.scope,authorization_details:r.authorization_details}}catch(r){let i={...t,error:r};return e.logger?e.logger.error("Seeka auth: failed to get client access token from server",{...i}):console.error("Seeka auth: failed to get client access token from server",{...i,err:ee.default.exceptions.getAllInfo(r)}),null}},nt=async(e,t)=>{let n={applicationId:t.appId,issuer:{url:t.issuerUrl}},r=await te(t);if(!r||!r)return null;try{let i=await(0,E.genericGrantRequest)(r,"app_install_token",{applicationInstallId:t.applicationInstallId,access_token:e,scope:"Seeka.API.Ingest"}),a={...n,token:{expires_at:i.expires_at,token_type:i.token_type,scope:i.scope}};return t.logger?t.logger.verbose("Seeka auth: got app access token from server",{...a}):console.info("Seeka auth: got app access token from server",{...a}),{token_type:i.token_type,access_token:i.access_token,expires_in:i.expires_in,id_token:i.id_token,refresh_token:i.refresh_token,scope:i.scope,authorization_details:i.authorization_details}}catch(i){let a={...n,error:i};return t.logger?t.logger.error("Seeka auth: failed to get app access token from server",{...a}):console.debug("Seeka auth: failed to get app access token from server",{...a}),null}},re=async e=>{let t=new O(e.appId,e.applicationInstallId),n={applicationId:e.appId,issuer:{url:e.issuerUrl}};return await t.getOrSet("auth:token:appinstall",async()=>{let r=await Qt(e);if(!r||!r.access_token)return null;let i=await nt(r.access_token,e);return i?{value:i,expiryAbsoluteMilliseconds:((i.expires_in>r.expires_in?r.expires_in:i.expires_in)||900*1e3)-60*1e3}:null},async()=>{e.logger?e.logger.verbose("Seeka auth: got app token from cache",{...n}):console.debug("Seeka auth: got app token from cache",{...n})})},it="https://router.seeka.services",Xt="https://router.seeka.services/tel/otel",at="https://account.seeka.app",Zt=(e,t,n,r,i)=>{let a=new Te;return a.appId=e.applicationId,a.appSecret=t,a.ingestUrl=process.env.SEEKA_INGEST_URL||it,a.issuerUrl=process.env.SEEKA_ISSUER_URL||at,a.organisationId=e.organisationId,a.applicationInstallId=e.applicationInstallId,a.runtime={type:"sdk/js/apps-server",ver:Kt.split("-")[0],client:n},a.logger=i,a.grantedPermissions=r,a.transformApiRequest=s=>er(a,s),a.transformApiResponse=async(s,c,o)=>tr(a,s,c,o),a.hasAnyPermissions=s=>!a.grantedPermissions||a.grantedPermissions.length===0?!1:!s||s.length===0?!0:s.some(c=>a.grantedPermissions.includes(c)),a.hasAllPermissions=s=>!a.grantedPermissions||a.grantedPermissions.length===0?!1:!s||s.length===0?!0:s.every(c=>a.grantedPermissions.includes(c)),a.hasPermission=s=>!a.grantedPermissions||a.grantedPermissions.length===0?!1:s?a.grantedPermissions.includes(s):!0,a},er=async(e,t)=>{let n=await re(e);if(!n||!n.access_token)throw new Error("Could not get access token for API request");return t.headers={...t.headers,"X-OrgId":e.organisationId,Authorization:"Bearer "+n?.access_token},t},tr=async(e,t,n,r)=>(n.data=JSON.stringify(n.data),r(n)),S={identity:{receiveFull:"Identity.Receive.Pii",send:"Identity.Send"},activity:{receiveAnon:"Activity.Receive.Anon",receiveFull:"Activity.Receive.Pii",send:"Activity.Send"}},rr=h(require("axios")),nr=h(require("http")),ir=h(require("https")),ar=new nr.default.Agent({keepAlive:!0,scheduling:"fifo"}),sr=new ir.default.Agent({keepAlive:!0,scheduling:"fifo"}),Ae=e=>{let t=rr.default.create({httpAgent:ar,httpsAgent:sr});return t.interceptors.request.use(function(n){let r={url:n.url,method:n.method};return process.env.LOGGING_LEVEL==="silly"&&(r={...r,body:n.data,params:n.params}),e.logger?e.logger.debug(`Seeka API: making call to ${r.url}`,{...r}):console.debug(`Seeka API: making call to ${r.url}`,{...r}),n},function(n){let r={error:n};return e.logger?e.logger.http("Seeka API: failed to send request",{...r}):console.debug("Seeka API: failed to send request",{...r}),Promise.reject(n)}),t.interceptors.response.use(function(n){let r={url:n.request?.url||n.config.url,method:n.request?.method||n.config.method,response:{status:n.status}};return e.logger?e.logger.http(`Seeka API: call to ${r.url} succeeded`,{...r}):console.debug(`Seeka API: call to ${r.url} succeeded`,{...r}),n},function(n){let{code:r,status:i,message:a}=n,{headers:s,url:c,method:o}=n?.config,l={code:r,status:i,message:a,headers:s,url:c,method:o,content:n?.response?.data};return e.logger?e.logger.error(`Seeka API: call to ${l.url} failed`,{...l}):console.error(`Seeka API: call to ${l.url} failed`,{...l}),Promise.reject(n)}),t},Se={getIdentityService:e=>new Ne(e,e.ingestUrl,Ae(e)),getIngestService:e=>new xe(e,e.ingestUrl,Ae(e))},st=class{constructor(e){this.config=e,this.ingestionService=Se.getIngestService(e),this.identityService=Se.getIdentityService(e)}config;maxBatchSize=50;refreshOrPrimeTokenCache=async()=>{await re(this.config)};ingestionService;identityService;checkPermission=(e,t)=>{if(!this.config.hasPermission(e))throw new Error("Cannot perform operation "+t+" on installationId "+this.config.applicationInstallId+" without permission "+e+". Currently granted permissions: "+(this.config.grantedPermissions?this.config.grantedPermissions.join(", "):"none"));return!0};mergeIdentity=async(e,t)=>{this.checkPermission(S.identity.send,"mergeIdentity");let n=B();return(await this.identityService.merge({id:e,src:{method:"",origin:t.origin,time:void 0,loc:t.loc,sess:n,diag:process.env.SEEKA_DEBUG_ENABLED==="true"?n:void 0,runtime:this.config.runtime}})).result?.personId};mergeIdentityBatch=async(e,t)=>{this.checkPermission(S.identity.send,"mergeIdentityBatch");let n=B();if(e.length===0){this.config.logger?.debug("No identities in batch");return}let r={method:"",origin:t.origin,time:void 0,loc:t.loc,sess:n,diag:process.env.SEEKA_DEBUG_ENABLED==="true"?n:void 0,runtime:this.config.runtime},i=Q(e,this.maxBatchSize);if(i.length>1&&this.config.logger&&this.config.logger.debug(`Identity batch size ${e} is greater than ${this.maxBatchSize}, splitting into ${i.length} batches`),await this.trackActivityBatchRaw({data:i[0].map(a=>({id:{id:a||{},src:{...r}}}))}),i.length>1){let a=i.map((s,c)=>c===0?Promise.resolve():(this.config.logger?.verbose(`Processing identity batch ${c+1} of ${i.length}`),this.trackActivityBatchRaw({data:s.map(o=>({id:{id:o||{},src:{...r}}}))})));await Promise.all(a)}};trackActivityBatch=async(e,t)=>{this.checkPermission(S.activity.send,"trackActivityBatch");let n=B();if(e.length===0){this.config.logger?.debug("No activities in batch");return}let r={method:"",origin:t.origin,time:void 0,loc:t.loc,sess:n,diag:process.env.SEEKA_DEBUG_ENABLED==="true"?n:void 0,runtime:this.config.runtime},i=Q(e,this.maxBatchSize);if(i.length>1&&this.config.logger&&this.config.logger.debug(`Activity batch size ${e.length} is greater than ${this.maxBatchSize}, splitting into ${i.length} batches`),await this.trackActivityBatchRaw({data:i[0].map(a=>({ev:{id:a.profile||{},src:{...r},payload:a.activity}}))}),i.length>1){let a=i.map((s,c)=>c===0?Promise.resolve():(this.config.logger?.verbose(`Processing activity batch ${c+1} of ${i.length}`),this.trackActivityBatchRaw({data:s.map(o=>({ev:{id:o.profile||{},src:{...r},payload:o.activity}}))})));await Promise.all(a)}};trackActivityBatchRaw=async e=>{await this.ingestionService.batch(e)};trackActivityForProfileId=async(e,t,n)=>{this.checkPermission(S.activity.send,"trackActivityForProfileId"),await this.trackActivityForProfileIdBatch([e],t,n)};trackActivityForProfileIdBatch=async(e,t,n)=>{this.checkPermission(S.activity.send,"trackActivityForProfileIdBatch"),await this.trackActivityBatch(e.map(r=>({activity:r,profile:t?{seekaPId:t}:void 0})),n)};trackActivityForProfile=async(e,t,n)=>{this.checkPermission(S.activity.send,"trackActivityForProfile"),await this.trackActivityForProfileBatch([e],t,n)};trackActivityForProfileBatch=async(e,t,n)=>{this.checkPermission(S.activity.send,"trackActivityForProfileBatch"),await this.trackActivityBatch(e.map(r=>({activity:r,profile:t})),n)}},or={measureAdvertisingPerformance:7},cr=h(require("crypto")),X="x-seeka-signature-sha256",ot=(e,t,n)=>{if(!t)return!1;let r=null;if(t.get&&typeof t.get=="function")r=t.get(X);else{let a=t[X];a&&(Array.isArray(a)&&a.length>0?r=a[0]:(typeof a=="string"||a instanceof String)&&(r=a))}if(!r)return!1;let i=lr(e,n)===r;return i||console.warn("Invalid webhook signature"),i},lr=(e,t)=>cr.createHmac("sha256",e).update(t).digest("hex"),pr=(e,t,n)=>{if(!ot(e,t,n))throw new Error("Invalid webhook signature")},b=h(require("crypto")),ct="aes-192-cbc",lt=(e,t)=>{if(!e)return"";if(!t)throw new Error("Secret is required to encrypt data");let n=b.default.scryptSync(t,"salt",24),r=b.default.randomBytes(16),i=b.default.createCipheriv(ct,n,r);return[i.update(e,"utf8","hex")+i.final("hex"),Buffer.from(r).toString("hex")].join("|")},pt=(e,t)=>{if(!e)return"";if(!t)throw new Error("Secret is required to decrypt data");let[n,r]=e.split("|");if(!r)throw new Error("IV not found");let i=b.default.scryptSync(t,"salt",24),a=b.default.createDecipheriv(ct,i,Buffer.from(r,"hex"));return a.update(n,"hex","utf8")+a.final("utf8")},dr=class{constructor(e){this.appSecret=e}appSecret;encryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to encrypt data");return lt(e,this.appSecret)};decryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to decrypt data");return pt(e,this.appSecret)}},ur=class dt{constructor(t,n){this.context=t,this.api=new st(t.config),this.appCache=new O(t.config.appId),this.appInstallCache=new O(t.config.appId,t.config.applicationInstallId),this.crypto=new dr(t.config.appSecret),this.logger=n}context;appCache;appInstallCache;api;logger;crypto;static create=(t,n,r,i,a)=>new dt({config:Zt({...n},t,{type:r.name,ver:r.version.split("-")[0]},i,a)},a)},gr=h(require("winston")),ne=require("lodash-es"),f=e=>e==null||e===""||String(e).trim()===""?"":String(e);function ut(e){if(e==null||e==="")return 0;let t=e.toString().replace(/[^0-9.]/g,"");return Number.isNaN(Number(t))?0:Number(t)}function fr(e){if(e==null||e===0||e==="")return+"0.00";let t=ut(e);return Number(t.toFixed(3))}function mr(e){return e==null||e===""||Number.isNaN(Number(e.toString()))?0:Math.floor(Number(e))}function hr(e){return JSON.parse(JSON.stringify(e))}function yr(e){return/^-?\d+$/.test(e)}function Ir(e){if(!(e==null||e.length===0))return ie(e)}function ie(e){return ie(e)}function vr(e,t){return(0,ne.get)(e,t)}function kr(e,t,n){return(0,ne.set)(e,t,n)}function Ar(e,t){return(0,ne.isEqual)(e,t)}function Sr(e){return e?e.trim().toLowerCase():""}function Pr(e){return e==null?"":(e=e.trim().replace(/-/gi,"").replace(/\(/gi,"").replace(/\)/gi,"").replace(/ /g,"").replace(/\+/g,""),e)}var wr=["order","subscriptionItemPurchase","oneTimeItemPurchase"],Cr=(e,t,n)=>{if(!e.activity)return[];let r=e.activity,i=r.activityName==="custom"?r.activityNameCustom:r.activityName;if(!i)return[];let a=i.toLowerCase(),s=[];return t.forEach(c=>{if(!c)return;switch(c.type){case"activityTracked":{if(!c.activityNames||!c.activityNames.find(p=>p.toLowerCase()===a))return;n.verbose("Matched activity tracked filter",{filter:c,activityName:i});break}case"purchaseMade":{if(!r.activityName||!wr.includes(r.activityName))return;n.verbose("Matched purchase made activity filter",{filter:c,activityName:i});break}default:{n.warn("Unknown activity filter type",{filter:c});return}}let o=c.sourceFilter;if(!o)return;let l=e.source,d;try{d=l?.loc?new URL(l.loc).hostname.toLowerCase():null}catch(p){n.error("Failed to parse activity source URL",{ex:gr.default.exceptions.getAllInfo(p),activitySource:l}),d=null}let k=l?.pipeline?.convergePipelineIntegrationInstanceId?.toLowerCase(),u=o.filters?o.filters.map(p=>{switch(p.type){case"wildcard":return n.verbose("Matched wildcard source filter",{sourceFilter:p}),!0;case"domain":return!d||!p.key?!1:d===p.key.toLowerCase()?(n.verbose("Matched domain source filter",{sourceFilter:p,activityHostname:d}),!0):!1;case"pipeline":return!k||!p.key?!1:k===p.key.toLowerCase()?(n.verbose("Matched pipeline source filter",{sourceFilter:p,sourceConvergePipelineIntegrationInstanceId:k}),!0):!1}}):[];switch(o.comparer){case"and":{u.every(p=>p===!0)&&s.push(c);break}case"or":{u.some(p=>p===!0)&&s.push(c);break}default:{n.warn("Unknown source filter comparer",{sourceFilters:o});break}}}),s},Tr=(e,t=!1)=>{let n=e.commerce,r=n?.totalPrice||n?.products?.map(a=>(a.unitPrice||0)*(a.quantity||1)).reduce((a,s)=>a+s,0)||void 0,i=n?.currencyCode||null;if((!r||r<=0)&&(r=e?.lead?.predictedLtv||e?.lead?.predictedValue,r&&e?.lead?.currencyCode&&(i=e?.lead?.currencyCode||null)),(!r||r<=0)&&(r=e?.contentItem?.value,r&&e?.contentItem?.currencyCode&&(i=e?.contentItem?.currencyCode||null)),(!r||r<=0)&&(e?.contentItem?.items&&e?.contentItem?.items.length>0&&(r=e?.contentItem?.items.map(a=>a&&a.unitPrice?a.unitPrice*(a.quantity||1):0).reduce((a,s)=>a+s,0)),r&&(i=e?.contentItem?.currencyCode||e?.commerce?.currencyCode||null,!i))){let a=e?.contentItem?.items?.filter(s=>s.currencyCode)||[];a.length>0&&(i=a[0].currencyCode||null)}if((!r||r<=0)&&e?.commerce?.products&&e?.commerce?.products.length>0&&(r=e?.commerce?.products.map(a=>a&&a.unitPrice?a.unitPrice*(a.quantity||1):0).reduce((a,s)=>a+s,0),r&&(i=e?.commerce?.currencyCode||null,!i))){let a=e?.commerce?.products?.filter(s=>s.currencyCode)||[];a.length>0&&(i=a[0].currencyCode||null)}return(!r||r<=0)&&!i?null:{value:r===0&&t?null:r||null,currencyCode:i}};function Nr(e,t,n){if(!e)return;let r=t.processing?.contentIdentificationBehavior,i=null;(n=="googleAnalytics"||n=="googleAds")&&(t.analytics?.libraries?.googleAnalytics?.merchant?.productItemIdBehavior!=null&&(r=t.analytics?.libraries?.googleAnalytics?.merchant?.productItemIdBehavior),i=f(t.analytics?.libraries?.googleAnalytics?.merchant?.productItemIdPrefix));let a;switch(r){case"sku":a=e?.sku;break;case"productId":a=e?.productIdentifier;break;case"variantId":a=e?.variantIdentifier;break;case"productIdAndVariantIdUnderscore":f(e.variantIdentifier)&&f(e.productIdentifier)?a=`${e.productIdentifier}_${e.variantIdentifier}`:f(e.variantIdentifier)?a=e.variantIdentifier:a=e.productIdentifier;break;case"variantIdOrProductId":f(e.variantIdentifier)?a=e.variantIdentifier:a=e.productIdentifier;break;default:a=f(e?.sku)||f(e?.variantIdentifier)||f(e?.productIdentifier);break}return i?`${i}${a}`:a}function xr(e,t){return f(e?.variantName)||f(e?.productName)}function br(e){if(!e||e.trim().length===0)return!1;let t=e.split(".").filter(n=>n.trim().length>0);return!(t.length!==4||t[0].toLowerCase()!=="sk".toLowerCase()||t[1].toLowerCase()!=="1".toLowerCase()||isNaN(parseInt(t[2],10))||isNaN(parseInt(t[3],10)))}var Er={defaultIssuerUrl:at,defaultTelemetryUrl:Xt,defaultIngestUrl:it}});var jr={};Dt(jr,{appLogger:()=>Tt,backgroundJobLogger:()=>$r,checkAuth:()=>Pt,childLogger:()=>C,connect:()=>ht,createOrUpdateInstallation:()=>Lr,deleteInstallation:()=>Br,disconnect:()=>yt,generateAppUiHttpRequestResponse:()=>Fr,getAccessTokenAndCheck:()=>me,getKey:()=>U,getList:()=>le,getOrCreate:()=>_r,getOrCreateClient:()=>I,getSeekaBrowserPlugin:()=>Wr,getSeekaBrowserPluginByName:()=>bt,isConnected:()=>se,listInstallations:()=>Ur,remove:()=>de,set:()=>pe,startServices:()=>ue,stopServices:()=>Rr,tryGet:()=>ce,tryGetInstallation:()=>W,webhookLogger:()=>Dr});module.exports=$t(jr);var mt=require("redis"),F=y(require("winston")),q=y(ft()),Or=()=>{let e=process.env.REDIS_CONNECTION_TLS==="true"?"rediss://":"redis://";return process.env.REDIS_CONNECTION_USER&&process.env.REDIS_CONNECTION_PASSWORD?`${e}${process.env.REDIS_CONNECTION_USER}:${process.env.REDIS_CONNECTION_PASSWORD}@${process.env.REDIS_CONNECTION_HOST}:${process.env.REDIS_CONNECTION_PORT}`:`${e}${process.env.REDIS_CONNECTION_HOST}:${process.env.REDIS_CONNECTION_PORT}`},ae="__SEEKA_REDIS_CLIENT__",I=e=>{if(global[ae])return global[ae];let t=(0,mt.createClient)({url:Or(),disableClientInfo:!0}).on("error",n=>e.error("Redis Client ",{ex:F.exceptions.getAllInfo(n)}));return global[ae]=t,t},ht=async e=>{await I(e).connect()},se=async e=>I(e).isOpen,yt=async e=>{I(e).destroy()},It=e=>`seeka:app:${process.env.SEEKA_APP_ID}:${e}`,U=(e,t)=>`${It(e)}:${t}`,_=e=>e==="install",vt=()=>{let e=process.env.DATA_ENCRYPTION_KEY;if(!e)throw new Error("DATA_ENCRYPTION_KEY is required to encrypt/decrypt installation state");return e},kt=e=>{if(!e)return!1;let t=e.split("|");if(t.length!==2)return!1;let[n,r]=t;return!n||!r?!1:/^[0-9a-f]+$/i.test(n)&&/^[0-9a-f]{32}$/i.test(r)},oe=e=>{if(!kt(e))return{plainText:e,wasEncrypted:!1};let t=vt();return{plainText:(0,q.decryptText)(e,t),wasEncrypted:!0}},R=e=>{if(kt(e))return{encryptedText:e,wasEncrypted:!0};let t=vt();return{encryptedText:(0,q.encryptText)(e,t),wasEncrypted:!1}};async function _r(e,t,n,r="string",i){let a=U(e,t),s=I(i),c=await At(s,a);if(c){if(r==="string"&&_(e)){let{plainText:o,wasEncrypted:l}=oe(c);if(!l){let{encryptedText:d}=R(c);await s.set(a,d)}return JSON.parse(o)}return JSON.parse(c)}if(r==="json")await s.json.set(a,"$",n);else{let o=JSON.stringify(n);if(_(e)){let{encryptedText:l}=R(o);await s.set(a,l)}else await s.set(a,o)}return n}async function ce(e,t,n="string",r){let i=U(e,t),a=I(r);if(n==="json"){let s=await a.json.get(i);if(s)return s}else{let s=await At(a,i);if(s){if(_(e)){let{plainText:c,wasEncrypted:o}=oe(s);if(!o){let{encryptedText:l}=R(s);await a.set(i,l)}return JSON.parse(c)}return JSON.parse(s)}}return null}async function le(e,t){let n=It(e),r=I(t),i=await r.keys(`${n}:*`),a=await r.mGet(i);if(a){let s=[];for(let c=0;c<a.length;c++){let o=a[c],l=i[c];if(!o)continue;let d=o;if(_(e)){let{plainText:k,wasEncrypted:u}=oe(d);if(!u){let{encryptedText:p}=R(d);await r.set(l,p)}s.push(JSON.parse(k))}else s.push(JSON.parse(d))}return s}return[]}async function pe(e,t,n,r="string",i){let a=U(e,t),s=I(i);if(r==="json")await s.json.set(a,"$",n);else{let c=JSON.stringify(n);if(_(e)){let{encryptedText:o}=R(c);await s.set(a,o)}else await s.set(a,c)}}async function de(e,t,n){let r=U(e,t);await I(n).del(r)}async function At(e,t){let n=await e.get(t);return typeof n=="string"?n:n?n.toString():""}var ue=async e=>{e.debug(`Trying to connect to Redis - ${process.env.REDIS_CONNECTION_HOST}`);try{await se(e)?e.verbose(`Redis already connected - ${process.env.REDIS_CONNECTION_HOST}`):(e.profile("service.redis.connect"),await ht(e),e.profile("service.redis.connect"),e.debug(`Redis connected - ${process.env.REDIS_CONNECTION_HOST}`))}catch(t){throw e.error(`Failed to connect to Redis - ${process.env.REDIS_CONNECTION_HOST}`,{ex:F.exceptions.getAllInfo(t)}),t}},Rr=async e=>{e.debug(`Trying to disconnect from Redis - ${process.env.REDIS_CONNECTION_HOST}`);try{await se(e)===!1?e.verbose(`Redis already disconnected - ${process.env.REDIS_CONNECTION_HOST}`):(e.profile("service.redis.disconnect"),await yt(e),e.profile("service.redis.disconnect"),e.verbose(`Redis disconnected - ${process.env.REDIS_CONNECTION_HOST}`))}catch(t){throw e.error(`Failed to disconnect from Redis - ${process.env.REDIS_CONNECTION_HOST}`,{ex:F.exceptions.getAllInfo(t)}),t}};var M="install",W=async(e,t,n)=>{let r=await ce(M,e,"string",n);if(r==null&&t)throw n.error(`Seeka installation ${e} not found`),new Error(`Seeka installation ${e} not found`);return r},Ur=async e=>await le(M,e),Lr=async(e,t)=>{e.installationState||(e.installationState={}),e.installedAt||(e.installedAt=new Date().toISOString());let n=await W(e.applicationInstallId,!1,t)===null;return await pe(M,e.applicationInstallId,e,"string",t),t.info(n?"Created installation state":"Updated installation state",{applicationInstallId:e.applicationInstallId,organisationId:e.organisationId,organisationBrandId:e.organisationBrandId}),e},Br=async(e,t)=>{await de(M,e,t),t.info("Deleted installation state",{applicationInstallId:e})};var j=e=>"seeka_app_"+e+"_at_app",H=e=>"seeka_app_"+e+"_at_core",ge="X-Seeka-App-Token",fe="X-Seeka-CoreApi-Token",G="at_app",K="at_core";var St=y(require("jsonwebtoken"));var me=async(e,t,n,r)=>{let i=new URL(e),a=t.get("Cookie"),s=i.searchParams.get(G)||"";if(!s&&t.get(ge)&&(s=t.get(ge)?.split("Bearer ")[1]),!s&&a){let o=a.split(";").find(l=>l.trim().startsWith(j(process.env.SEEKA_APP_ID)));o&&(s=o.split("=")[1])}let c=i.searchParams.get(K)||"";if(!c&&t.get(fe)&&(c=t.get(fe)?.split("Bearer ")[1]),!c&&a){let o=a.split(";").find(l=>l.trim().startsWith(H(process.env.SEEKA_APP_ID)));o&&(c=o.split("=")[1])}return await Pt(s,c,n,r)},Pt=async(e,t,n,r)=>{let i,a,s;if(e)try{let o=St.default.verify(e,process.env.SEEKA_APP_SECRET,{ignoreNotBefore:!0});if(r.info("Decoded token",{decoded:o}),!o.appId||o.appId.replace(/-/g,"")!==process.env.SEEKA_APP_ID.replace(/-/g,"")){r.error("Invalid token - app id does not match",{decoded:o,appIdToken:o.appId,appIdEnv:process.env.SEEKA_APP_ID});return}else i=o.appId;if(o.appInstallId)a=o.appInstallId;else{r.error("Invalid token - no appInstallId",{decoded:o});return}s=o.exp}catch(o){r.error("Failed to validate token",{err:o});return}else{r.error("No access token present");return}n&&await n(r);let c=await W(a,!1,r);if(c==null){r.warn("UI call cannot be processed as the installation ID is not known by this app",{seekaAppInstallId:a});return}return{appAccessToken:e,coreApiAccessToken:t,seekaAppId:i,seekaAppInstallId:a,expiresAt:s,installation:c}};var J=y(require("fs/promises")),N=y(require("path"));var wt=require("@opentelemetry/winston-transport"),v=y(require("winston")),Ct=[new v.transports.Console({level:process.env.LOGGING_LEVEL,format:v.format.combine(v.format.errors({stack:!0}),v.format.cli(),v.format.splat()),handleExceptions:!0,handleRejections:!0})];process.env.OTEL_SDK_DISABLED!=="true"&&Ct.push(new wt.OpenTelemetryTransportV3({handleExceptions:!0,handleRejections:!0}));var Tt=v.createLogger({level:process.env.LOGGING_LEVEL,transports:Ct,exitOnError:!1}),C=(e,t,n=Tt,r={})=>n.child({...e,...t?{seekaAppInstallId:t.applicationInstallId,seekaAppInstallOrganisationBrandId:t.organisationBrandId,seekaAppInstallOrganisationId:t.organisationId,...r?.invocationId?{"faas.invocation_id":r.invocationId}:{}}:{}}),Dr=(e,t)=>{let n={seekaWebhookType:e.type,seekaWebhookIsTest:e.isTest,RequestId:e.requestId,"faas.invocation_id":t.invocationId,CausationId:e.causationId,CorrelationId:e.causationId},r=e.context;return r&&(n.seekaAppInstallId=r.applicationInstallId,n.seekaAppInstallOrganisationBrandId=r.organisationBrandId,n.seekaAppInstallOrganisationId=r.organisationId),C(n)},$r=(e,t,n)=>{let r={jobContext:t,jobName:e,"faas.invocation_id":n.invocationId,CausationId:t?.causationId,CorrelationId:t?.causationId,seekaAppInstallId:t?.applicationInstallId??t?.payload.applicationInstallId,seekaAppInstallOrganisationBrandId:t?.organisationBrandId,seekaAppInstallOrganisationId:t?.organisationId};return C(r)};async function Nt(e,t){return await J.readFile(e,{encoding:t})}var he="config.js",Fr=async(e,t,n,r,i,a)=>{let s=C(null,void 0,void 0,r);s.profile("http.seeka.webhook.app.ui");let o=new URL(e).pathname?.replace(/^\/app/,"")||"/";s.verbose("Received Seeka UI request",{requestedPath:o,url:e,method:t});let l=N.default.resolve("./dist/src/ui/build"),d=null,k=null,u,p={},V=[],g,z=async()=>o==="/health"?null:(g=await me(e,n,()=>ue(s),s),g?(d=g.seekaAppId,k=g.seekaAppInstallId,u=g.installation,s=C(null,u,s,r),s.verbose("Authenticated Seeka UI request",{requestedPath:o,url:e,method:t}),s=C(null,u,s,r),V.push({name:j(process.env.SEEKA_APP_ID),value:g.appAccessToken,httpOnly:!0,secure:!0,sameSite:"None",expires:new Date(g.expiresAt*1e3)}),V.push({name:H(process.env.SEEKA_APP_ID),value:g.coreApiAccessToken,httpOnly:!0,secure:!0,sameSite:"None",expires:new Date(g.expiresAt*1e3)}),null):{status:403,jsonBody:{error:"Invalid token"}}),A=N.default.join(l,o),w;try{if(o==="/health")return{status:200,jsonBody:{status:"ok"}};if(o==="/"+he){let m=await z();if(m)return m;let T=process.env.APP_UI_BASE_PATH?`${process.env.APP_UI_BASE_PATH}`:"",x=`${process.env.SELF_HOST_BASEURL}${T}`,Et={seekaAppId:d||"",seekaAppInstallId:k||"",organisationBrandId:u?.organisationBrandId||"",appBaseUrl:x,state:await i(u,s)};w=`window.seekaAppConfig = ${JSON.stringify(Et)}`}if(o.startsWith("/api")){let m=await z();if(m)return m;let T=await a(o,t,u,s);return T||{status:404,jsonBody:{error:"Not found"}}}if(o==="/"||o==="/index.html"){let m=await z();if(m)return m;let T=`?${G}=${encodeURIComponent(g?.appAccessToken||"")}&${K}=${encodeURIComponent(g?.coreApiAccessToken||"")}&`;A=N.default.join(l,"index.html");let x=await Nt(A,"utf-8");x=x.replace(he+"?",he+T),w=x}else w||(A=N.default.join(l,o),await J.access(A))}catch(m){A=N.default.join(l,"index.html"),console.log("File not found, serving index.html",{err:m,requestedPath:o,buildPath:l,filePath:A,content:w})}return w||(w=await Nt(A)),{status:200,headers:{"Content-Type":qr(A),"Referrer-Policy":"no-referrer",...p},cookies:V,body:w}};function qr(e){return e.endsWith(".html")?"text/html":e.endsWith(".js")?"application/javascript":e.endsWith(".css")?"text/css":e.endsWith(".png")?"image/png":e.endsWith(".jpg")||e.endsWith(".jpeg")?"image/jpeg":e.endsWith(".gif")?"image/gif":"application/octet-stream"}var Ie=y(require("fs/promises")),ye=y(require("path")),xt=y(require("winston")),Mr=async e=>Ie.default.stat(e).then(()=>!0).catch(()=>!1);async function Wr(e,t,n,r){let a=ye.default.resolve(ye.default.join(t,"seeka-browser-plugin.min.js"));return await bt(e,a,n,r)}async function bt(e,t,n,r){r.profile("http.seeka.browser.plugin");let i,a;try{r.verbose("Handling request for browser plugin content",{path:t}),await Mr(t)?(r.verbose("Browser plugin content found",{path:t}),i=await Ie.default.readFile(t,"utf8"),a=`${e}(${JSON.stringify(n)})`):r.error("Browser plugin content not found",{path:t})}catch(s){r.error("Failed to handle request for browser plugin content",{ex:xt.default.exceptions.getAllInfo(s)})}finally{r.profile("http.seeka.browser.plugin"),r.verbose("Request for browser plugin content handled")}if(!i||!a)throw new Error("Failed to handle request for browser plugin content");return{content:i,init:a}}0&&(module.exports={appLogger,backgroundJobLogger,checkAuth,childLogger,connect,createOrUpdateInstallation,deleteInstallation,disconnect,generateAppUiHttpRequestResponse,getAccessTokenAndCheck,getKey,getList,getOrCreate,getOrCreateClient,getSeekaBrowserPlugin,getSeekaBrowserPluginByName,isConnected,listInstallations,remove,set,startServices,stopServices,tryGet,tryGetInstallation,webhookLogger});
1
+ "use strict";var Ot=Object.create;var L=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var Rt=Object.getOwnPropertyNames;var Ut=Object.getPrototypeOf,Lt=Object.prototype.hasOwnProperty;var Bt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Dt=(e,t)=>{for(var n in t)L(e,n,{get:t[n],enumerable:!0})},ve=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Rt(t))!Lt.call(e,i)&&i!==n&&L(e,i,{get:()=>t[i],enumerable:!(r=_t(t,i))||r.enumerable});return e};var y=(e,t,n)=>(n=e!=null?Ot(Ut(e)):{},ve(t||!e||!e.__esModule?L(n,"default",{value:e,enumerable:!0}):n,e)),$t=e=>ve(L({},"__esModule",{value:!0}),e);var ft=Bt((Kr,gt)=>{"use strict";var Ft=Object.create,$=Object.defineProperty,qt=Object.getOwnPropertyDescriptor,Mt=Object.getOwnPropertyNames,Wt=Object.getPrototypeOf,jt=Object.prototype.hasOwnProperty,Ht=(e,t)=>{for(var n in t)$(e,n,{get:t[n],enumerable:!0})},Pe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Mt(t))!jt.call(e,i)&&i!==n&&$(e,i,{get:()=>t[i],enumerable:!(r=qt(t,i))||r.enumerable});return e},h=(e,t,n)=>(n=e!=null?Ft(Wt(e)):{},Pe(t||!e||!e.__esModule?$(n,"default",{value:e,enumerable:!0}):n,e)),Gt=e=>Pe($({},"__esModule",{value:!0}),e),we={};Ht(we,{ActivityPipelineActivityFilterSourceItemType:()=>We,ActivityPipelineActivityFilterType:()=>qe,AnalyticsLibrary:()=>He,ApiException:()=>Xe,ApiServiceProxyBase:()=>Z,AppPermissionKeys:()=>S,ClickAttributionSourcePlatform:()=>Fe,ConditionComparer:()=>Me,ConditionOperator:()=>je,ConsentMappingMatchType:()=>Ye,ContentIdentificationBehavior:()=>Ge,ConvergePipelineLoggableActivityType:()=>Be,ConvergeVendorDestinationPublishStrategy:()=>Ke,CrossDomainTrackingUtmBehavior:()=>Je,ECommerceContentType:()=>_e,ECommerceFinancialStatus:()=>Le,ECommerceFulfillmentStatus:()=>Ue,ECommercePlatform:()=>Re,IabPrivacyConsentPurposeId:()=>ze,IabPrivacyConsentPurposeIdMap:()=>or,IdentityServiceProxy:()=>Ne,IngestServiceProxy:()=>xe,PrivacyConsentType:()=>Ee,PrivacyDataControlMode:()=>Qe,RegionalConsentGrantOption:()=>Ve,ResponseResultType:()=>be,SdkLogEventLevel:()=>De,SeekaApiHelper:()=>st,SeekaAppCacheManager:()=>O,SeekaAppConfig:()=>Te,SeekaAppHelper:()=>ur,SeekaWebhookCallType:()=>$e,TrackingActivityNames:()=>D,TrackingEventSourceOriginType:()=>Oe,chunk:()=>Q,cloneDeep:()=>hr,dateToUtcDateTimeReferenceString:()=>tt,decryptText:()=>pt,emailAddress:()=>Sr,encryptText:()=>lt,generateNewSessionId:()=>B,getActivityName:()=>Vt,getActivityValue:()=>Tr,getContentIdFromProduct:()=>Nr,getContentNameFromProduct:()=>xr,getIssuer:()=>te,getNestedProperty:()=>vr,getNewAppInstallToken:()=>nt,getNewOrCachedAppInstallToken:()=>re,getRandomNumberString:()=>et,isDeepEqual:()=>Ar,isNumber:()=>yr,isValidSeekaProfileId:()=>br,last:()=>ie,lastOrDefault:()=>Ir,matchActivityPipelineFilters:()=>Cr,md5Hash:()=>rt,parseFloat:()=>ut,parseInt:()=>mr,parseMoney:()=>fr,parseStr:()=>f,phoneNumberToE164:()=>Pr,separatePersonFullName:()=>zt,setNestedProperty:()=>kr,throwOnInvalidWebhookSignature:()=>pr,urls:()=>Er,validateWebhookSignature:()=>ot,webhookSignatureHeaderName:()=>X});gt.exports=Gt(we);var Kt="3.8.1",Ce=h(require("axios")),Te=class{appId;appSecret;ingestUrl;issuerUrl;organisationId;applicationInstallId;runtime;logger;grantedPermissions;transformApiRequest;transformApiResponse;hasAnyPermissions;hasAllPermissions;hasPermission},Z=class{config;constructor(e){this.config=e}transformOptions=async e=>await this.config.transformApiRequest(e);transformResult=async(e,t,n)=>await this.config.transformApiResponse(e,t,n)},Ne=class extends Z{instance;baseUrl;jsonParseReviver=void 0;constructor(e,t,n){super(e),this.instance=n||Ce.default.create(),this.baseUrl=t??"https://api-localdev-env0-seeka.au.ngrok.io"}merge(e,t){let n=this.baseUrl+"/api/identity";n=n.replace(/[?&]$/,"");let r={data:JSON.stringify(e),method:"POST",url:n,headers:{"Content-Type":"application/json",Accept:"application/json"},cancelToken:t};return this.transformOptions(r).then(i=>this.instance.request(i)).catch(i=>{if(Ze(i)&&i.response)return i.response;throw i}).then(i=>this.transformResult(n,i,a=>this.processMerge(a)))}processMerge(e){let t=e.status,n={};if(e.headers&&typeof e.headers=="object")for(let r in e.headers)e.headers.hasOwnProperty(r)&&(n[r]=e.headers[r]);if(t===200){let r=e.data,i=null;return i=JSON.parse(r),Promise.resolve(i)}else if(t===400){let r=e.data,i=null;return i=JSON.parse(r),P("A server side error occurred.",t,r,n,i)}else if(t===401){let r=e.data,i=null;return i=JSON.parse(r),P("A server side error occurred.",t,r,n,i)}else if(t===422){let r=e.data,i=null;return i=JSON.parse(r),P("A server side error occurred.",t,r,n,i)}else if(t!==200&&t!==204){let r=e.data;return P("An unexpected server error occurred.",t,r,n)}return Promise.resolve(null)}},xe=class extends Z{instance;baseUrl;jsonParseReviver=void 0;constructor(e,t,n){super(e),this.instance=n||Ce.default.create(),this.baseUrl=t??"https://api-localdev-env0-seeka.au.ngrok.io"}batch(e,t){let n=this.baseUrl+"/api/ingest";n=n.replace(/[?&]$/,"");let r={data:JSON.stringify(e),method:"POST",url:n,headers:{"Content-Type":"application/json"},cancelToken:t};return this.transformOptions(r).then(i=>this.instance.request(i)).catch(i=>{if(Ze(i)&&i.response)return i.response;throw i}).then(i=>this.transformResult(n,i,a=>this.processBatch(a)))}processBatch(e){let t=e.status,n={};if(e.headers&&typeof e.headers=="object")for(let r in e.headers)e.headers.hasOwnProperty(r)&&(n[r]=e.headers[r]);if(t===202){let r=e.data;return Promise.resolve(null)}else if(t===400){let r=e.data,i=null;return i=JSON.parse(r),P("A server side error occurred.",t,r,n,i)}else if(t===401){let r=e.data,i=null;return i=JSON.parse(r),P("A server side error occurred.",t,r,n,i)}else if(t===422){let r=e.data,i=null;return i=JSON.parse(r),P("A server side error occurred.",t,r,n,i)}else if(t!==200&&t!==204){let r=e.data;return P("An unexpected server error occurred.",t,r,n)}return Promise.resolve(null)}},be=(e=>(e.Undefined="undefined",e.Success="success",e.Failed="failed",e))(be||{}),Ee=(e=>(e.Unknown="unknown",e.Informed="informed",e.Implied="implied",e.Explicit="explicit",e.Active="active",e.Passive="passive",e))(Ee||{}),Oe=(e=>(e.Browser="browser",e.Server="server",e.Mobile="mobile",e.Desktop="desktop",e.PhysicalStore="physicalStore",e.Email="email",e.Phone="phone",e.Chat="chat",e.Automatic="automatic",e))(Oe||{}),D=(e=>(e.Undefined="undefined",e.PageViewOrganic="pageViewOrganic",e.PageViewUtmAttributed="pageViewUtmAttributed",e.AddPaymentMethod="addPaymentMethod",e.AddToWishlist="addToWishlist",e.ContactMessage="contactMessage",e.Custom="custom",e.SyncCart="syncCart",e.Order="order",e.InitiateCheckout="initiateCheckout",e.AddToCart="addToCart",e.RemoveFromCart="removeFromCart",e.OneTimeItemPurchase="oneTimeItemPurchase",e.SubscriptionItemPurchase="subscriptionItemPurchase",e.ViewProduct="viewProduct",e.ViewPage="viewPage",e.ApplyPromotionalCode="applyPromotionalCode",e.KeywordSearch="keywordSearch",e.UserLoginSignup="userLoginSignup",e.UserLogin="userLogin",e.NewsletterSignup="newsletterSignup",e.Lead="lead",e.ChangeProductAttribute="changeProductAttribute",e.FilterItemsByAttribute="filterItemsByAttribute",e.Schedule="schedule",e.ViewContentItem="viewContentItem",e.StartTrial="startTrial",e))(D||{}),_e=(e=>(e.Undefined="undefined",e.SingleProduct="singleProduct",e.SingleVariant="singleVariant",e.Collection="collection",e))(_e||{}),Re=(e=>(e.None="none",e.BigCommerce="bigCommerce",e.Shopify="shopify",e.OrderGroove="orderGroove",e.Magento="magento",e.Generic="generic",e.WooCommerce="wooCommerce",e.Demandware="demandware",e))(Re||{}),Ue=(e=>(e.Undefined="undefined",e.Fulfilled="fulfilled",e.NoneFulfilled="noneFulfilled",e.PartiallyFulfilled="partiallyFulfilled",e.RestockedOrCancelled="restockedOrCancelled",e.Pending="pending",e))(Ue||{}),Le=(e=>(e.Undefined="undefined",e.Pending="pending",e.Authorized="authorized",e.PartiallyPaid="partiallyPaid",e.Paid="paid",e.PartiallyRefunded="partiallyRefunded",e.Refunded="refunded",e.Voided="voided",e))(Le||{}),Be=(e=>(e.Generic="generic",e.ActivityIngress="activityIngress",e.ActivityEgress="activityEgress",e.UserProfile="userProfile",e.SdkLog="sdkLog",e.Detections="detections",e.ActivityEgressFilter="activityEgressFilter",e.Diagnosis="diagnosis",e.PipelineIntegrationOutput="pipelineIntegrationOutput",e))(Be||{}),De=(e=>(e.Information="information",e.Warning="warning",e.Error="error",e.Verbose="verbose",e))(De||{}),$e=(e=>(e.None="none",e.Probe="probe",e.AppInstalled="appInstalled",e.IdentityChanged="identityChanged",e.ActivityAccepted="activityAccepted",e.AppInstallSettingsUpdated="appInstallSettingsUpdated",e.AppUninstalled="appUninstalled",e.BrowserSdkPlugin="browserSdkPlugin",e))($e||{}),Fe=(e=>(e.Unknown="unknown",e.Google="google",e.Meta="meta",e.Snapchat="snapchat",e.Pinterest="pinterest",e.TikTok="tikTok",e))(Fe||{}),qe=(e=>(e.Undefined="undefined",e.PurchaseMade="purchaseMade",e.ActivityTracked="activityTracked",e))(qe||{}),Me=(e=>(e.Undefined="undefined",e.And="and",e.Or="or",e))(Me||{}),We=(e=>(e.Undefined="undefined",e.Domain="domain",e.Pipeline="pipeline",e.Wildcard="wildcard",e.Url="url",e.PagePath="pagePath",e))(We||{}),je=(e=>(e.Undefined="undefined",e.Equals="equals",e.NotEquals="notEquals",e.Contains="contains",e.NotContains="notContains",e.StartsWith="startsWith",e.EndsWith="endsWith",e.IsNull="isNull",e.NotNull="notNull",e.IsTrue="isTrue",e.IsFalse="isFalse",e.GreaterThanOrEquals="greaterThanOrEquals",e.LessThanOrEquals="lessThanOrEquals",e.GreaterThan="greaterThan",e.LessThan="lessThan",e.Before="before",e.After="after",e.Between="between",e.In="in",e.NotIn="notIn",e.Regex="regEx",e.Any="any",e))(je||{}),He=(e=>(e.Undefined="undefined",e.Seeka="seeka",e.DynamicYield="dynamicYield",e.Segment="segment",e.FacebookPixel="facebookPixel",e.GoogleAnalytics="googleAnalytics",e.Braze="braze",e.SnapchatPixel="snapchatPixel",e.Pinterest="pinterest",e.TikTokPixel="tikTokPixel",e.GoogleAds="googleAds",e))(He||{}),Ge=(e=>(e.Default="default",e.Sku="sku",e.ProductId="productId",e.VariantId="variantId",e.ProductIdAndVariantIdUnderscore="productIdAndVariantIdUnderscore",e.VariantIdOrProductId="variantIdOrProductId",e))(Ge||{}),Ke=(e=>(e.DeliverAllTraitsAndDeliverAllEvents="deliverAllTraitsAndDeliverAllEvents",e.DeliverAllTraitsAndDeliverEventsOnlyIfMaxWeightedTraitsPresent="deliverAllTraitsAndDeliverEventsOnlyIfMaxWeightedTraitsPresent",e.DeliverMaxWeightedTraitsOnlyAndDeliverAllEvents="deliverMaxWeightedTraitsOnlyAndDeliverAllEvents",e.DeliverMaxWeightedTraitsOnlyAndDeliverEventsOnlyIfMaxWeightedTraitsPresent="deliverMaxWeightedTraitsOnlyAndDeliverEventsOnlyIfMaxWeightedTraitsPresent",e))(Ke||{}),Je=(e=>(e.None="none",e.SessionPassthrough="sessionPassthrough",e.UrlPassthrough="urlPassthrough",e))(Je||{}),Ve=(e=>(e.Unset="unset",e.Granted="granted",e.Denied="denied",e))(Ve||{}),ze=(e=>(e.Undefined="undefined",e.MeasureAdvertisingPerformance="measureAdvertisingPerformance",e))(ze||{}),Ye=(e=>(e.Undefined="undefined",e.AllOf="allOf",e.AnyOf="anyOf",e))(Ye||{}),Qe=(e=>(e.Disabled="disabled",e.Explicit="explicit",e.Implicit="implicit",e))(Qe||{}),Xe=class extends Error{message;status;response;headers;result;constructor(e,t,n,r,i){super(),this.message=e,this.status=t,this.response=n,this.headers=r,this.result=i}isApiException=!0;static isApiException(e){return e.isApiException===!0}};function P(e,t,n,r,i){throw i??new Xe(e,t,n,r,null)}function Ze(e){return e&&e.isAxiosError===!0}var E=require("openid-client"),ee=h(require("winston")),Y=h(require("memory-cache")),ke="seeka:sdk",O=class{constructor(e,t){this.appId=e,this.appInstallationId=t}appId;appInstallationId;set=async(e,t,n)=>{let r=this.getKey(e);Y.default.put(r,JSON.stringify(t),n)};getOrSet=async(e,t,n)=>{let r=this.getKey(e),i=Y.default.get(r);if(i){let s=JSON.parse(i);return n&&await n(s),s}let a=await t();return a?(Y.default.put(r,JSON.stringify(a.value),a.expiryAbsoluteMilliseconds),a.value):null};getKey=e=>this.appInstallationId?`${ke}:${this.appId}:${this.appInstallationId}:${e}`:`${ke}:${this.appId}:${e}`},Jt=h(require("crypto")),B=()=>{let e=tt(new Date),t=et();return`${e}.${t}`},Vt=e=>{let t=Object.keys(D),n=e.toLowerCase(),r=t.find(i=>i.toLowerCase()===n);return r?D[r]:"custom"},et=()=>Math.floor(Math.random()*(9999999999-1e9)+1e9).toString(),tt=e=>{let t=(e.getUTCMonth()+1).toString();t.length<2&&(t="0"+t);let n=e.getUTCDate().toString();n.length<2&&(n="0"+n);let r=e.getUTCHours().toString();r.length<2&&(r="0"+r);let i=e.getUTCMinutes().toString();i.length<2&&(i="0"+i);let a=e.getUTCSeconds().toString();return a.length<2&&(a="0"+a),`${e.getUTCFullYear()}${t}${n}.${r}${i}${a}`},rt=e=>Jt.createHash("md5").update(e).digest("hex"),zt=e=>{if(!e)return{firstName:null,lastName:null};let t=e.trim().split(" ");return t.length===1?{firstName:e,lastName:null}:t.length===2?{firstName:t[0],lastName:t[1]}:{firstName:t[0],lastName:t.slice(1).join(" ")}},Q=(e,t)=>e.reduce((n,r,i)=>{let a=Math.floor(i/t);return n[a]||(n[a]=[]),n[a].push(r),n},[]),te=async e=>{let t={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.debug("Seeka auth: getting issuer",{...t}):console.debug("Seeka auth: getting issuer",{...t});let n=new O(e.appId,e.applicationInstallId),r=rt(e.issuerUrl+"_"+e.appId),i=await n.getOrSet(r,async()=>{try{let a=await Yt(e);return!a||!a.meta||!a.raw?null:(e.logger?e.logger.verbose("Seeka auth: got issuer from remote",{...t}):console.debug("Seeka auth: got issuer from remote",{...t}),{value:a.meta,expiryAbsoluteMilliseconds:1e3*60*60})}catch(a){return e.logger?e.logger.error("Seeka auth: failed getting issuer",{...t,ex:ee.default.exceptions.getAllInfo(a)}):console.error("Seeka auth: failed getting issuer",{...t}),null}},async()=>{e.logger?e.logger.verbose("Seeka auth: got issuer from cache",{...t}):console.debug("Seeka auth: got issuer from cache",{...t})});return i===null?null:new E.Configuration(i.serverMetadata,i.clientId,e.appSecret)},Yt=async e=>{let t={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.verbose("Seeka auth: discovering issuer from remote",{...t}):console.info("Seeka auth: discovering issuer from remote",{...t});try{let n=e.appId.replace(/-/g,""),r=await(0,E.discovery)(new URL(e.issuerUrl),n,void 0,(0,E.None)(),{timeout:1e4});return e.logger?e.logger.verbose("Seeka auth: discovered issuer from remote",{...t,client_id:r.clientMetadata().client_id}):console.info("Seeka auth: discovered issuer from remote",{...t,client_id:r.clientMetadata().client_id}),{meta:{serverMetadata:r.serverMetadata(),clientMetadata:r.clientMetadata(),timeout:r.timeout,clientId:n},raw:r}}catch(n){return e.logger?e.logger.error("Seeka auth: failed discovering issuer from remote",{...t,ex:ee.default.exceptions.getAllInfo(n)}):console.error("Seeka auth: failed discovering issuer from remote",{...t,err:n}),null}},Qt=async e=>{let t={applicationId:e.appId,issuer:{url:e.issuerUrl}},n=await te(e);if(!n)return null;try{let r=await(0,E.clientCredentialsGrant)(n,{resource:n.clientMetadata().client_id}),i={...t,token:{expires_at:r.expires_at,token_type:r.token_type,scope:r.scope}};return e.logger?e.logger.verbose("Seeka auth: got client access token from server",{...i}):console.info("Seeka auth: got app client token from server",{...i}),{token_type:r.token_type,access_token:r.access_token,expires_in:r.expires_in,id_token:r.id_token,refresh_token:r.refresh_token,scope:r.scope,authorization_details:r.authorization_details}}catch(r){let i={...t,error:r};return e.logger?e.logger.error("Seeka auth: failed to get client access token from server",{...i}):console.error("Seeka auth: failed to get client access token from server",{...i,err:ee.default.exceptions.getAllInfo(r)}),null}},nt=async(e,t)=>{let n={applicationId:t.appId,issuer:{url:t.issuerUrl}},r=await te(t);if(!r||!r)return null;try{let i=await(0,E.genericGrantRequest)(r,"app_install_token",{applicationInstallId:t.applicationInstallId,access_token:e,scope:"Seeka.API.Ingest"}),a={...n,token:{expires_at:i.expires_at,token_type:i.token_type,scope:i.scope}};return t.logger?t.logger.verbose("Seeka auth: got app access token from server",{...a}):console.info("Seeka auth: got app access token from server",{...a}),{token_type:i.token_type,access_token:i.access_token,expires_in:i.expires_in,id_token:i.id_token,refresh_token:i.refresh_token,scope:i.scope,authorization_details:i.authorization_details}}catch(i){let a={...n,error:i};return t.logger?t.logger.error("Seeka auth: failed to get app access token from server",{...a}):console.debug("Seeka auth: failed to get app access token from server",{...a}),null}},re=async e=>{let t=new O(e.appId,e.applicationInstallId),n={applicationId:e.appId,issuer:{url:e.issuerUrl}};return await t.getOrSet("auth:token:appinstall",async()=>{let r=await Qt(e);if(!r||!r.access_token)return null;let i=await nt(r.access_token,e);return i?{value:i,expiryAbsoluteMilliseconds:((i.expires_in>r.expires_in?r.expires_in:i.expires_in)||900*1e3)-60*1e3}:null},async()=>{e.logger?e.logger.verbose("Seeka auth: got app token from cache",{...n}):console.debug("Seeka auth: got app token from cache",{...n})})},it="https://router.seeka.services",Xt="https://router.seeka.services/tel/otel",at="https://account.seeka.app",Zt=(e,t,n,r,i)=>{let a=new Te;return a.appId=e.applicationId,a.appSecret=t,a.ingestUrl=process.env.SEEKA_INGEST_URL||it,a.issuerUrl=process.env.SEEKA_ISSUER_URL||at,a.organisationId=e.organisationId,a.applicationInstallId=e.applicationInstallId,a.runtime={type:"sdk/js/apps-server",ver:Kt.split("-")[0],client:n},a.logger=i,a.grantedPermissions=r,a.transformApiRequest=s=>er(a,s),a.transformApiResponse=async(s,c,o)=>tr(a,s,c,o),a.hasAnyPermissions=s=>!a.grantedPermissions||a.grantedPermissions.length===0?!1:!s||s.length===0?!0:s.some(c=>a.grantedPermissions.includes(c)),a.hasAllPermissions=s=>!a.grantedPermissions||a.grantedPermissions.length===0?!1:!s||s.length===0?!0:s.every(c=>a.grantedPermissions.includes(c)),a.hasPermission=s=>!a.grantedPermissions||a.grantedPermissions.length===0?!1:s?a.grantedPermissions.includes(s):!0,a},er=async(e,t)=>{let n=await re(e);if(!n||!n.access_token)throw new Error("Could not get access token for API request");return t.headers={...t.headers,"X-OrgId":e.organisationId,Authorization:"Bearer "+n?.access_token},t},tr=async(e,t,n,r)=>(n.data=JSON.stringify(n.data),r(n)),S={identity:{receiveFull:"Identity.Receive.Pii",send:"Identity.Send"},activity:{receiveAnon:"Activity.Receive.Anon",receiveFull:"Activity.Receive.Pii",send:"Activity.Send"}},rr=h(require("axios")),nr=h(require("http")),ir=h(require("https")),ar=new nr.default.Agent({keepAlive:!0,scheduling:"fifo"}),sr=new ir.default.Agent({keepAlive:!0,scheduling:"fifo"}),Ae=e=>{let t=rr.default.create({httpAgent:ar,httpsAgent:sr});return t.interceptors.request.use(function(n){let r={url:n.url,method:n.method};return process.env.LOGGING_LEVEL==="silly"&&(r={...r,body:n.data,params:n.params}),e.logger?e.logger.debug(`Seeka API: making call to ${r.url}`,{...r}):console.debug(`Seeka API: making call to ${r.url}`,{...r}),n},function(n){let r={error:n};return e.logger?e.logger.http("Seeka API: failed to send request",{...r}):console.debug("Seeka API: failed to send request",{...r}),Promise.reject(n)}),t.interceptors.response.use(function(n){let r={url:n.request?.url||n.config.url,method:n.request?.method||n.config.method,response:{status:n.status}};return e.logger?e.logger.http(`Seeka API: call to ${r.url} succeeded`,{...r}):console.debug(`Seeka API: call to ${r.url} succeeded`,{...r}),n},function(n){let{code:r,status:i,message:a}=n,{headers:s,url:c,method:o}=n?.config,l={code:r,status:i,message:a,headers:s,url:c,method:o,content:n?.response?.data};return e.logger?e.logger.error(`Seeka API: call to ${l.url} failed`,{...l}):console.error(`Seeka API: call to ${l.url} failed`,{...l}),Promise.reject(n)}),t},Se={getIdentityService:e=>new Ne(e,e.ingestUrl,Ae(e)),getIngestService:e=>new xe(e,e.ingestUrl,Ae(e))},st=class{constructor(e){this.config=e,this.ingestionService=Se.getIngestService(e),this.identityService=Se.getIdentityService(e)}config;maxBatchSize=50;refreshOrPrimeTokenCache=async()=>{await re(this.config)};ingestionService;identityService;checkPermission=(e,t)=>{if(!this.config.hasPermission(e))throw new Error("Cannot perform operation "+t+" on installationId "+this.config.applicationInstallId+" without permission "+e+". Currently granted permissions: "+(this.config.grantedPermissions?this.config.grantedPermissions.join(", "):"none"));return!0};mergeIdentity=async(e,t)=>{this.checkPermission(S.identity.send,"mergeIdentity");let n=B();return(await this.identityService.merge({id:e,src:{method:"",origin:t.origin,time:void 0,loc:t.loc,sess:n,diag:process.env.SEEKA_DEBUG_ENABLED==="true"?n:void 0,runtime:this.config.runtime}})).result?.personId};mergeIdentityBatch=async(e,t)=>{this.checkPermission(S.identity.send,"mergeIdentityBatch");let n=B();if(e.length===0){this.config.logger?.debug("No identities in batch");return}let r={method:"",origin:t.origin,time:void 0,loc:t.loc,sess:n,diag:process.env.SEEKA_DEBUG_ENABLED==="true"?n:void 0,runtime:this.config.runtime},i=Q(e,this.maxBatchSize);if(i.length>1&&this.config.logger&&this.config.logger.debug(`Identity batch size ${e} is greater than ${this.maxBatchSize}, splitting into ${i.length} batches`),await this.trackActivityBatchRaw({data:i[0].map(a=>({id:{id:a||{},src:{...r}}}))}),i.length>1){let a=i.map((s,c)=>c===0?Promise.resolve():(this.config.logger?.verbose(`Processing identity batch ${c+1} of ${i.length}`),this.trackActivityBatchRaw({data:s.map(o=>({id:{id:o||{},src:{...r}}}))})));await Promise.all(a)}};trackActivityBatch=async(e,t)=>{this.checkPermission(S.activity.send,"trackActivityBatch");let n=B();if(e.length===0){this.config.logger?.debug("No activities in batch");return}let r={method:"",origin:t.origin,time:void 0,loc:t.loc,sess:n,diag:process.env.SEEKA_DEBUG_ENABLED==="true"?n:void 0,runtime:this.config.runtime},i=Q(e,this.maxBatchSize);if(i.length>1&&this.config.logger&&this.config.logger.debug(`Activity batch size ${e.length} is greater than ${this.maxBatchSize}, splitting into ${i.length} batches`),await this.trackActivityBatchRaw({data:i[0].map(a=>({ev:{id:a.profile||{},src:{...r},payload:a.activity}}))}),i.length>1){let a=i.map((s,c)=>c===0?Promise.resolve():(this.config.logger?.verbose(`Processing activity batch ${c+1} of ${i.length}`),this.trackActivityBatchRaw({data:s.map(o=>({ev:{id:o.profile||{},src:{...r},payload:o.activity}}))})));await Promise.all(a)}};trackActivityBatchRaw=async e=>{await this.ingestionService.batch(e)};trackActivityForProfileId=async(e,t,n)=>{this.checkPermission(S.activity.send,"trackActivityForProfileId"),await this.trackActivityForProfileIdBatch([e],t,n)};trackActivityForProfileIdBatch=async(e,t,n)=>{this.checkPermission(S.activity.send,"trackActivityForProfileIdBatch"),await this.trackActivityBatch(e.map(r=>({activity:r,profile:t?{seekaPId:t}:void 0})),n)};trackActivityForProfile=async(e,t,n)=>{this.checkPermission(S.activity.send,"trackActivityForProfile"),await this.trackActivityForProfileBatch([e],t,n)};trackActivityForProfileBatch=async(e,t,n)=>{this.checkPermission(S.activity.send,"trackActivityForProfileBatch"),await this.trackActivityBatch(e.map(r=>({activity:r,profile:t})),n)}},or={measureAdvertisingPerformance:7},cr=h(require("crypto")),X="x-seeka-signature-sha256",ot=(e,t,n)=>{if(!t)return!1;let r=null;if(t.get&&typeof t.get=="function")r=t.get(X);else{let a=t[X];a&&(Array.isArray(a)&&a.length>0?r=a[0]:(typeof a=="string"||a instanceof String)&&(r=a))}if(!r)return!1;let i=lr(e,n)===r;return i||console.warn("Invalid webhook signature"),i},lr=(e,t)=>cr.createHmac("sha256",e).update(t).digest("hex"),pr=(e,t,n)=>{if(!ot(e,t,n))throw new Error("Invalid webhook signature")},b=h(require("crypto")),ct="aes-192-cbc",lt=(e,t)=>{if(!e)return"";if(!t)throw new Error("Secret is required to encrypt data");let n=b.default.scryptSync(t,"salt",24),r=b.default.randomBytes(16),i=b.default.createCipheriv(ct,n,r);return[i.update(e,"utf8","hex")+i.final("hex"),Buffer.from(r).toString("hex")].join("|")},pt=(e,t)=>{if(!e)return"";if(!t)throw new Error("Secret is required to decrypt data");let[n,r]=e.split("|");if(!r)throw new Error("IV not found");let i=b.default.scryptSync(t,"salt",24),a=b.default.createDecipheriv(ct,i,Buffer.from(r,"hex"));return a.update(n,"hex","utf8")+a.final("utf8")},dr=class{constructor(e){this.appSecret=e}appSecret;encryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to encrypt data");return lt(e,this.appSecret)};decryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to decrypt data");return pt(e,this.appSecret)}},ur=class dt{constructor(t,n){this.context=t,this.api=new st(t.config),this.appCache=new O(t.config.appId),this.appInstallCache=new O(t.config.appId,t.config.applicationInstallId),this.crypto=new dr(t.config.appSecret),this.logger=n}context;appCache;appInstallCache;api;logger;crypto;static create=(t,n,r,i,a)=>new dt({config:Zt({...n},t,{type:r.name,ver:r.version.split("-")[0]},i,a)},a)},gr=h(require("winston")),ne=require("lodash-es"),f=e=>e==null||e===""||String(e).trim()===""?"":String(e);function ut(e){if(e==null||e==="")return 0;let t=e.toString().replace(/[^0-9.]/g,"");return Number.isNaN(Number(t))?0:Number(t)}function fr(e){if(e==null||e===0||e==="")return+"0.00";let t=ut(e);return Number(t.toFixed(3))}function mr(e){return e==null||e===""||Number.isNaN(Number(e.toString()))?0:Math.floor(Number(e))}function hr(e){return JSON.parse(JSON.stringify(e))}function yr(e){return/^-?\d+$/.test(e)}function Ir(e){if(!(e==null||e.length===0))return ie(e)}function ie(e){return ie(e)}function vr(e,t){return(0,ne.get)(e,t)}function kr(e,t,n){return(0,ne.set)(e,t,n)}function Ar(e,t){return(0,ne.isEqual)(e,t)}function Sr(e){return e?e.trim().toLowerCase():""}function Pr(e){return e==null?"":(e=e.trim().replace(/-/gi,"").replace(/\(/gi,"").replace(/\)/gi,"").replace(/ /g,"").replace(/\+/g,""),e)}var wr=["order","subscriptionItemPurchase","oneTimeItemPurchase"],Cr=(e,t,n)=>{if(!e.activity)return[];let r=e.activity,i=r.activityName==="custom"?r.activityNameCustom:r.activityName;if(!i)return[];let a=i.toLowerCase(),s=[];return t.forEach(c=>{if(!c)return;switch(c.type){case"activityTracked":{if(!c.activityNames||!c.activityNames.find(p=>p.toLowerCase()===a))return;n.verbose("Matched activity tracked filter",{filter:c,activityName:i});break}case"purchaseMade":{if(!r.activityName||!wr.includes(r.activityName))return;n.verbose("Matched purchase made activity filter",{filter:c,activityName:i});break}default:{n.warn("Unknown activity filter type",{filter:c});return}}let o=c.sourceFilter;if(!o)return;let l=e.source,d;try{d=l?.loc?new URL(l.loc).hostname.toLowerCase():null}catch(p){n.error("Failed to parse activity source URL",{ex:gr.default.exceptions.getAllInfo(p),activitySource:l}),d=null}let k=l?.pipeline?.convergePipelineIntegrationInstanceId?.toLowerCase(),u=o.filters?o.filters.map(p=>{switch(p.type){case"wildcard":return n.verbose("Matched wildcard source filter",{sourceFilter:p}),!0;case"domain":return!d||!p.key?!1:d===p.key.toLowerCase()?(n.verbose("Matched domain source filter",{sourceFilter:p,activityHostname:d}),!0):!1;case"pipeline":return!k||!p.key?!1:k===p.key.toLowerCase()?(n.verbose("Matched pipeline source filter",{sourceFilter:p,sourceConvergePipelineIntegrationInstanceId:k}),!0):!1}}):[];switch(o.comparer){case"and":{u.every(p=>p===!0)&&s.push(c);break}case"or":{u.some(p=>p===!0)&&s.push(c);break}default:{n.warn("Unknown source filter comparer",{sourceFilters:o});break}}}),s},Tr=(e,t=!1)=>{let n=e.commerce,r=n?.totalPrice||n?.products?.map(a=>(a.unitPrice||0)*(a.quantity||1)).reduce((a,s)=>a+s,0)||void 0,i=n?.currencyCode||null;if((!r||r<=0)&&(r=e?.lead?.predictedLtv||e?.lead?.predictedValue,r&&e?.lead?.currencyCode&&(i=e?.lead?.currencyCode||null)),(!r||r<=0)&&(r=e?.contentItem?.value,r&&e?.contentItem?.currencyCode&&(i=e?.contentItem?.currencyCode||null)),(!r||r<=0)&&(e?.contentItem?.items&&e?.contentItem?.items.length>0&&(r=e?.contentItem?.items.map(a=>a&&a.unitPrice?a.unitPrice*(a.quantity||1):0).reduce((a,s)=>a+s,0)),r&&(i=e?.contentItem?.currencyCode||e?.commerce?.currencyCode||null,!i))){let a=e?.contentItem?.items?.filter(s=>s.currencyCode)||[];a.length>0&&(i=a[0].currencyCode||null)}if((!r||r<=0)&&e?.commerce?.products&&e?.commerce?.products.length>0&&(r=e?.commerce?.products.map(a=>a&&a.unitPrice?a.unitPrice*(a.quantity||1):0).reduce((a,s)=>a+s,0),r&&(i=e?.commerce?.currencyCode||null,!i))){let a=e?.commerce?.products?.filter(s=>s.currencyCode)||[];a.length>0&&(i=a[0].currencyCode||null)}return(!r||r<=0)&&!i?null:{value:r===0&&t?null:r||null,currencyCode:i}};function Nr(e,t,n){if(!e)return;let r=t.processing?.contentIdentificationBehavior,i=null;(n=="googleAnalytics"||n=="googleAds")&&(t.analytics?.libraries?.googleAnalytics?.merchant?.productItemIdBehavior!=null&&(r=t.analytics?.libraries?.googleAnalytics?.merchant?.productItemIdBehavior),i=f(t.analytics?.libraries?.googleAnalytics?.merchant?.productItemIdPrefix));let a;switch(r){case"sku":a=e?.sku;break;case"productId":a=e?.productIdentifier;break;case"variantId":a=e?.variantIdentifier;break;case"productIdAndVariantIdUnderscore":f(e.variantIdentifier)&&f(e.productIdentifier)?a=`${e.productIdentifier}_${e.variantIdentifier}`:f(e.variantIdentifier)?a=e.variantIdentifier:a=e.productIdentifier;break;case"variantIdOrProductId":f(e.variantIdentifier)?a=e.variantIdentifier:a=e.productIdentifier;break;default:a=f(e?.sku)||f(e?.variantIdentifier)||f(e?.productIdentifier);break}return i?`${i}${a}`:a}function xr(e,t){return f(e?.variantName)||f(e?.productName)}function br(e){if(!e||e.trim().length===0)return!1;let t=e.split(".").filter(n=>n.trim().length>0);return!(t.length!==4||t[0].toLowerCase()!=="sk".toLowerCase()||t[1].toLowerCase()!=="1".toLowerCase()||isNaN(parseInt(t[2],10))||isNaN(parseInt(t[3],10)))}var Er={defaultIssuerUrl:at,defaultTelemetryUrl:Xt,defaultIngestUrl:it}});var jr={};Dt(jr,{appLogger:()=>Tt,backgroundJobLogger:()=>$r,checkAuth:()=>Pt,childLogger:()=>C,connect:()=>ht,createOrUpdateInstallation:()=>Lr,deleteInstallation:()=>Br,disconnect:()=>yt,generateAppUiHttpRequestResponse:()=>Fr,getAccessTokenAndCheck:()=>me,getKey:()=>U,getList:()=>le,getOrCreate:()=>_r,getOrCreateClient:()=>I,getSeekaBrowserPlugin:()=>Wr,getSeekaBrowserPluginByName:()=>bt,isConnected:()=>se,listInstallations:()=>Ur,remove:()=>de,set:()=>pe,startServices:()=>ue,stopServices:()=>Rr,tryGet:()=>ce,tryGetInstallation:()=>W,webhookLogger:()=>Dr});module.exports=$t(jr);var mt=require("redis"),F=y(require("winston")),q=y(ft()),Or=()=>{let e=process.env.REDIS_CONNECTION_TLS==="true"?"rediss://":"redis://";return process.env.REDIS_CONNECTION_USER&&process.env.REDIS_CONNECTION_PASSWORD?`${e}${process.env.REDIS_CONNECTION_USER}:${process.env.REDIS_CONNECTION_PASSWORD}@${process.env.REDIS_CONNECTION_HOST}:${process.env.REDIS_CONNECTION_PORT}`:`${e}${process.env.REDIS_CONNECTION_HOST}:${process.env.REDIS_CONNECTION_PORT}`},ae="__SEEKA_REDIS_CLIENT__",I=e=>{if(global[ae])return global[ae];let t=(0,mt.createClient)({url:Or(),disableClientInfo:!0}).on("error",n=>e.error("Redis Client ",{ex:F.exceptions.getAllInfo(n)}));return global[ae]=t,t},ht=async e=>{await I(e).connect()},se=async e=>I(e).isOpen,yt=async e=>{I(e).destroy()},It=e=>`seeka:app:${process.env.SEEKA_APP_ID}:${e}`,U=(e,t)=>`${It(e)}:${t}`,_=e=>e==="install",vt=()=>{let e=process.env.DATA_ENCRYPTION_KEY;if(!e)throw new Error("DATA_ENCRYPTION_KEY is required to encrypt/decrypt installation state");return e},kt=e=>{if(!e)return!1;let t=e.split("|");if(t.length!==2)return!1;let[n,r]=t;return!n||!r?!1:/^[0-9a-f]+$/i.test(n)&&/^[0-9a-f]{32}$/i.test(r)},oe=e=>{if(!kt(e))return{plainText:e,wasEncrypted:!1};let t=vt();return{plainText:(0,q.decryptText)(e,t),wasEncrypted:!0}},R=e=>{if(kt(e))return{encryptedText:e,wasEncrypted:!0};let t=vt();return{encryptedText:(0,q.encryptText)(e,t),wasEncrypted:!1}};async function _r(e,t,n,r="string",i){let a=U(e,t),s=I(i),c=await At(s,a);if(c){if(r==="string"&&_(e)){let{plainText:o,wasEncrypted:l}=oe(c);if(!l){let{encryptedText:d}=R(c);await s.set(a,d)}return JSON.parse(o)}return JSON.parse(c)}if(r==="json")await s.json.set(a,"$",n);else{let o=JSON.stringify(n);if(_(e)){let{encryptedText:l}=R(o);await s.set(a,l)}else await s.set(a,o)}return n}async function ce(e,t,n="string",r){let i=U(e,t),a=I(r);if(n==="json"){let s=await a.json.get(i);if(s)return s}else{let s=await At(a,i);if(s){if(_(e)){let{plainText:c,wasEncrypted:o}=oe(s);if(!o){let{encryptedText:l}=R(s);await a.set(i,l)}return JSON.parse(c)}return JSON.parse(s)}}return null}async function le(e,t){let n=It(e),r=I(t),i=await r.keys(`${n}:*`),a=await r.mGet(i);if(a){let s=[];for(let c=0;c<a.length;c++){let o=a[c],l=i[c];if(!o)continue;let d=o;if(_(e)){let{plainText:k,wasEncrypted:u}=oe(d);if(!u){let{encryptedText:p}=R(d);await r.set(l,p)}s.push(JSON.parse(k))}else s.push(JSON.parse(d))}return s}return[]}async function pe(e,t,n,r="string",i){let a=U(e,t),s=I(i);if(r==="json")await s.json.set(a,"$",n);else{let c=JSON.stringify(n);if(_(e)){let{encryptedText:o}=R(c);await s.set(a,o)}else await s.set(a,c)}}async function de(e,t,n){let r=U(e,t);await I(n).del(r)}async function At(e,t){let n=await e.get(t);return typeof n=="string"?n:n?n.toString():""}var ue=async e=>{e.debug(`Trying to connect to Redis - ${process.env.REDIS_CONNECTION_HOST}`);try{await se(e)?e.verbose(`Redis already connected - ${process.env.REDIS_CONNECTION_HOST}`):(e.profile("service.redis.connect"),await ht(e),e.profile("service.redis.connect"),e.debug(`Redis connected - ${process.env.REDIS_CONNECTION_HOST}`))}catch(t){throw e.error(`Failed to connect to Redis - ${process.env.REDIS_CONNECTION_HOST}`,{ex:F.exceptions.getAllInfo(t)}),t}},Rr=async e=>{e.debug(`Trying to disconnect from Redis - ${process.env.REDIS_CONNECTION_HOST}`);try{await se(e)===!1?e.verbose(`Redis already disconnected - ${process.env.REDIS_CONNECTION_HOST}`):(e.profile("service.redis.disconnect"),await yt(e),e.profile("service.redis.disconnect"),e.verbose(`Redis disconnected - ${process.env.REDIS_CONNECTION_HOST}`))}catch(t){throw e.error(`Failed to disconnect from Redis - ${process.env.REDIS_CONNECTION_HOST}`,{ex:F.exceptions.getAllInfo(t)}),t}};var M="install",W=async(e,t,n)=>{let r=await ce(M,e,"string",n);if(r==null&&t)throw n.error(`Seeka installation ${e} not found`),new Error(`Seeka installation ${e} not found`);return r},Ur=async e=>await le(M,e),Lr=async(e,t)=>{e.installationState||(e.installationState={}),e.installedAt||(e.installedAt=new Date().toISOString());let n=await W(e.applicationInstallId,!1,t)===null;return await pe(M,e.applicationInstallId,e,"string",t),t.info(n?"Created installation state":"Updated installation state",{applicationInstallId:e.applicationInstallId,organisationId:e.organisationId,organisationBrandId:e.organisationBrandId}),e},Br=async(e,t)=>{await de(M,e,t),t.info("Deleted installation state",{applicationInstallId:e})};var j=e=>"seeka_app_"+e+"_at_app",H=e=>"seeka_app_"+e+"_at_core",ge="X-Seeka-App-Token",fe="X-Seeka-CoreApi-Token",G="at_app",K="at_core";var St=y(require("jsonwebtoken"));var me=async(e,t,n,r)=>{let i=new URL(e),a=t.get("Cookie"),s=i.searchParams.get(G)||"";if(!s&&t.get(ge)&&(s=t.get(ge)?.split("Bearer ")[1]),!s&&a){let o=a.split(";").find(l=>l.trim().startsWith(j(process.env.SEEKA_APP_ID)));o&&(s=o.split("=")[1])}let c=i.searchParams.get(K)||"";if(!c&&t.get(fe)&&(c=t.get(fe)?.split("Bearer ")[1]),!c&&a){let o=a.split(";").find(l=>l.trim().startsWith(H(process.env.SEEKA_APP_ID)));o&&(c=o.split("=")[1])}return await Pt(s,c,n,r)},Pt=async(e,t,n,r)=>{let i,a,s;if(e)try{let o=St.default.verify(e,process.env.SEEKA_APP_SECRET,{ignoreNotBefore:!0});if(r.info("Decoded token",{decoded:o}),!o.appId||o.appId.replace(/-/g,"")!==process.env.SEEKA_APP_ID.replace(/-/g,"")){r.error("Invalid token - app id does not match",{decoded:o,appIdToken:o.appId,appIdEnv:process.env.SEEKA_APP_ID});return}else i=o.appId;if(o.appInstallId)a=o.appInstallId;else{r.error("Invalid token - no appInstallId",{decoded:o});return}s=o.exp}catch(o){r.error("Failed to validate token",{err:o});return}else{r.error("No access token present");return}n&&await n(r);let c=await W(a,!1,r);if(c==null){r.warn("UI call cannot be processed as the installation ID is not known by this app",{seekaAppInstallId:a});return}return{appAccessToken:e,coreApiAccessToken:t,seekaAppId:i,seekaAppInstallId:a,expiresAt:s,installation:c}};var J=y(require("fs/promises")),N=y(require("path"));var wt=require("@opentelemetry/winston-transport"),v=y(require("winston")),Ct=[new v.transports.Console({level:process.env.LOGGING_LEVEL,format:v.format.combine(v.format.errors({stack:!0}),v.format.cli(),v.format.splat()),handleExceptions:!0,handleRejections:!0})];process.env.OTEL_SDK_DISABLED!=="true"&&Ct.push(new wt.OpenTelemetryTransportV3({handleExceptions:!0,handleRejections:!0}));var Tt=v.createLogger({level:process.env.LOGGING_LEVEL,transports:Ct,exitOnError:!1}),C=(e,t,n=Tt,r={})=>n.child({...e,...t?{seekaAppInstallId:t.applicationInstallId,seekaAppInstallOrganisationBrandId:t.organisationBrandId,seekaAppInstallOrganisationId:t.organisationId,...r?.invocationId?{"faas.invocation_id":r.invocationId}:{}}:{}}),Dr=(e,t)=>{let n={seekaWebhookType:e.type,seekaWebhookIsTest:e.isTest,RequestId:e.requestId,"faas.invocation_id":t.invocationId,CausationId:e.causationId,CorrelationId:e.causationId},r=e.context;return r&&(n.seekaAppInstallId=r.applicationInstallId,n.seekaAppInstallOrganisationBrandId=r.organisationBrandId,n.seekaAppInstallOrganisationId=r.organisationId),C(n)},$r=(e,t,n)=>{let r={jobContext:t,jobName:e,"faas.invocation_id":n.invocationId,CausationId:t?.causationId,CorrelationId:t?.causationId,seekaAppInstallId:t?.applicationInstallId??t?.payload.applicationInstallId,seekaAppInstallOrganisationBrandId:t?.organisationBrandId,seekaAppInstallOrganisationId:t?.organisationId};return C(r)};async function Nt(e,t){return await J.readFile(e,{encoding:t})}var he="config.js",Fr=async(e,t,n,r,i,a)=>{let s=C(null,void 0,void 0,r);s.profile("http.seeka.webhook.app.ui");let o=new URL(e).pathname?.replace(/^\/app/,"")||"/";s.verbose("Received Seeka UI request",{requestedPath:o,url:e,method:t});let l=N.default.resolve("./dist/src/ui/build"),d=null,k=null,u,p={},V=[],g,z=async()=>o==="/health"?null:(g=await me(e,n,()=>ue(s),s),g?(d=g.seekaAppId,k=g.seekaAppInstallId,u=g.installation,s=C(null,u,s,r),s.verbose("Authenticated Seeka UI request",{requestedPath:o,url:e,method:t}),s=C(null,u,s,r),V.push({name:j(process.env.SEEKA_APP_ID),value:g.appAccessToken,httpOnly:!0,secure:!0,sameSite:"None",expires:new Date(g.expiresAt*1e3)}),V.push({name:H(process.env.SEEKA_APP_ID),value:g.coreApiAccessToken,httpOnly:!0,secure:!0,sameSite:"None",expires:new Date(g.expiresAt*1e3)}),null):{status:403,jsonBody:{error:"Invalid token"}}),A=N.default.join(l,o),w;try{if(o==="/health")return{status:200,jsonBody:{status:"ok"}};if(o==="/"+he){let m=await z();if(m)return m;let T=process.env.APP_UI_BASE_PATH?`${process.env.APP_UI_BASE_PATH}`:"",x=`${process.env.SELF_HOST_BASEURL}${T}`,Et={seekaAppId:d||"",seekaAppInstallId:k||"",organisationBrandId:u?.organisationBrandId||"",appBaseUrl:x,state:await i(u,s)};w=`window.seekaAppConfig = ${JSON.stringify(Et)}`}if(o.startsWith("/api")){let m=await z();if(m)return m;let T=await a(o,t,u,s);return T||{status:404,jsonBody:{error:"Not found"}}}if(o==="/"||o==="/index.html"){let m=await z();if(m)return m;let T=`?${G}=${encodeURIComponent(g?.appAccessToken||"")}&${K}=${encodeURIComponent(g?.coreApiAccessToken||"")}&`;A=N.default.join(l,"index.html");let x=await Nt(A,"utf-8");x=x.replace(he+"?",he+T),w=x}else w||(A=N.default.join(l,o),await J.access(A))}catch(m){A=N.default.join(l,"index.html"),console.log("File not found, serving index.html",{err:m,requestedPath:o,buildPath:l,filePath:A,content:w})}return w||(w=await Nt(A)),{status:200,headers:{"Content-Type":qr(A),"Referrer-Policy":"no-referrer",...p},cookies:V,body:w}};function qr(e){return e.endsWith(".html")?"text/html":e.endsWith(".js")?"application/javascript":e.endsWith(".css")?"text/css":e.endsWith(".png")?"image/png":e.endsWith(".jpg")||e.endsWith(".jpeg")?"image/jpeg":e.endsWith(".gif")?"image/gif":"application/octet-stream"}var Ie=y(require("fs/promises")),ye=y(require("path")),xt=y(require("winston")),Mr=async e=>Ie.default.stat(e).then(()=>!0).catch(()=>!1);async function Wr(e,t,n,r){let a=ye.default.resolve(ye.default.join(t,"seeka-browser-plugin.min.js"));return await bt(e,a,n,r)}async function bt(e,t,n,r){r.profile("http.seeka.browser.plugin");let i,a;try{r.verbose("Handling request for browser plugin content",{path:t}),await Mr(t)?(r.verbose("Browser plugin content found",{path:t}),i=await Ie.default.readFile(t,"utf8"),a=`${e}(${JSON.stringify(n)})`):r.error("Browser plugin content not found",{path:t})}catch(s){r.error("Failed to handle request for browser plugin content",{ex:xt.default.exceptions.getAllInfo(s)})}finally{r.profile("http.seeka.browser.plugin"),r.verbose("Request for browser plugin content handled")}if(!i||!a)throw new Error("Failed to handle request for browser plugin content");return{content:i,init:a}}0&&(module.exports={appLogger,backgroundJobLogger,checkAuth,childLogger,connect,createOrUpdateInstallation,deleteInstallation,disconnect,generateAppUiHttpRequestResponse,getAccessTokenAndCheck,getKey,getList,getOrCreate,getOrCreateClient,getSeekaBrowserPlugin,getSeekaBrowserPluginByName,isConnected,listInstallations,remove,set,startServices,stopServices,tryGet,tryGetInstallation,webhookLogger});
@@ -1 +1 @@
1
- var At=Object.create;var le=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var u=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Tt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Nt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Pt(t))!Ct.call(e,i)&&i!==n&&le(e,i,{get:()=>t[i],enumerable:!(r=St(t,i))||r.enumerable});return e};var xt=(e,t,n)=>(n=e!=null?At(wt(e)):{},Nt(t||!e||!e.__esModule?le(n,"default",{value:e,enumerable:!0}):n,e));var it=Tt((Lr,nt)=>{"use strict";var bt=Object.create,B=Object.defineProperty,Et=Object.getOwnPropertyDescriptor,Ot=Object.getOwnPropertyNames,_t=Object.getPrototypeOf,Rt=Object.prototype.hasOwnProperty,Ut=(e,t)=>{for(var n in t)B(e,n,{get:t[n],enumerable:!0})},ge=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ot(t))!Rt.call(e,i)&&i!==n&&B(e,i,{get:()=>t[i],enumerable:!(r=Et(t,i))||r.enumerable});return e},y=(e,t,n)=>(n=e!=null?bt(_t(e)):{},ge(t||!e||!e.__esModule?B(n,"default",{value:e,enumerable:!0}):n,e)),Lt=e=>ge(B({},"__esModule",{value:!0}),e),fe={};Ut(fe,{ActivityPipelineActivityFilterSourceItemType:()=>_e,ActivityPipelineActivityFilterType:()=>Ee,AnalyticsLibrary:()=>Ue,ApiException:()=>We,ApiServiceProxyBase:()=>Q,AppPermissionKeys:()=>A,ClickAttributionSourcePlatform:()=>be,ConditionComparer:()=>Oe,ConditionOperator:()=>Re,ConsentMappingMatchType:()=>qe,ContentIdentificationBehavior:()=>Le,ConvergePipelineLoggableActivityType:()=>Te,ConvergeVendorDestinationPublishStrategy:()=>Be,CrossDomainTrackingUtmBehavior:()=>De,ECommerceContentType:()=>Se,ECommerceFinancialStatus:()=>Ce,ECommerceFulfillmentStatus:()=>we,ECommercePlatform:()=>Pe,IabPrivacyConsentPurposeId:()=>Fe,IabPrivacyConsentPurposeIdMap:()=>Qt,IdentityServiceProxy:()=>ye,IngestServiceProxy:()=>Ie,PrivacyConsentType:()=>ke,PrivacyDataControlMode:()=>Me,RegionalConsentGrantOption:()=>$e,ResponseResultType:()=>ve,SdkLogEventLevel:()=>Ne,SeekaApiHelper:()=>Ye,SeekaAppCacheManager:()=>E,SeekaAppConfig:()=>he,SeekaAppHelper:()=>rr,SeekaWebhookCallType:()=>xe,TrackingActivityNames:()=>L,TrackingEventSourceOriginType:()=>Ae,chunk:()=>z,cloneDeep:()=>sr,dateToUtcDateTimeReferenceString:()=>Ge,decryptText:()=>et,emailAddress:()=>ur,encryptText:()=>Ze,generateNewSessionId:()=>U,getActivityName:()=>$t,getActivityValue:()=>hr,getContentIdFromProduct:()=>yr,getContentNameFromProduct:()=>Ir,getIssuer:()=>Z,getNestedProperty:()=>lr,getNewAppInstallToken:()=>Je,getNewOrCachedAppInstallToken:()=>ee,getRandomNumberString:()=>He,isDeepEqual:()=>dr,isNumber:()=>or,isValidSeekaProfileId:()=>vr,last:()=>re,lastOrDefault:()=>cr,matchActivityPipelineFilters:()=>mr,md5Hash:()=>Ke,parseFloat:()=>rt,parseInt:()=>ar,parseMoney:()=>ir,parseStr:()=>m,phoneNumberToE164:()=>gr,separatePersonFullName:()=>Ft,setNestedProperty:()=>pr,throwOnInvalidWebhookSignature:()=>er,urls:()=>kr,validateWebhookSignature:()=>Qe,webhookSignatureHeaderName:()=>Y});nt.exports=Lt(fe);var Bt="3.7.0",me=y(u("axios")),he=class{appId;appSecret;ingestUrl;issuerUrl;organisationId;applicationInstallId;runtime;logger;grantedPermissions;transformApiRequest;transformApiResponse;hasAnyPermissions;hasAllPermissions;hasPermission},Q=class{config;constructor(e){this.config=e}transformOptions=async e=>await this.config.transformApiRequest(e);transformResult=async(e,t,n)=>await this.config.transformApiResponse(e,t,n)},ye=class extends Q{instance;baseUrl;jsonParseReviver=void 0;constructor(e,t,n){super(e),this.instance=n||me.default.create(),this.baseUrl=t??"https://api-localdev-env0-seeka.au.ngrok.io"}merge(e,t){let n=this.baseUrl+"/api/identity";n=n.replace(/[?&]$/,"");let r={data:JSON.stringify(e),method:"POST",url:n,headers:{"Content-Type":"application/json",Accept:"application/json"},cancelToken:t};return this.transformOptions(r).then(i=>this.instance.request(i)).catch(i=>{if(je(i)&&i.response)return i.response;throw i}).then(i=>this.transformResult(n,i,a=>this.processMerge(a)))}processMerge(e){let t=e.status,n={};if(e.headers&&typeof e.headers=="object")for(let r in e.headers)e.headers.hasOwnProperty(r)&&(n[r]=e.headers[r]);if(t===200){let r=e.data,i=null;return i=JSON.parse(r),Promise.resolve(i)}else if(t===400){let r=e.data,i=null;return i=JSON.parse(r),S("A server side error occurred.",t,r,n,i)}else if(t===401){let r=e.data,i=null;return i=JSON.parse(r),S("A server side error occurred.",t,r,n,i)}else if(t===422){let r=e.data,i=null;return i=JSON.parse(r),S("A server side error occurred.",t,r,n,i)}else if(t!==200&&t!==204){let r=e.data;return S("An unexpected server error occurred.",t,r,n)}return Promise.resolve(null)}},Ie=class extends Q{instance;baseUrl;jsonParseReviver=void 0;constructor(e,t,n){super(e),this.instance=n||me.default.create(),this.baseUrl=t??"https://api-localdev-env0-seeka.au.ngrok.io"}batch(e,t){let n=this.baseUrl+"/api/ingest";n=n.replace(/[?&]$/,"");let r={data:JSON.stringify(e),method:"POST",url:n,headers:{"Content-Type":"application/json"},cancelToken:t};return this.transformOptions(r).then(i=>this.instance.request(i)).catch(i=>{if(je(i)&&i.response)return i.response;throw i}).then(i=>this.transformResult(n,i,a=>this.processBatch(a)))}processBatch(e){let t=e.status,n={};if(e.headers&&typeof e.headers=="object")for(let r in e.headers)e.headers.hasOwnProperty(r)&&(n[r]=e.headers[r]);if(t===202){let r=e.data;return Promise.resolve(null)}else if(t===400){let r=e.data,i=null;return i=JSON.parse(r),S("A server side error occurred.",t,r,n,i)}else if(t===401){let r=e.data,i=null;return i=JSON.parse(r),S("A server side error occurred.",t,r,n,i)}else if(t===422){let r=e.data,i=null;return i=JSON.parse(r),S("A server side error occurred.",t,r,n,i)}else if(t!==200&&t!==204){let r=e.data;return S("An unexpected server error occurred.",t,r,n)}return Promise.resolve(null)}},ve=(e=>(e.Undefined="undefined",e.Success="success",e.Failed="failed",e))(ve||{}),ke=(e=>(e.Unknown="unknown",e.Informed="informed",e.Implied="implied",e.Explicit="explicit",e.Active="active",e.Passive="passive",e))(ke||{}),Ae=(e=>(e.Browser="browser",e.Server="server",e.Mobile="mobile",e.Desktop="desktop",e.PhysicalStore="physicalStore",e.Email="email",e.Phone="phone",e.Chat="chat",e.Automatic="automatic",e))(Ae||{}),L=(e=>(e.Undefined="undefined",e.PageViewOrganic="pageViewOrganic",e.PageViewUtmAttributed="pageViewUtmAttributed",e.AddPaymentMethod="addPaymentMethod",e.AddToWishlist="addToWishlist",e.ContactMessage="contactMessage",e.Custom="custom",e.SyncCart="syncCart",e.Order="order",e.InitiateCheckout="initiateCheckout",e.AddToCart="addToCart",e.RemoveFromCart="removeFromCart",e.OneTimeItemPurchase="oneTimeItemPurchase",e.SubscriptionItemPurchase="subscriptionItemPurchase",e.ViewProduct="viewProduct",e.ViewPage="viewPage",e.ApplyPromotionalCode="applyPromotionalCode",e.KeywordSearch="keywordSearch",e.UserLoginSignup="userLoginSignup",e.UserLogin="userLogin",e.NewsletterSignup="newsletterSignup",e.Lead="lead",e.ChangeProductAttribute="changeProductAttribute",e.FilterItemsByAttribute="filterItemsByAttribute",e.Schedule="schedule",e.ViewContentItem="viewContentItem",e.StartTrial="startTrial",e))(L||{}),Se=(e=>(e.Undefined="undefined",e.SingleProduct="singleProduct",e.SingleVariant="singleVariant",e.Collection="collection",e))(Se||{}),Pe=(e=>(e.None="none",e.BigCommerce="bigCommerce",e.Shopify="shopify",e.OrderGroove="orderGroove",e.Magento="magento",e.Generic="generic",e.WooCommerce="wooCommerce",e.Demandware="demandware",e))(Pe||{}),we=(e=>(e.Undefined="undefined",e.Fulfilled="fulfilled",e.NoneFulfilled="noneFulfilled",e.PartiallyFulfilled="partiallyFulfilled",e.RestockedOrCancelled="restockedOrCancelled",e.Pending="pending",e))(we||{}),Ce=(e=>(e.Undefined="undefined",e.Pending="pending",e.Authorized="authorized",e.PartiallyPaid="partiallyPaid",e.Paid="paid",e.PartiallyRefunded="partiallyRefunded",e.Refunded="refunded",e.Voided="voided",e))(Ce||{}),Te=(e=>(e.Generic="generic",e.ActivityIngress="activityIngress",e.ActivityEgress="activityEgress",e.UserProfile="userProfile",e.SdkLog="sdkLog",e.Detections="detections",e.ActivityEgressFilter="activityEgressFilter",e.Diagnosis="diagnosis",e.PipelineIntegrationOutput="pipelineIntegrationOutput",e))(Te||{}),Ne=(e=>(e.Information="information",e.Warning="warning",e.Error="error",e.Verbose="verbose",e))(Ne||{}),xe=(e=>(e.None="none",e.Probe="probe",e.AppInstalled="appInstalled",e.IdentityChanged="identityChanged",e.ActivityAccepted="activityAccepted",e.AppInstallSettingsUpdated="appInstallSettingsUpdated",e.AppUninstalled="appUninstalled",e.BrowserSdkPlugin="browserSdkPlugin",e))(xe||{}),be=(e=>(e.Unknown="unknown",e.Google="google",e.Meta="meta",e.Snapchat="snapchat",e.Pinterest="pinterest",e.TikTok="tikTok",e))(be||{}),Ee=(e=>(e.Undefined="undefined",e.PurchaseMade="purchaseMade",e.ActivityTracked="activityTracked",e))(Ee||{}),Oe=(e=>(e.Undefined="undefined",e.And="and",e.Or="or",e))(Oe||{}),_e=(e=>(e.Undefined="undefined",e.Domain="domain",e.Pipeline="pipeline",e.Wildcard="wildcard",e.Url="url",e.PagePath="pagePath",e))(_e||{}),Re=(e=>(e.Undefined="undefined",e.Equals="equals",e.NotEquals="notEquals",e.Contains="contains",e.NotContains="notContains",e.StartsWith="startsWith",e.EndsWith="endsWith",e.IsNull="isNull",e.NotNull="notNull",e.IsTrue="isTrue",e.IsFalse="isFalse",e.GreaterThanOrEquals="greaterThanOrEquals",e.LessThanOrEquals="lessThanOrEquals",e.GreaterThan="greaterThan",e.LessThan="lessThan",e.Before="before",e.After="after",e.Between="between",e.In="in",e.NotIn="notIn",e.Regex="regEx",e.Any="any",e))(Re||{}),Ue=(e=>(e.Undefined="undefined",e.Seeka="seeka",e.DynamicYield="dynamicYield",e.Segment="segment",e.FacebookPixel="facebookPixel",e.GoogleAnalytics="googleAnalytics",e.Braze="braze",e.SnapchatPixel="snapchatPixel",e.Pinterest="pinterest",e.TikTokPixel="tikTokPixel",e.GoogleAds="googleAds",e))(Ue||{}),Le=(e=>(e.Default="default",e.Sku="sku",e.ProductId="productId",e.VariantId="variantId",e.ProductIdAndVariantIdUnderscore="productIdAndVariantIdUnderscore",e.VariantIdOrProductId="variantIdOrProductId",e))(Le||{}),Be=(e=>(e.DeliverAllTraitsAndDeliverAllEvents="deliverAllTraitsAndDeliverAllEvents",e.DeliverAllTraitsAndDeliverEventsOnlyIfMaxWeightedTraitsPresent="deliverAllTraitsAndDeliverEventsOnlyIfMaxWeightedTraitsPresent",e.DeliverMaxWeightedTraitsOnlyAndDeliverAllEvents="deliverMaxWeightedTraitsOnlyAndDeliverAllEvents",e.DeliverMaxWeightedTraitsOnlyAndDeliverEventsOnlyIfMaxWeightedTraitsPresent="deliverMaxWeightedTraitsOnlyAndDeliverEventsOnlyIfMaxWeightedTraitsPresent",e))(Be||{}),De=(e=>(e.None="none",e.SessionPassthrough="sessionPassthrough",e.UrlPassthrough="urlPassthrough",e))(De||{}),$e=(e=>(e.Unset="unset",e.Granted="granted",e.Denied="denied",e))($e||{}),Fe=(e=>(e.Undefined="undefined",e.MeasureAdvertisingPerformance="measureAdvertisingPerformance",e))(Fe||{}),qe=(e=>(e.Undefined="undefined",e.AllOf="allOf",e.AnyOf="anyOf",e))(qe||{}),Me=(e=>(e.Disabled="disabled",e.Explicit="explicit",e.Implicit="implicit",e))(Me||{}),We=class extends Error{message;status;response;headers;result;constructor(e,t,n,r,i){super(),this.message=e,this.status=t,this.response=n,this.headers=r,this.result=i}isApiException=!0;static isApiException(e){return e.isApiException===!0}};function S(e,t,n,r,i){throw i??new We(e,t,n,r,null)}function je(e){return e&&e.isAxiosError===!0}var b=u("openid-client"),X=y(u("winston")),V=y(u("memory-cache")),pe="seeka:sdk",E=class{constructor(e,t){this.appId=e,this.appInstallationId=t}appId;appInstallationId;set=async(e,t,n)=>{let r=this.getKey(e);V.default.put(r,JSON.stringify(t),n)};getOrSet=async(e,t,n)=>{let r=this.getKey(e),i=V.default.get(r);if(i){let s=JSON.parse(i);return n&&await n(s),s}let a=await t();return a?(V.default.put(r,JSON.stringify(a.value),a.expiryAbsoluteMilliseconds),a.value):null};getKey=e=>this.appInstallationId?`${pe}:${this.appId}:${this.appInstallationId}:${e}`:`${pe}:${this.appId}:${e}`},Dt=y(u("crypto")),U=()=>{let e=Ge(new Date),t=He();return`${e}.${t}`},$t=e=>{let t=Object.keys(L),n=e.toLowerCase(),r=t.find(i=>i.toLowerCase()===n);return r?L[r]:"custom"},He=()=>Math.floor(Math.random()*(9999999999-1e9)+1e9).toString(),Ge=e=>{let t=(e.getUTCMonth()+1).toString();t.length<2&&(t="0"+t);let n=e.getUTCDate().toString();n.length<2&&(n="0"+n);let r=e.getUTCHours().toString();r.length<2&&(r="0"+r);let i=e.getUTCMinutes().toString();i.length<2&&(i="0"+i);let a=e.getUTCSeconds().toString();return a.length<2&&(a="0"+a),`${e.getUTCFullYear()}${t}${n}.${r}${i}${a}`},Ke=e=>Dt.createHash("md5").update(e).digest("hex"),Ft=e=>{if(!e)return{firstName:null,lastName:null};let t=e.trim().split(" ");return t.length===1?{firstName:e,lastName:null}:t.length===2?{firstName:t[0],lastName:t[1]}:{firstName:t[0],lastName:t.slice(1).join(" ")}},z=(e,t)=>e.reduce((n,r,i)=>{let a=Math.floor(i/t);return n[a]||(n[a]=[]),n[a].push(r),n},[]),Z=async e=>{let t={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.debug("Seeka auth: getting issuer",{...t}):console.debug("Seeka auth: getting issuer",{...t});let n=new E(e.appId,e.applicationInstallId),r=Ke(e.issuerUrl+"_"+e.appId),i=await n.getOrSet(r,async()=>{try{let a=await qt(e);return!a||!a.meta||!a.raw?null:(e.logger?e.logger.verbose("Seeka auth: got issuer from remote",{...t}):console.debug("Seeka auth: got issuer from remote",{...t}),{value:a.meta,expiryAbsoluteMilliseconds:1e3*60*60})}catch(a){return e.logger?e.logger.error("Seeka auth: failed getting issuer",{...t,ex:X.default.exceptions.getAllInfo(a)}):console.error("Seeka auth: failed getting issuer",{...t}),null}},async()=>{e.logger?e.logger.verbose("Seeka auth: got issuer from cache",{...t}):console.debug("Seeka auth: got issuer from cache",{...t})});return i===null?null:new b.Configuration(i.serverMetadata,i.clientId,e.appSecret)},qt=async e=>{let t={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.verbose("Seeka auth: discovering issuer from remote",{...t}):console.info("Seeka auth: discovering issuer from remote",{...t});try{let n=e.appId.replace(/-/g,""),r=await(0,b.discovery)(new URL(e.issuerUrl),n,void 0,(0,b.None)(),{timeout:1e4});return e.logger?e.logger.verbose("Seeka auth: discovered issuer from remote",{...t,client_id:r.clientMetadata().client_id}):console.info("Seeka auth: discovered issuer from remote",{...t,client_id:r.clientMetadata().client_id}),{meta:{serverMetadata:r.serverMetadata(),clientMetadata:r.clientMetadata(),timeout:r.timeout,clientId:n},raw:r}}catch(n){return e.logger?e.logger.error("Seeka auth: failed discovering issuer from remote",{...t,ex:X.default.exceptions.getAllInfo(n)}):console.error("Seeka auth: failed discovering issuer from remote",{...t,err:n}),null}},Mt=async e=>{let t={applicationId:e.appId,issuer:{url:e.issuerUrl}},n=await Z(e);if(!n)return null;try{let r=await(0,b.clientCredentialsGrant)(n,{resource:n.clientMetadata().client_id}),i={...t,token:{expires_at:r.expires_at,token_type:r.token_type,scope:r.scope}};return e.logger?e.logger.verbose("Seeka auth: got client access token from server",{...i}):console.info("Seeka auth: got app client token from server",{...i}),{token_type:r.token_type,access_token:r.access_token,expires_in:r.expires_in,id_token:r.id_token,refresh_token:r.refresh_token,scope:r.scope,authorization_details:r.authorization_details}}catch(r){let i={...t,error:r};return e.logger?e.logger.error("Seeka auth: failed to get client access token from server",{...i}):console.error("Seeka auth: failed to get client access token from server",{...i,err:X.default.exceptions.getAllInfo(r)}),null}},Je=async(e,t)=>{let n={applicationId:t.appId,issuer:{url:t.issuerUrl}},r=await Z(t);if(!r||!r)return null;try{let i=await(0,b.genericGrantRequest)(r,"app_install_token",{applicationInstallId:t.applicationInstallId,access_token:e,scope:"Seeka.API.Ingest"}),a={...n,token:{expires_at:i.expires_at,token_type:i.token_type,scope:i.scope}};return t.logger?t.logger.verbose("Seeka auth: got app access token from server",{...a}):console.info("Seeka auth: got app access token from server",{...a}),{token_type:i.token_type,access_token:i.access_token,expires_in:i.expires_in,id_token:i.id_token,refresh_token:i.refresh_token,scope:i.scope,authorization_details:i.authorization_details}}catch(i){let a={...n,error:i};return t.logger?t.logger.error("Seeka auth: failed to get app access token from server",{...a}):console.debug("Seeka auth: failed to get app access token from server",{...a}),null}},ee=async e=>{let t=new E(e.appId,e.applicationInstallId),n={applicationId:e.appId,issuer:{url:e.issuerUrl}};return await t.getOrSet("auth:token:appinstall",async()=>{let r=await Mt(e);if(!r||!r.access_token)return null;let i=await Je(r.access_token,e);return i?{value:i,expiryAbsoluteMilliseconds:((i.expires_in>r.expires_in?r.expires_in:i.expires_in)||900*1e3)-60*1e3}:null},async()=>{e.logger?e.logger.verbose("Seeka auth: got app token from cache",{...n}):console.debug("Seeka auth: got app token from cache",{...n})})},Ve="https://router.seeka.services",Wt="https://router.seeka.services/tel/otel",ze="https://account.seeka.app",jt=(e,t,n,r,i)=>{let a=new he;return a.appId=e.applicationId,a.appSecret=t,a.ingestUrl=process.env.SEEKA_INGEST_URL||Ve,a.issuerUrl=process.env.SEEKA_ISSUER_URL||ze,a.organisationId=e.organisationId,a.applicationInstallId=e.applicationInstallId,a.runtime={type:"sdk/js/apps-server",ver:Bt.split("-")[0],client:n},a.logger=i,a.grantedPermissions=r,a.transformApiRequest=s=>Ht(a,s),a.transformApiResponse=async(s,c,o)=>Gt(a,s,c,o),a.hasAnyPermissions=s=>!a.grantedPermissions||a.grantedPermissions.length===0?!1:!s||s.length===0?!0:s.some(c=>a.grantedPermissions.includes(c)),a.hasAllPermissions=s=>!a.grantedPermissions||a.grantedPermissions.length===0?!1:!s||s.length===0?!0:s.every(c=>a.grantedPermissions.includes(c)),a.hasPermission=s=>!a.grantedPermissions||a.grantedPermissions.length===0?!1:s?a.grantedPermissions.includes(s):!0,a},Ht=async(e,t)=>{let n=await ee(e);if(!n||!n.access_token)throw new Error("Could not get access token for API request");return t.headers={...t.headers,"X-OrgId":e.organisationId,Authorization:"Bearer "+n?.access_token},t},Gt=async(e,t,n,r)=>(n.data=JSON.stringify(n.data),r(n)),A={identity:{receiveFull:"Identity.Receive.Pii",send:"Identity.Send"},activity:{receiveAnon:"Activity.Receive.Anon",receiveFull:"Activity.Receive.Pii",send:"Activity.Send"}},Kt=y(u("axios")),Jt=y(u("http")),Vt=y(u("https")),zt=new Jt.default.Agent({keepAlive:!0,scheduling:"fifo"}),Yt=new Vt.default.Agent({keepAlive:!0,scheduling:"fifo"}),de=e=>{let t=Kt.default.create({httpAgent:zt,httpsAgent:Yt});return t.interceptors.request.use(function(n){let r={url:n.url,method:n.method};return process.env.LOGGING_LEVEL==="silly"&&(r={...r,body:n.data,params:n.params}),e.logger?e.logger.debug(`Seeka API: making call to ${r.url}`,{...r}):console.debug(`Seeka API: making call to ${r.url}`,{...r}),n},function(n){let r={error:n};return e.logger?e.logger.http("Seeka API: failed to send request",{...r}):console.debug("Seeka API: failed to send request",{...r}),Promise.reject(n)}),t.interceptors.response.use(function(n){let r={url:n.request?.url||n.config.url,method:n.request?.method||n.config.method,response:{status:n.status}};return e.logger?e.logger.http(`Seeka API: call to ${r.url} succeeded`,{...r}):console.debug(`Seeka API: call to ${r.url} succeeded`,{...r}),n},function(n){let{code:r,status:i,message:a}=n,{headers:s,url:c,method:o}=n?.config,l={code:r,status:i,message:a,headers:s,url:c,method:o,content:n?.response?.data};return e.logger?e.logger.error(`Seeka API: call to ${l.url} failed`,{...l}):console.error(`Seeka API: call to ${l.url} failed`,{...l}),Promise.reject(n)}),t},ue={getIdentityService:e=>new ye(e,e.ingestUrl,de(e)),getIngestService:e=>new Ie(e,e.ingestUrl,de(e))},Ye=class{constructor(e){this.config=e,this.ingestionService=ue.getIngestService(e),this.identityService=ue.getIdentityService(e)}config;maxBatchSize=50;refreshOrPrimeTokenCache=async()=>{await ee(this.config)};ingestionService;identityService;checkPermission=(e,t)=>{if(!this.config.hasPermission(e))throw new Error("Cannot perform operation "+t+" on installationId "+this.config.applicationInstallId+" without permission "+e+". Currently granted permissions: "+(this.config.grantedPermissions?this.config.grantedPermissions.join(", "):"none"));return!0};mergeIdentity=async(e,t)=>{this.checkPermission(A.identity.send,"mergeIdentity");let n=U();return(await this.identityService.merge({id:e,src:{method:"",origin:t.origin,time:void 0,loc:t.loc,sess:n,diag:process.env.SEEKA_DEBUG_ENABLED==="true"?n:void 0,runtime:this.config.runtime}})).result?.personId};mergeIdentityBatch=async(e,t)=>{this.checkPermission(A.identity.send,"mergeIdentityBatch");let n=U();if(e.length===0){this.config.logger?.debug("No identities in batch");return}let r={method:"",origin:t.origin,time:void 0,loc:t.loc,sess:n,diag:process.env.SEEKA_DEBUG_ENABLED==="true"?n:void 0,runtime:this.config.runtime},i=z(e,this.maxBatchSize);if(i.length>1&&this.config.logger&&this.config.logger.debug(`Identity batch size ${e} is greater than ${this.maxBatchSize}, splitting into ${i.length} batches`),await this.trackActivityBatchRaw({data:i[0].map(a=>({id:{id:a||{},src:{...r}}}))}),i.length>1){let a=i.map((s,c)=>c===0?Promise.resolve():(this.config.logger?.verbose(`Processing identity batch ${c+1} of ${i.length}`),this.trackActivityBatchRaw({data:s.map(o=>({id:{id:o||{},src:{...r}}}))})));await Promise.all(a)}};trackActivityBatch=async(e,t)=>{this.checkPermission(A.activity.send,"trackActivityBatch");let n=U();if(e.length===0){this.config.logger?.debug("No activities in batch");return}let r={method:"",origin:t.origin,time:void 0,loc:t.loc,sess:n,diag:process.env.SEEKA_DEBUG_ENABLED==="true"?n:void 0,runtime:this.config.runtime},i=z(e,this.maxBatchSize);if(i.length>1&&this.config.logger&&this.config.logger.debug(`Activity batch size ${e.length} is greater than ${this.maxBatchSize}, splitting into ${i.length} batches`),await this.trackActivityBatchRaw({data:i[0].map(a=>({ev:{id:a.profile||{},src:{...r},payload:a.activity}}))}),i.length>1){let a=i.map((s,c)=>c===0?Promise.resolve():(this.config.logger?.verbose(`Processing activity batch ${c+1} of ${i.length}`),this.trackActivityBatchRaw({data:s.map(o=>({ev:{id:o.profile||{},src:{...r},payload:o.activity}}))})));await Promise.all(a)}};trackActivityBatchRaw=async e=>{await this.ingestionService.batch(e)};trackActivityForProfileId=async(e,t,n)=>{this.checkPermission(A.activity.send,"trackActivityForProfileId"),await this.trackActivityForProfileIdBatch([e],t,n)};trackActivityForProfileIdBatch=async(e,t,n)=>{this.checkPermission(A.activity.send,"trackActivityForProfileIdBatch"),await this.trackActivityBatch(e.map(r=>({activity:r,profile:t?{seekaPId:t}:void 0})),n)};trackActivityForProfile=async(e,t,n)=>{this.checkPermission(A.activity.send,"trackActivityForProfile"),await this.trackActivityForProfileBatch([e],t,n)};trackActivityForProfileBatch=async(e,t,n)=>{this.checkPermission(A.activity.send,"trackActivityForProfileBatch"),await this.trackActivityBatch(e.map(r=>({activity:r,profile:t})),n)}},Qt={measureAdvertisingPerformance:7},Xt=y(u("crypto")),Y="x-seeka-signature-sha256",Qe=(e,t,n)=>{if(!t)return!1;let r=null;if(t.get&&typeof t.get=="function")r=t.get(Y);else{let a=t[Y];a&&(Array.isArray(a)&&a.length>0?r=a[0]:(typeof a=="string"||a instanceof String)&&(r=a))}if(!r)return!1;let i=Zt(e,n)===r;return i||console.warn("Invalid webhook signature"),i},Zt=(e,t)=>Xt.createHmac("sha256",e).update(t).digest("hex"),er=(e,t,n)=>{if(!Qe(e,t,n))throw new Error("Invalid webhook signature")},x=y(u("crypto")),Xe="aes-192-cbc",Ze=(e,t)=>{if(!e)return"";if(!t)throw new Error("Secret is required to encrypt data");let n=x.default.scryptSync(t,"salt",24),r=x.default.randomBytes(16),i=x.default.createCipheriv(Xe,n,r);return[i.update(e,"utf8","hex")+i.final("hex"),Buffer.from(r).toString("hex")].join("|")},et=(e,t)=>{if(!e)return"";if(!t)throw new Error("Secret is required to decrypt data");let[n,r]=e.split("|");if(!r)throw new Error("IV not found");let i=x.default.scryptSync(t,"salt",24),a=x.default.createDecipheriv(Xe,i,Buffer.from(r,"hex"));return a.update(n,"hex","utf8")+a.final("utf8")},tr=class{constructor(e){this.appSecret=e}appSecret;encryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to encrypt data");return Ze(e,this.appSecret)};decryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to decrypt data");return et(e,this.appSecret)}},rr=class tt{constructor(t,n){this.context=t,this.api=new Ye(t.config),this.appCache=new E(t.config.appId),this.appInstallCache=new E(t.config.appId,t.config.applicationInstallId),this.crypto=new tr(t.config.appSecret),this.logger=n}context;appCache;appInstallCache;api;logger;crypto;static create=(t,n,r,i,a)=>new tt({config:jt({...n},t,{type:r.name,ver:r.version.split("-")[0]},i,a)},a)},nr=y(u("winston")),te=u("lodash-es"),m=e=>e==null||e===""||String(e).trim()===""?"":String(e);function rt(e){if(e==null||e==="")return 0;let t=e.toString().replace(/[^0-9.]/g,"");return Number.isNaN(Number(t))?0:Number(t)}function ir(e){if(e==null||e===0||e==="")return+"0.00";let t=rt(e);return Number(t.toFixed(3))}function ar(e){return e==null||e===""||Number.isNaN(Number(e.toString()))?0:Math.floor(Number(e))}function sr(e){return JSON.parse(JSON.stringify(e))}function or(e){return/^-?\d+$/.test(e)}function cr(e){if(!(e==null||e.length===0))return re(e)}function re(e){return re(e)}function lr(e,t){return(0,te.get)(e,t)}function pr(e,t,n){return(0,te.set)(e,t,n)}function dr(e,t){return(0,te.isEqual)(e,t)}function ur(e){return e?e.trim().toLowerCase():""}function gr(e){return e==null?"":(e=e.trim().replace(/-/gi,"").replace(/\(/gi,"").replace(/\)/gi,"").replace(/ /g,"").replace(/\+/g,""),e)}var fr=["order","subscriptionItemPurchase","oneTimeItemPurchase"],mr=(e,t,n)=>{if(!e.activity)return[];let r=e.activity,i=r.activityName==="custom"?r.activityNameCustom:r.activityName;if(!i)return[];let a=i.toLowerCase(),s=[];return t.forEach(c=>{if(!c)return;switch(c.type){case"activityTracked":{if(!c.activityNames||!c.activityNames.find(p=>p.toLowerCase()===a))return;n.verbose("Matched activity tracked filter",{filter:c,activityName:i});break}case"purchaseMade":{if(!r.activityName||!fr.includes(r.activityName))return;n.verbose("Matched purchase made activity filter",{filter:c,activityName:i});break}default:{n.warn("Unknown activity filter type",{filter:c});return}}let o=c.sourceFilter;if(!o)return;let l=e.source,d;try{d=l?.loc?new URL(l.loc).hostname.toLowerCase():null}catch(p){n.error("Failed to parse activity source URL",{ex:nr.default.exceptions.getAllInfo(p),activitySource:l}),d=null}let v=l?.pipeline?.convergePipelineIntegrationInstanceId?.toLowerCase(),g=o.filters?o.filters.map(p=>{switch(p.type){case"wildcard":return n.verbose("Matched wildcard source filter",{sourceFilter:p}),!0;case"domain":return!d||!p.key?!1:d===p.key.toLowerCase()?(n.verbose("Matched domain source filter",{sourceFilter:p,activityHostname:d}),!0):!1;case"pipeline":return!v||!p.key?!1:v===p.key.toLowerCase()?(n.verbose("Matched pipeline source filter",{sourceFilter:p,sourceConvergePipelineIntegrationInstanceId:v}),!0):!1}}):[];switch(o.comparer){case"and":{g.every(p=>p===!0)&&s.push(c);break}case"or":{g.some(p=>p===!0)&&s.push(c);break}default:{n.warn("Unknown source filter comparer",{sourceFilters:o});break}}}),s},hr=(e,t=!1)=>{let n=e.commerce,r=n?.totalPrice||n?.products?.map(a=>(a.unitPrice||0)*(a.quantity||1)).reduce((a,s)=>a+s,0)||void 0,i=n?.currencyCode||null;if((!r||r<=0)&&(r=e?.lead?.predictedLtv||e?.lead?.predictedValue,r&&e?.lead?.currencyCode&&(i=e?.lead?.currencyCode||null)),(!r||r<=0)&&(r=e?.contentItem?.value,r&&e?.contentItem?.currencyCode&&(i=e?.contentItem?.currencyCode||null)),(!r||r<=0)&&(e?.contentItem?.items&&e?.contentItem?.items.length>0&&(r=e?.contentItem?.items.map(a=>a&&a.unitPrice?a.unitPrice*(a.quantity||1):0).reduce((a,s)=>a+s,0)),r&&(i=e?.contentItem?.currencyCode||e?.commerce?.currencyCode||null,!i))){let a=e?.contentItem?.items?.filter(s=>s.currencyCode)||[];a.length>0&&(i=a[0].currencyCode||null)}if((!r||r<=0)&&e?.commerce?.products&&e?.commerce?.products.length>0&&(r=e?.commerce?.products.map(a=>a&&a.unitPrice?a.unitPrice*(a.quantity||1):0).reduce((a,s)=>a+s,0),r&&(i=e?.commerce?.currencyCode||null,!i))){let a=e?.commerce?.products?.filter(s=>s.currencyCode)||[];a.length>0&&(i=a[0].currencyCode||null)}return(!r||r<=0)&&!i?null:{value:r===0&&t?null:r||null,currencyCode:i}};function yr(e,t,n){if(!e)return;let r=t.processing?.contentIdentificationBehavior,i=null;(n=="googleAnalytics"||n=="googleAds")&&(t.analytics?.libraries?.googleAnalytics?.merchant?.productItemIdBehavior!=null&&(r=t.analytics?.libraries?.googleAnalytics?.merchant?.productItemIdBehavior),i=m(t.analytics?.libraries?.googleAnalytics?.merchant?.productItemIdPrefix));let a;switch(r){case"sku":a=e?.sku;break;case"productId":a=e?.productIdentifier;break;case"variantId":a=e?.variantIdentifier;break;case"productIdAndVariantIdUnderscore":m(e.variantIdentifier)&&m(e.productIdentifier)?a=`${e.productIdentifier}_${e.variantIdentifier}`:m(e.variantIdentifier)?a=e.variantIdentifier:a=e.productIdentifier;break;case"variantIdOrProductId":m(e.variantIdentifier)?a=e.variantIdentifier:a=e.productIdentifier;break;default:a=m(e?.sku)||m(e?.variantIdentifier)||m(e?.productIdentifier);break}return i?`${i}${a}`:a}function Ir(e,t){return m(e?.variantName)||m(e?.productName)}function vr(e){if(!e||e.trim().length===0)return!1;let t=e.split(".").filter(n=>n.trim().length>0);return!(t.length!==4||t[0].toLowerCase()!=="sk".toLowerCase()||t[1].toLowerCase()!=="1".toLowerCase()||isNaN(parseInt(t[2],10))||isNaN(parseInt(t[3],10)))}var kr={defaultIssuerUrl:ze,defaultTelemetryUrl:Wt,defaultIngestUrl:Ve}});var $=xt(it());import{createClient as Ar}from"redis";import*as D from"winston";var Sr=()=>{let e=process.env.REDIS_CONNECTION_TLS==="true"?"rediss://":"redis://";return process.env.REDIS_CONNECTION_USER&&process.env.REDIS_CONNECTION_PASSWORD?`${e}${process.env.REDIS_CONNECTION_USER}:${process.env.REDIS_CONNECTION_PASSWORD}@${process.env.REDIS_CONNECTION_HOST}:${process.env.REDIS_CONNECTION_PORT}`:`${e}${process.env.REDIS_CONNECTION_HOST}:${process.env.REDIS_CONNECTION_PORT}`},ne="__SEEKA_REDIS_CLIENT__",P=e=>{if(global[ne])return global[ne];let t=Ar({url:Sr(),disableClientInfo:!0}).on("error",n=>e.error("Redis Client ",{ex:D.exceptions.getAllInfo(n)}));return global[ne]=t,t},Pr=async e=>{await P(e).connect()},at=async e=>P(e).isOpen,wr=async e=>{P(e).destroy()},st=e=>`seeka:app:${process.env.SEEKA_APP_ID}:${e}`,F=(e,t)=>`${st(e)}:${t}`,O=e=>e==="install",ot=()=>{let e=process.env.DATA_ENCRYPTION_KEY;if(!e)throw new Error("DATA_ENCRYPTION_KEY is required to encrypt/decrypt installation state");return e},ct=e=>{if(!e)return!1;let t=e.split("|");if(t.length!==2)return!1;let[n,r]=t;return!n||!r?!1:/^[0-9a-f]+$/i.test(n)&&/^[0-9a-f]{32}$/i.test(r)},ie=e=>{if(!ct(e))return{plainText:e,wasEncrypted:!1};let t=ot();return{plainText:(0,$.decryptText)(e,t),wasEncrypted:!0}},_=e=>{if(ct(e))return{encryptedText:e,wasEncrypted:!0};let t=ot();return{encryptedText:(0,$.encryptText)(e,t),wasEncrypted:!1}};async function Kr(e,t,n,r="string",i){let a=F(e,t),s=P(i),c=await gt(s,a);if(c){if(r==="string"&&O(e)){let{plainText:o,wasEncrypted:l}=ie(c);if(!l){let{encryptedText:d}=_(c);await s.set(a,d)}return JSON.parse(o)}return JSON.parse(c)}if(r==="json")await s.json.set(a,"$",n);else{let o=JSON.stringify(n);if(O(e)){let{encryptedText:l}=_(o);await s.set(a,l)}else await s.set(a,o)}return n}async function lt(e,t,n="string",r){let i=F(e,t),a=P(r);if(n==="json"){let s=await a.json.get(i);if(s)return s}else{let s=await gt(a,i);if(s){if(O(e)){let{plainText:c,wasEncrypted:o}=ie(s);if(!o){let{encryptedText:l}=_(s);await a.set(i,l)}return JSON.parse(c)}return JSON.parse(s)}}return null}async function pt(e,t){let n=st(e),r=P(t),i=await r.keys(`${n}:*`),a=await r.mGet(i);if(a){let s=[];for(let c=0;c<a.length;c++){let o=a[c],l=i[c];if(!o)continue;let d=o;if(O(e)){let{plainText:v,wasEncrypted:g}=ie(d);if(!g){let{encryptedText:p}=_(d);await r.set(l,p)}s.push(JSON.parse(v))}else s.push(JSON.parse(d))}return s}return[]}async function dt(e,t,n,r="string",i){let a=F(e,t),s=P(i);if(r==="json")await s.json.set(a,"$",n);else{let c=JSON.stringify(n);if(O(e)){let{encryptedText:o}=_(c);await s.set(a,o)}else await s.set(a,c)}}async function ut(e,t,n){let r=F(e,t);await P(n).del(r)}async function gt(e,t){let n=await e.get(t);return typeof n=="string"?n:n?n.toString():""}var ft=async e=>{e.debug(`Trying to connect to Redis - ${process.env.REDIS_CONNECTION_HOST}`);try{await at(e)?e.verbose(`Redis already connected - ${process.env.REDIS_CONNECTION_HOST}`):(e.profile("service.redis.connect"),await Pr(e),e.profile("service.redis.connect"),e.debug(`Redis connected - ${process.env.REDIS_CONNECTION_HOST}`))}catch(t){throw e.error(`Failed to connect to Redis - ${process.env.REDIS_CONNECTION_HOST}`,{ex:D.exceptions.getAllInfo(t)}),t}},Jr=async e=>{e.debug(`Trying to disconnect from Redis - ${process.env.REDIS_CONNECTION_HOST}`);try{await at(e)===!1?e.verbose(`Redis already disconnected - ${process.env.REDIS_CONNECTION_HOST}`):(e.profile("service.redis.disconnect"),await wr(e),e.profile("service.redis.disconnect"),e.verbose(`Redis disconnected - ${process.env.REDIS_CONNECTION_HOST}`))}catch(t){throw e.error(`Failed to disconnect from Redis - ${process.env.REDIS_CONNECTION_HOST}`,{ex:D.exceptions.getAllInfo(t)}),t}};var q="install",ae=async(e,t,n)=>{let r=await lt(q,e,"string",n);if(r==null&&t)throw n.error(`Seeka installation ${e} not found`),new Error(`Seeka installation ${e} not found`);return r},Yr=async e=>await pt(q,e),Qr=async(e,t)=>{e.installationState||(e.installationState={}),e.installedAt||(e.installedAt=new Date().toISOString());let n=await ae(e.applicationInstallId,!1,t)===null;return await dt(q,e.applicationInstallId,e,"string",t),t.info(n?"Created installation state":"Updated installation state",{applicationInstallId:e.applicationInstallId,organisationId:e.organisationId,organisationBrandId:e.organisationBrandId}),e},Xr=async(e,t)=>{await ut(q,e,t),t.info("Deleted installation state",{applicationInstallId:e})};var M=e=>"seeka_app_"+e+"_at_app",W=e=>"seeka_app_"+e+"_at_core",se="X-Seeka-App-Token",oe="X-Seeka-CoreApi-Token",j="at_app",H="at_core";import Cr from"jsonwebtoken";var mt=async(e,t,n,r)=>{let i=new URL(e),a=t.get("Cookie"),s=i.searchParams.get(j)||"";if(!s&&t.get(se)&&(s=t.get(se)?.split("Bearer ")[1]),!s&&a){let o=a.split(";").find(l=>l.trim().startsWith(M(process.env.SEEKA_APP_ID)));o&&(s=o.split("=")[1])}let c=i.searchParams.get(H)||"";if(!c&&t.get(oe)&&(c=t.get(oe)?.split("Bearer ")[1]),!c&&a){let o=a.split(";").find(l=>l.trim().startsWith(W(process.env.SEEKA_APP_ID)));o&&(c=o.split("=")[1])}return await Tr(s,c,n,r)},Tr=async(e,t,n,r)=>{let i,a,s;if(e)try{let o=Cr.verify(e,process.env.SEEKA_APP_SECRET,{ignoreNotBefore:!0});if(r.info("Decoded token",{decoded:o}),!o.appId||o.appId.replace(/-/g,"")!==process.env.SEEKA_APP_ID.replace(/-/g,"")){r.error("Invalid token - app id does not match",{decoded:o,appIdToken:o.appId,appIdEnv:process.env.SEEKA_APP_ID});return}else i=o.appId;if(o.appInstallId)a=o.appInstallId;else{r.error("Invalid token - no appInstallId",{decoded:o});return}s=o.exp}catch(o){r.error("Failed to validate token",{err:o});return}else{r.error("No access token present");return}n&&await n(r);let c=await ae(a,!1,r);if(c==null){r.warn("UI call cannot be processed as the installation ID is not known by this app",{seekaAppInstallId:a});return}return{appAccessToken:e,coreApiAccessToken:t,seekaAppId:i,seekaAppInstallId:a,expiresAt:s,installation:c}};import*as G from"fs/promises";import R from"path";import{OpenTelemetryTransportV3 as Nr}from"@opentelemetry/winston-transport";import*as I from"winston";var ht=[new I.transports.Console({level:process.env.LOGGING_LEVEL,format:I.format.combine(I.format.errors({stack:!0}),I.format.cli(),I.format.splat()),handleExceptions:!0,handleRejections:!0})];process.env.OTEL_SDK_DISABLED!=="true"&&ht.push(new Nr({handleExceptions:!0,handleRejections:!0}));var xr=I.createLogger({level:process.env.LOGGING_LEVEL,transports:ht,exitOnError:!1}),T=(e,t,n=xr,r={})=>n.child({...e,...t?{seekaAppInstallId:t.applicationInstallId,seekaAppInstallOrganisationBrandId:t.organisationBrandId,seekaAppInstallOrganisationId:t.organisationId,...r?.invocationId?{"faas.invocation_id":r.invocationId}:{}}:{}}),on=(e,t)=>{let n={seekaWebhookType:e.type,seekaWebhookIsTest:e.isTest,RequestId:e.requestId,"faas.invocation_id":t.invocationId,CausationId:e.causationId,CorrelationId:e.causationId},r=e.context;return r&&(n.seekaAppInstallId=r.applicationInstallId,n.seekaAppInstallOrganisationBrandId=r.organisationBrandId,n.seekaAppInstallOrganisationId=r.organisationId),T(n)},cn=(e,t,n)=>{let r={jobContext:t,jobName:e,"faas.invocation_id":n.invocationId,CausationId:t?.causationId,CorrelationId:t?.causationId,seekaAppInstallId:t?.applicationInstallId??t?.payload.applicationInstallId,seekaAppInstallOrganisationBrandId:t?.organisationBrandId,seekaAppInstallOrganisationId:t?.organisationId};return T(r)};async function yt(e,t){return await G.readFile(e,{encoding:t})}var ce="config.js",hn=async(e,t,n,r,i,a)=>{let s=T(null,void 0,void 0,r);s.profile("http.seeka.webhook.app.ui");let o=new URL(e).pathname?.replace(/^\/app/,"")||"/";s.verbose("Received Seeka UI request",{requestedPath:o,url:e,method:t});let l=R.resolve("./dist/src/ui/build"),d=null,v=null,g,p={},K=[],f,J=async()=>o==="/health"?null:(f=await mt(e,n,()=>ft(s),s),f?(d=f.seekaAppId,v=f.seekaAppInstallId,g=f.installation,s=T(null,g,s,r),s.verbose("Authenticated Seeka UI request",{requestedPath:o,url:e,method:t}),s=T(null,g,s,r),K.push({name:M(process.env.SEEKA_APP_ID),value:f.appAccessToken,httpOnly:!0,secure:!0,sameSite:"None",expires:new Date(f.expiresAt*1e3)}),K.push({name:W(process.env.SEEKA_APP_ID),value:f.coreApiAccessToken,httpOnly:!0,secure:!0,sameSite:"None",expires:new Date(f.expiresAt*1e3)}),null):{status:403,jsonBody:{error:"Invalid token"}}),k=R.join(l,o),w;try{if(o==="/health")return{status:200,jsonBody:{status:"ok"}};if(o==="/"+ce){let h=await J();if(h)return h;let C=process.env.APP_UI_BASE_PATH?`${process.env.APP_UI_BASE_PATH}`:"",N=`${process.env.SELF_HOST_BASEURL}${C}`,kt={seekaAppId:d||"",seekaAppInstallId:v||"",organisationBrandId:g?.organisationBrandId||"",appBaseUrl:N,state:await i(g,s)};w=`window.seekaAppConfig = ${JSON.stringify(kt)}`}if(o.startsWith("/api")){let h=await J();if(h)return h;let C=await a(o,t,g,s);return C||{status:404,jsonBody:{error:"Not found"}}}if(o==="/"||o==="/index.html"){let h=await J();if(h)return h;let C=`?${j}=${encodeURIComponent(f?.appAccessToken||"")}&${H}=${encodeURIComponent(f?.coreApiAccessToken||"")}&`;k=R.join(l,"index.html");let N=await yt(k,"utf-8");N=N.replace(ce+"?",ce+C),w=N}else w||(k=R.join(l,o),await G.access(k))}catch(h){k=R.join(l,"index.html"),console.log("File not found, serving index.html",{err:h,requestedPath:o,buildPath:l,filePath:k,content:w})}return w||(w=await yt(k)),{status:200,headers:{"Content-Type":br(k),"Referrer-Policy":"no-referrer",...p},cookies:K,body:w}};function br(e){return e.endsWith(".html")?"text/html":e.endsWith(".js")?"application/javascript":e.endsWith(".css")?"text/css":e.endsWith(".png")?"image/png":e.endsWith(".jpg")||e.endsWith(".jpeg")?"image/jpeg":e.endsWith(".gif")?"image/gif":"application/octet-stream"}import vt from"fs/promises";import It from"path";import Er from"winston";var Or=async e=>vt.stat(e).then(()=>!0).catch(()=>!1);async function Sn(e,t,n,r){let a=It.resolve(It.join(t,"seeka-browser-plugin.min.js"));return await _r(e,a,n,r)}async function _r(e,t,n,r){r.profile("http.seeka.browser.plugin");let i,a;try{r.verbose("Handling request for browser plugin content",{path:t}),await Or(t)?(r.verbose("Browser plugin content found",{path:t}),i=await vt.readFile(t,"utf8"),a=`${e}(${JSON.stringify(n)})`):r.error("Browser plugin content not found",{path:t})}catch(s){r.error("Failed to handle request for browser plugin content",{ex:Er.exceptions.getAllInfo(s)})}finally{r.profile("http.seeka.browser.plugin"),r.verbose("Request for browser plugin content handled")}if(!i||!a)throw new Error("Failed to handle request for browser plugin content");return{content:i,init:a}}export{xr as appLogger,cn as backgroundJobLogger,Tr as checkAuth,T as childLogger,Pr as connect,Qr as createOrUpdateInstallation,Xr as deleteInstallation,wr as disconnect,hn as generateAppUiHttpRequestResponse,mt as getAccessTokenAndCheck,F as getKey,pt as getList,Kr as getOrCreate,P as getOrCreateClient,Sn as getSeekaBrowserPlugin,_r as getSeekaBrowserPluginByName,at as isConnected,Yr as listInstallations,ut as remove,dt as set,ft as startServices,Jr as stopServices,lt as tryGet,ae as tryGetInstallation,on as webhookLogger};
1
+ var At=Object.create;var le=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var u=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Tt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Nt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Pt(t))!Ct.call(e,i)&&i!==n&&le(e,i,{get:()=>t[i],enumerable:!(r=St(t,i))||r.enumerable});return e};var xt=(e,t,n)=>(n=e!=null?At(wt(e)):{},Nt(t||!e||!e.__esModule?le(n,"default",{value:e,enumerable:!0}):n,e));var it=Tt((Lr,nt)=>{"use strict";var bt=Object.create,B=Object.defineProperty,Et=Object.getOwnPropertyDescriptor,Ot=Object.getOwnPropertyNames,_t=Object.getPrototypeOf,Rt=Object.prototype.hasOwnProperty,Ut=(e,t)=>{for(var n in t)B(e,n,{get:t[n],enumerable:!0})},ge=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ot(t))!Rt.call(e,i)&&i!==n&&B(e,i,{get:()=>t[i],enumerable:!(r=Et(t,i))||r.enumerable});return e},y=(e,t,n)=>(n=e!=null?bt(_t(e)):{},ge(t||!e||!e.__esModule?B(n,"default",{value:e,enumerable:!0}):n,e)),Lt=e=>ge(B({},"__esModule",{value:!0}),e),fe={};Ut(fe,{ActivityPipelineActivityFilterSourceItemType:()=>_e,ActivityPipelineActivityFilterType:()=>Ee,AnalyticsLibrary:()=>Ue,ApiException:()=>We,ApiServiceProxyBase:()=>Q,AppPermissionKeys:()=>A,ClickAttributionSourcePlatform:()=>be,ConditionComparer:()=>Oe,ConditionOperator:()=>Re,ConsentMappingMatchType:()=>qe,ContentIdentificationBehavior:()=>Le,ConvergePipelineLoggableActivityType:()=>Te,ConvergeVendorDestinationPublishStrategy:()=>Be,CrossDomainTrackingUtmBehavior:()=>De,ECommerceContentType:()=>Se,ECommerceFinancialStatus:()=>Ce,ECommerceFulfillmentStatus:()=>we,ECommercePlatform:()=>Pe,IabPrivacyConsentPurposeId:()=>Fe,IabPrivacyConsentPurposeIdMap:()=>Qt,IdentityServiceProxy:()=>ye,IngestServiceProxy:()=>Ie,PrivacyConsentType:()=>ke,PrivacyDataControlMode:()=>Me,RegionalConsentGrantOption:()=>$e,ResponseResultType:()=>ve,SdkLogEventLevel:()=>Ne,SeekaApiHelper:()=>Ye,SeekaAppCacheManager:()=>E,SeekaAppConfig:()=>he,SeekaAppHelper:()=>rr,SeekaWebhookCallType:()=>xe,TrackingActivityNames:()=>L,TrackingEventSourceOriginType:()=>Ae,chunk:()=>z,cloneDeep:()=>sr,dateToUtcDateTimeReferenceString:()=>Ge,decryptText:()=>et,emailAddress:()=>ur,encryptText:()=>Ze,generateNewSessionId:()=>U,getActivityName:()=>$t,getActivityValue:()=>hr,getContentIdFromProduct:()=>yr,getContentNameFromProduct:()=>Ir,getIssuer:()=>Z,getNestedProperty:()=>lr,getNewAppInstallToken:()=>Je,getNewOrCachedAppInstallToken:()=>ee,getRandomNumberString:()=>He,isDeepEqual:()=>dr,isNumber:()=>or,isValidSeekaProfileId:()=>vr,last:()=>re,lastOrDefault:()=>cr,matchActivityPipelineFilters:()=>mr,md5Hash:()=>Ke,parseFloat:()=>rt,parseInt:()=>ar,parseMoney:()=>ir,parseStr:()=>m,phoneNumberToE164:()=>gr,separatePersonFullName:()=>Ft,setNestedProperty:()=>pr,throwOnInvalidWebhookSignature:()=>er,urls:()=>kr,validateWebhookSignature:()=>Qe,webhookSignatureHeaderName:()=>Y});nt.exports=Lt(fe);var Bt="3.8.1",me=y(u("axios")),he=class{appId;appSecret;ingestUrl;issuerUrl;organisationId;applicationInstallId;runtime;logger;grantedPermissions;transformApiRequest;transformApiResponse;hasAnyPermissions;hasAllPermissions;hasPermission},Q=class{config;constructor(e){this.config=e}transformOptions=async e=>await this.config.transformApiRequest(e);transformResult=async(e,t,n)=>await this.config.transformApiResponse(e,t,n)},ye=class extends Q{instance;baseUrl;jsonParseReviver=void 0;constructor(e,t,n){super(e),this.instance=n||me.default.create(),this.baseUrl=t??"https://api-localdev-env0-seeka.au.ngrok.io"}merge(e,t){let n=this.baseUrl+"/api/identity";n=n.replace(/[?&]$/,"");let r={data:JSON.stringify(e),method:"POST",url:n,headers:{"Content-Type":"application/json",Accept:"application/json"},cancelToken:t};return this.transformOptions(r).then(i=>this.instance.request(i)).catch(i=>{if(je(i)&&i.response)return i.response;throw i}).then(i=>this.transformResult(n,i,a=>this.processMerge(a)))}processMerge(e){let t=e.status,n={};if(e.headers&&typeof e.headers=="object")for(let r in e.headers)e.headers.hasOwnProperty(r)&&(n[r]=e.headers[r]);if(t===200){let r=e.data,i=null;return i=JSON.parse(r),Promise.resolve(i)}else if(t===400){let r=e.data,i=null;return i=JSON.parse(r),S("A server side error occurred.",t,r,n,i)}else if(t===401){let r=e.data,i=null;return i=JSON.parse(r),S("A server side error occurred.",t,r,n,i)}else if(t===422){let r=e.data,i=null;return i=JSON.parse(r),S("A server side error occurred.",t,r,n,i)}else if(t!==200&&t!==204){let r=e.data;return S("An unexpected server error occurred.",t,r,n)}return Promise.resolve(null)}},Ie=class extends Q{instance;baseUrl;jsonParseReviver=void 0;constructor(e,t,n){super(e),this.instance=n||me.default.create(),this.baseUrl=t??"https://api-localdev-env0-seeka.au.ngrok.io"}batch(e,t){let n=this.baseUrl+"/api/ingest";n=n.replace(/[?&]$/,"");let r={data:JSON.stringify(e),method:"POST",url:n,headers:{"Content-Type":"application/json"},cancelToken:t};return this.transformOptions(r).then(i=>this.instance.request(i)).catch(i=>{if(je(i)&&i.response)return i.response;throw i}).then(i=>this.transformResult(n,i,a=>this.processBatch(a)))}processBatch(e){let t=e.status,n={};if(e.headers&&typeof e.headers=="object")for(let r in e.headers)e.headers.hasOwnProperty(r)&&(n[r]=e.headers[r]);if(t===202){let r=e.data;return Promise.resolve(null)}else if(t===400){let r=e.data,i=null;return i=JSON.parse(r),S("A server side error occurred.",t,r,n,i)}else if(t===401){let r=e.data,i=null;return i=JSON.parse(r),S("A server side error occurred.",t,r,n,i)}else if(t===422){let r=e.data,i=null;return i=JSON.parse(r),S("A server side error occurred.",t,r,n,i)}else if(t!==200&&t!==204){let r=e.data;return S("An unexpected server error occurred.",t,r,n)}return Promise.resolve(null)}},ve=(e=>(e.Undefined="undefined",e.Success="success",e.Failed="failed",e))(ve||{}),ke=(e=>(e.Unknown="unknown",e.Informed="informed",e.Implied="implied",e.Explicit="explicit",e.Active="active",e.Passive="passive",e))(ke||{}),Ae=(e=>(e.Browser="browser",e.Server="server",e.Mobile="mobile",e.Desktop="desktop",e.PhysicalStore="physicalStore",e.Email="email",e.Phone="phone",e.Chat="chat",e.Automatic="automatic",e))(Ae||{}),L=(e=>(e.Undefined="undefined",e.PageViewOrganic="pageViewOrganic",e.PageViewUtmAttributed="pageViewUtmAttributed",e.AddPaymentMethod="addPaymentMethod",e.AddToWishlist="addToWishlist",e.ContactMessage="contactMessage",e.Custom="custom",e.SyncCart="syncCart",e.Order="order",e.InitiateCheckout="initiateCheckout",e.AddToCart="addToCart",e.RemoveFromCart="removeFromCart",e.OneTimeItemPurchase="oneTimeItemPurchase",e.SubscriptionItemPurchase="subscriptionItemPurchase",e.ViewProduct="viewProduct",e.ViewPage="viewPage",e.ApplyPromotionalCode="applyPromotionalCode",e.KeywordSearch="keywordSearch",e.UserLoginSignup="userLoginSignup",e.UserLogin="userLogin",e.NewsletterSignup="newsletterSignup",e.Lead="lead",e.ChangeProductAttribute="changeProductAttribute",e.FilterItemsByAttribute="filterItemsByAttribute",e.Schedule="schedule",e.ViewContentItem="viewContentItem",e.StartTrial="startTrial",e))(L||{}),Se=(e=>(e.Undefined="undefined",e.SingleProduct="singleProduct",e.SingleVariant="singleVariant",e.Collection="collection",e))(Se||{}),Pe=(e=>(e.None="none",e.BigCommerce="bigCommerce",e.Shopify="shopify",e.OrderGroove="orderGroove",e.Magento="magento",e.Generic="generic",e.WooCommerce="wooCommerce",e.Demandware="demandware",e))(Pe||{}),we=(e=>(e.Undefined="undefined",e.Fulfilled="fulfilled",e.NoneFulfilled="noneFulfilled",e.PartiallyFulfilled="partiallyFulfilled",e.RestockedOrCancelled="restockedOrCancelled",e.Pending="pending",e))(we||{}),Ce=(e=>(e.Undefined="undefined",e.Pending="pending",e.Authorized="authorized",e.PartiallyPaid="partiallyPaid",e.Paid="paid",e.PartiallyRefunded="partiallyRefunded",e.Refunded="refunded",e.Voided="voided",e))(Ce||{}),Te=(e=>(e.Generic="generic",e.ActivityIngress="activityIngress",e.ActivityEgress="activityEgress",e.UserProfile="userProfile",e.SdkLog="sdkLog",e.Detections="detections",e.ActivityEgressFilter="activityEgressFilter",e.Diagnosis="diagnosis",e.PipelineIntegrationOutput="pipelineIntegrationOutput",e))(Te||{}),Ne=(e=>(e.Information="information",e.Warning="warning",e.Error="error",e.Verbose="verbose",e))(Ne||{}),xe=(e=>(e.None="none",e.Probe="probe",e.AppInstalled="appInstalled",e.IdentityChanged="identityChanged",e.ActivityAccepted="activityAccepted",e.AppInstallSettingsUpdated="appInstallSettingsUpdated",e.AppUninstalled="appUninstalled",e.BrowserSdkPlugin="browserSdkPlugin",e))(xe||{}),be=(e=>(e.Unknown="unknown",e.Google="google",e.Meta="meta",e.Snapchat="snapchat",e.Pinterest="pinterest",e.TikTok="tikTok",e))(be||{}),Ee=(e=>(e.Undefined="undefined",e.PurchaseMade="purchaseMade",e.ActivityTracked="activityTracked",e))(Ee||{}),Oe=(e=>(e.Undefined="undefined",e.And="and",e.Or="or",e))(Oe||{}),_e=(e=>(e.Undefined="undefined",e.Domain="domain",e.Pipeline="pipeline",e.Wildcard="wildcard",e.Url="url",e.PagePath="pagePath",e))(_e||{}),Re=(e=>(e.Undefined="undefined",e.Equals="equals",e.NotEquals="notEquals",e.Contains="contains",e.NotContains="notContains",e.StartsWith="startsWith",e.EndsWith="endsWith",e.IsNull="isNull",e.NotNull="notNull",e.IsTrue="isTrue",e.IsFalse="isFalse",e.GreaterThanOrEquals="greaterThanOrEquals",e.LessThanOrEquals="lessThanOrEquals",e.GreaterThan="greaterThan",e.LessThan="lessThan",e.Before="before",e.After="after",e.Between="between",e.In="in",e.NotIn="notIn",e.Regex="regEx",e.Any="any",e))(Re||{}),Ue=(e=>(e.Undefined="undefined",e.Seeka="seeka",e.DynamicYield="dynamicYield",e.Segment="segment",e.FacebookPixel="facebookPixel",e.GoogleAnalytics="googleAnalytics",e.Braze="braze",e.SnapchatPixel="snapchatPixel",e.Pinterest="pinterest",e.TikTokPixel="tikTokPixel",e.GoogleAds="googleAds",e))(Ue||{}),Le=(e=>(e.Default="default",e.Sku="sku",e.ProductId="productId",e.VariantId="variantId",e.ProductIdAndVariantIdUnderscore="productIdAndVariantIdUnderscore",e.VariantIdOrProductId="variantIdOrProductId",e))(Le||{}),Be=(e=>(e.DeliverAllTraitsAndDeliverAllEvents="deliverAllTraitsAndDeliverAllEvents",e.DeliverAllTraitsAndDeliverEventsOnlyIfMaxWeightedTraitsPresent="deliverAllTraitsAndDeliverEventsOnlyIfMaxWeightedTraitsPresent",e.DeliverMaxWeightedTraitsOnlyAndDeliverAllEvents="deliverMaxWeightedTraitsOnlyAndDeliverAllEvents",e.DeliverMaxWeightedTraitsOnlyAndDeliverEventsOnlyIfMaxWeightedTraitsPresent="deliverMaxWeightedTraitsOnlyAndDeliverEventsOnlyIfMaxWeightedTraitsPresent",e))(Be||{}),De=(e=>(e.None="none",e.SessionPassthrough="sessionPassthrough",e.UrlPassthrough="urlPassthrough",e))(De||{}),$e=(e=>(e.Unset="unset",e.Granted="granted",e.Denied="denied",e))($e||{}),Fe=(e=>(e.Undefined="undefined",e.MeasureAdvertisingPerformance="measureAdvertisingPerformance",e))(Fe||{}),qe=(e=>(e.Undefined="undefined",e.AllOf="allOf",e.AnyOf="anyOf",e))(qe||{}),Me=(e=>(e.Disabled="disabled",e.Explicit="explicit",e.Implicit="implicit",e))(Me||{}),We=class extends Error{message;status;response;headers;result;constructor(e,t,n,r,i){super(),this.message=e,this.status=t,this.response=n,this.headers=r,this.result=i}isApiException=!0;static isApiException(e){return e.isApiException===!0}};function S(e,t,n,r,i){throw i??new We(e,t,n,r,null)}function je(e){return e&&e.isAxiosError===!0}var b=u("openid-client"),X=y(u("winston")),V=y(u("memory-cache")),pe="seeka:sdk",E=class{constructor(e,t){this.appId=e,this.appInstallationId=t}appId;appInstallationId;set=async(e,t,n)=>{let r=this.getKey(e);V.default.put(r,JSON.stringify(t),n)};getOrSet=async(e,t,n)=>{let r=this.getKey(e),i=V.default.get(r);if(i){let s=JSON.parse(i);return n&&await n(s),s}let a=await t();return a?(V.default.put(r,JSON.stringify(a.value),a.expiryAbsoluteMilliseconds),a.value):null};getKey=e=>this.appInstallationId?`${pe}:${this.appId}:${this.appInstallationId}:${e}`:`${pe}:${this.appId}:${e}`},Dt=y(u("crypto")),U=()=>{let e=Ge(new Date),t=He();return`${e}.${t}`},$t=e=>{let t=Object.keys(L),n=e.toLowerCase(),r=t.find(i=>i.toLowerCase()===n);return r?L[r]:"custom"},He=()=>Math.floor(Math.random()*(9999999999-1e9)+1e9).toString(),Ge=e=>{let t=(e.getUTCMonth()+1).toString();t.length<2&&(t="0"+t);let n=e.getUTCDate().toString();n.length<2&&(n="0"+n);let r=e.getUTCHours().toString();r.length<2&&(r="0"+r);let i=e.getUTCMinutes().toString();i.length<2&&(i="0"+i);let a=e.getUTCSeconds().toString();return a.length<2&&(a="0"+a),`${e.getUTCFullYear()}${t}${n}.${r}${i}${a}`},Ke=e=>Dt.createHash("md5").update(e).digest("hex"),Ft=e=>{if(!e)return{firstName:null,lastName:null};let t=e.trim().split(" ");return t.length===1?{firstName:e,lastName:null}:t.length===2?{firstName:t[0],lastName:t[1]}:{firstName:t[0],lastName:t.slice(1).join(" ")}},z=(e,t)=>e.reduce((n,r,i)=>{let a=Math.floor(i/t);return n[a]||(n[a]=[]),n[a].push(r),n},[]),Z=async e=>{let t={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.debug("Seeka auth: getting issuer",{...t}):console.debug("Seeka auth: getting issuer",{...t});let n=new E(e.appId,e.applicationInstallId),r=Ke(e.issuerUrl+"_"+e.appId),i=await n.getOrSet(r,async()=>{try{let a=await qt(e);return!a||!a.meta||!a.raw?null:(e.logger?e.logger.verbose("Seeka auth: got issuer from remote",{...t}):console.debug("Seeka auth: got issuer from remote",{...t}),{value:a.meta,expiryAbsoluteMilliseconds:1e3*60*60})}catch(a){return e.logger?e.logger.error("Seeka auth: failed getting issuer",{...t,ex:X.default.exceptions.getAllInfo(a)}):console.error("Seeka auth: failed getting issuer",{...t}),null}},async()=>{e.logger?e.logger.verbose("Seeka auth: got issuer from cache",{...t}):console.debug("Seeka auth: got issuer from cache",{...t})});return i===null?null:new b.Configuration(i.serverMetadata,i.clientId,e.appSecret)},qt=async e=>{let t={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.verbose("Seeka auth: discovering issuer from remote",{...t}):console.info("Seeka auth: discovering issuer from remote",{...t});try{let n=e.appId.replace(/-/g,""),r=await(0,b.discovery)(new URL(e.issuerUrl),n,void 0,(0,b.None)(),{timeout:1e4});return e.logger?e.logger.verbose("Seeka auth: discovered issuer from remote",{...t,client_id:r.clientMetadata().client_id}):console.info("Seeka auth: discovered issuer from remote",{...t,client_id:r.clientMetadata().client_id}),{meta:{serverMetadata:r.serverMetadata(),clientMetadata:r.clientMetadata(),timeout:r.timeout,clientId:n},raw:r}}catch(n){return e.logger?e.logger.error("Seeka auth: failed discovering issuer from remote",{...t,ex:X.default.exceptions.getAllInfo(n)}):console.error("Seeka auth: failed discovering issuer from remote",{...t,err:n}),null}},Mt=async e=>{let t={applicationId:e.appId,issuer:{url:e.issuerUrl}},n=await Z(e);if(!n)return null;try{let r=await(0,b.clientCredentialsGrant)(n,{resource:n.clientMetadata().client_id}),i={...t,token:{expires_at:r.expires_at,token_type:r.token_type,scope:r.scope}};return e.logger?e.logger.verbose("Seeka auth: got client access token from server",{...i}):console.info("Seeka auth: got app client token from server",{...i}),{token_type:r.token_type,access_token:r.access_token,expires_in:r.expires_in,id_token:r.id_token,refresh_token:r.refresh_token,scope:r.scope,authorization_details:r.authorization_details}}catch(r){let i={...t,error:r};return e.logger?e.logger.error("Seeka auth: failed to get client access token from server",{...i}):console.error("Seeka auth: failed to get client access token from server",{...i,err:X.default.exceptions.getAllInfo(r)}),null}},Je=async(e,t)=>{let n={applicationId:t.appId,issuer:{url:t.issuerUrl}},r=await Z(t);if(!r||!r)return null;try{let i=await(0,b.genericGrantRequest)(r,"app_install_token",{applicationInstallId:t.applicationInstallId,access_token:e,scope:"Seeka.API.Ingest"}),a={...n,token:{expires_at:i.expires_at,token_type:i.token_type,scope:i.scope}};return t.logger?t.logger.verbose("Seeka auth: got app access token from server",{...a}):console.info("Seeka auth: got app access token from server",{...a}),{token_type:i.token_type,access_token:i.access_token,expires_in:i.expires_in,id_token:i.id_token,refresh_token:i.refresh_token,scope:i.scope,authorization_details:i.authorization_details}}catch(i){let a={...n,error:i};return t.logger?t.logger.error("Seeka auth: failed to get app access token from server",{...a}):console.debug("Seeka auth: failed to get app access token from server",{...a}),null}},ee=async e=>{let t=new E(e.appId,e.applicationInstallId),n={applicationId:e.appId,issuer:{url:e.issuerUrl}};return await t.getOrSet("auth:token:appinstall",async()=>{let r=await Mt(e);if(!r||!r.access_token)return null;let i=await Je(r.access_token,e);return i?{value:i,expiryAbsoluteMilliseconds:((i.expires_in>r.expires_in?r.expires_in:i.expires_in)||900*1e3)-60*1e3}:null},async()=>{e.logger?e.logger.verbose("Seeka auth: got app token from cache",{...n}):console.debug("Seeka auth: got app token from cache",{...n})})},Ve="https://router.seeka.services",Wt="https://router.seeka.services/tel/otel",ze="https://account.seeka.app",jt=(e,t,n,r,i)=>{let a=new he;return a.appId=e.applicationId,a.appSecret=t,a.ingestUrl=process.env.SEEKA_INGEST_URL||Ve,a.issuerUrl=process.env.SEEKA_ISSUER_URL||ze,a.organisationId=e.organisationId,a.applicationInstallId=e.applicationInstallId,a.runtime={type:"sdk/js/apps-server",ver:Bt.split("-")[0],client:n},a.logger=i,a.grantedPermissions=r,a.transformApiRequest=s=>Ht(a,s),a.transformApiResponse=async(s,c,o)=>Gt(a,s,c,o),a.hasAnyPermissions=s=>!a.grantedPermissions||a.grantedPermissions.length===0?!1:!s||s.length===0?!0:s.some(c=>a.grantedPermissions.includes(c)),a.hasAllPermissions=s=>!a.grantedPermissions||a.grantedPermissions.length===0?!1:!s||s.length===0?!0:s.every(c=>a.grantedPermissions.includes(c)),a.hasPermission=s=>!a.grantedPermissions||a.grantedPermissions.length===0?!1:s?a.grantedPermissions.includes(s):!0,a},Ht=async(e,t)=>{let n=await ee(e);if(!n||!n.access_token)throw new Error("Could not get access token for API request");return t.headers={...t.headers,"X-OrgId":e.organisationId,Authorization:"Bearer "+n?.access_token},t},Gt=async(e,t,n,r)=>(n.data=JSON.stringify(n.data),r(n)),A={identity:{receiveFull:"Identity.Receive.Pii",send:"Identity.Send"},activity:{receiveAnon:"Activity.Receive.Anon",receiveFull:"Activity.Receive.Pii",send:"Activity.Send"}},Kt=y(u("axios")),Jt=y(u("http")),Vt=y(u("https")),zt=new Jt.default.Agent({keepAlive:!0,scheduling:"fifo"}),Yt=new Vt.default.Agent({keepAlive:!0,scheduling:"fifo"}),de=e=>{let t=Kt.default.create({httpAgent:zt,httpsAgent:Yt});return t.interceptors.request.use(function(n){let r={url:n.url,method:n.method};return process.env.LOGGING_LEVEL==="silly"&&(r={...r,body:n.data,params:n.params}),e.logger?e.logger.debug(`Seeka API: making call to ${r.url}`,{...r}):console.debug(`Seeka API: making call to ${r.url}`,{...r}),n},function(n){let r={error:n};return e.logger?e.logger.http("Seeka API: failed to send request",{...r}):console.debug("Seeka API: failed to send request",{...r}),Promise.reject(n)}),t.interceptors.response.use(function(n){let r={url:n.request?.url||n.config.url,method:n.request?.method||n.config.method,response:{status:n.status}};return e.logger?e.logger.http(`Seeka API: call to ${r.url} succeeded`,{...r}):console.debug(`Seeka API: call to ${r.url} succeeded`,{...r}),n},function(n){let{code:r,status:i,message:a}=n,{headers:s,url:c,method:o}=n?.config,l={code:r,status:i,message:a,headers:s,url:c,method:o,content:n?.response?.data};return e.logger?e.logger.error(`Seeka API: call to ${l.url} failed`,{...l}):console.error(`Seeka API: call to ${l.url} failed`,{...l}),Promise.reject(n)}),t},ue={getIdentityService:e=>new ye(e,e.ingestUrl,de(e)),getIngestService:e=>new Ie(e,e.ingestUrl,de(e))},Ye=class{constructor(e){this.config=e,this.ingestionService=ue.getIngestService(e),this.identityService=ue.getIdentityService(e)}config;maxBatchSize=50;refreshOrPrimeTokenCache=async()=>{await ee(this.config)};ingestionService;identityService;checkPermission=(e,t)=>{if(!this.config.hasPermission(e))throw new Error("Cannot perform operation "+t+" on installationId "+this.config.applicationInstallId+" without permission "+e+". Currently granted permissions: "+(this.config.grantedPermissions?this.config.grantedPermissions.join(", "):"none"));return!0};mergeIdentity=async(e,t)=>{this.checkPermission(A.identity.send,"mergeIdentity");let n=U();return(await this.identityService.merge({id:e,src:{method:"",origin:t.origin,time:void 0,loc:t.loc,sess:n,diag:process.env.SEEKA_DEBUG_ENABLED==="true"?n:void 0,runtime:this.config.runtime}})).result?.personId};mergeIdentityBatch=async(e,t)=>{this.checkPermission(A.identity.send,"mergeIdentityBatch");let n=U();if(e.length===0){this.config.logger?.debug("No identities in batch");return}let r={method:"",origin:t.origin,time:void 0,loc:t.loc,sess:n,diag:process.env.SEEKA_DEBUG_ENABLED==="true"?n:void 0,runtime:this.config.runtime},i=z(e,this.maxBatchSize);if(i.length>1&&this.config.logger&&this.config.logger.debug(`Identity batch size ${e} is greater than ${this.maxBatchSize}, splitting into ${i.length} batches`),await this.trackActivityBatchRaw({data:i[0].map(a=>({id:{id:a||{},src:{...r}}}))}),i.length>1){let a=i.map((s,c)=>c===0?Promise.resolve():(this.config.logger?.verbose(`Processing identity batch ${c+1} of ${i.length}`),this.trackActivityBatchRaw({data:s.map(o=>({id:{id:o||{},src:{...r}}}))})));await Promise.all(a)}};trackActivityBatch=async(e,t)=>{this.checkPermission(A.activity.send,"trackActivityBatch");let n=U();if(e.length===0){this.config.logger?.debug("No activities in batch");return}let r={method:"",origin:t.origin,time:void 0,loc:t.loc,sess:n,diag:process.env.SEEKA_DEBUG_ENABLED==="true"?n:void 0,runtime:this.config.runtime},i=z(e,this.maxBatchSize);if(i.length>1&&this.config.logger&&this.config.logger.debug(`Activity batch size ${e.length} is greater than ${this.maxBatchSize}, splitting into ${i.length} batches`),await this.trackActivityBatchRaw({data:i[0].map(a=>({ev:{id:a.profile||{},src:{...r},payload:a.activity}}))}),i.length>1){let a=i.map((s,c)=>c===0?Promise.resolve():(this.config.logger?.verbose(`Processing activity batch ${c+1} of ${i.length}`),this.trackActivityBatchRaw({data:s.map(o=>({ev:{id:o.profile||{},src:{...r},payload:o.activity}}))})));await Promise.all(a)}};trackActivityBatchRaw=async e=>{await this.ingestionService.batch(e)};trackActivityForProfileId=async(e,t,n)=>{this.checkPermission(A.activity.send,"trackActivityForProfileId"),await this.trackActivityForProfileIdBatch([e],t,n)};trackActivityForProfileIdBatch=async(e,t,n)=>{this.checkPermission(A.activity.send,"trackActivityForProfileIdBatch"),await this.trackActivityBatch(e.map(r=>({activity:r,profile:t?{seekaPId:t}:void 0})),n)};trackActivityForProfile=async(e,t,n)=>{this.checkPermission(A.activity.send,"trackActivityForProfile"),await this.trackActivityForProfileBatch([e],t,n)};trackActivityForProfileBatch=async(e,t,n)=>{this.checkPermission(A.activity.send,"trackActivityForProfileBatch"),await this.trackActivityBatch(e.map(r=>({activity:r,profile:t})),n)}},Qt={measureAdvertisingPerformance:7},Xt=y(u("crypto")),Y="x-seeka-signature-sha256",Qe=(e,t,n)=>{if(!t)return!1;let r=null;if(t.get&&typeof t.get=="function")r=t.get(Y);else{let a=t[Y];a&&(Array.isArray(a)&&a.length>0?r=a[0]:(typeof a=="string"||a instanceof String)&&(r=a))}if(!r)return!1;let i=Zt(e,n)===r;return i||console.warn("Invalid webhook signature"),i},Zt=(e,t)=>Xt.createHmac("sha256",e).update(t).digest("hex"),er=(e,t,n)=>{if(!Qe(e,t,n))throw new Error("Invalid webhook signature")},x=y(u("crypto")),Xe="aes-192-cbc",Ze=(e,t)=>{if(!e)return"";if(!t)throw new Error("Secret is required to encrypt data");let n=x.default.scryptSync(t,"salt",24),r=x.default.randomBytes(16),i=x.default.createCipheriv(Xe,n,r);return[i.update(e,"utf8","hex")+i.final("hex"),Buffer.from(r).toString("hex")].join("|")},et=(e,t)=>{if(!e)return"";if(!t)throw new Error("Secret is required to decrypt data");let[n,r]=e.split("|");if(!r)throw new Error("IV not found");let i=x.default.scryptSync(t,"salt",24),a=x.default.createDecipheriv(Xe,i,Buffer.from(r,"hex"));return a.update(n,"hex","utf8")+a.final("utf8")},tr=class{constructor(e){this.appSecret=e}appSecret;encryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to encrypt data");return Ze(e,this.appSecret)};decryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to decrypt data");return et(e,this.appSecret)}},rr=class tt{constructor(t,n){this.context=t,this.api=new Ye(t.config),this.appCache=new E(t.config.appId),this.appInstallCache=new E(t.config.appId,t.config.applicationInstallId),this.crypto=new tr(t.config.appSecret),this.logger=n}context;appCache;appInstallCache;api;logger;crypto;static create=(t,n,r,i,a)=>new tt({config:jt({...n},t,{type:r.name,ver:r.version.split("-")[0]},i,a)},a)},nr=y(u("winston")),te=u("lodash-es"),m=e=>e==null||e===""||String(e).trim()===""?"":String(e);function rt(e){if(e==null||e==="")return 0;let t=e.toString().replace(/[^0-9.]/g,"");return Number.isNaN(Number(t))?0:Number(t)}function ir(e){if(e==null||e===0||e==="")return+"0.00";let t=rt(e);return Number(t.toFixed(3))}function ar(e){return e==null||e===""||Number.isNaN(Number(e.toString()))?0:Math.floor(Number(e))}function sr(e){return JSON.parse(JSON.stringify(e))}function or(e){return/^-?\d+$/.test(e)}function cr(e){if(!(e==null||e.length===0))return re(e)}function re(e){return re(e)}function lr(e,t){return(0,te.get)(e,t)}function pr(e,t,n){return(0,te.set)(e,t,n)}function dr(e,t){return(0,te.isEqual)(e,t)}function ur(e){return e?e.trim().toLowerCase():""}function gr(e){return e==null?"":(e=e.trim().replace(/-/gi,"").replace(/\(/gi,"").replace(/\)/gi,"").replace(/ /g,"").replace(/\+/g,""),e)}var fr=["order","subscriptionItemPurchase","oneTimeItemPurchase"],mr=(e,t,n)=>{if(!e.activity)return[];let r=e.activity,i=r.activityName==="custom"?r.activityNameCustom:r.activityName;if(!i)return[];let a=i.toLowerCase(),s=[];return t.forEach(c=>{if(!c)return;switch(c.type){case"activityTracked":{if(!c.activityNames||!c.activityNames.find(p=>p.toLowerCase()===a))return;n.verbose("Matched activity tracked filter",{filter:c,activityName:i});break}case"purchaseMade":{if(!r.activityName||!fr.includes(r.activityName))return;n.verbose("Matched purchase made activity filter",{filter:c,activityName:i});break}default:{n.warn("Unknown activity filter type",{filter:c});return}}let o=c.sourceFilter;if(!o)return;let l=e.source,d;try{d=l?.loc?new URL(l.loc).hostname.toLowerCase():null}catch(p){n.error("Failed to parse activity source URL",{ex:nr.default.exceptions.getAllInfo(p),activitySource:l}),d=null}let v=l?.pipeline?.convergePipelineIntegrationInstanceId?.toLowerCase(),g=o.filters?o.filters.map(p=>{switch(p.type){case"wildcard":return n.verbose("Matched wildcard source filter",{sourceFilter:p}),!0;case"domain":return!d||!p.key?!1:d===p.key.toLowerCase()?(n.verbose("Matched domain source filter",{sourceFilter:p,activityHostname:d}),!0):!1;case"pipeline":return!v||!p.key?!1:v===p.key.toLowerCase()?(n.verbose("Matched pipeline source filter",{sourceFilter:p,sourceConvergePipelineIntegrationInstanceId:v}),!0):!1}}):[];switch(o.comparer){case"and":{g.every(p=>p===!0)&&s.push(c);break}case"or":{g.some(p=>p===!0)&&s.push(c);break}default:{n.warn("Unknown source filter comparer",{sourceFilters:o});break}}}),s},hr=(e,t=!1)=>{let n=e.commerce,r=n?.totalPrice||n?.products?.map(a=>(a.unitPrice||0)*(a.quantity||1)).reduce((a,s)=>a+s,0)||void 0,i=n?.currencyCode||null;if((!r||r<=0)&&(r=e?.lead?.predictedLtv||e?.lead?.predictedValue,r&&e?.lead?.currencyCode&&(i=e?.lead?.currencyCode||null)),(!r||r<=0)&&(r=e?.contentItem?.value,r&&e?.contentItem?.currencyCode&&(i=e?.contentItem?.currencyCode||null)),(!r||r<=0)&&(e?.contentItem?.items&&e?.contentItem?.items.length>0&&(r=e?.contentItem?.items.map(a=>a&&a.unitPrice?a.unitPrice*(a.quantity||1):0).reduce((a,s)=>a+s,0)),r&&(i=e?.contentItem?.currencyCode||e?.commerce?.currencyCode||null,!i))){let a=e?.contentItem?.items?.filter(s=>s.currencyCode)||[];a.length>0&&(i=a[0].currencyCode||null)}if((!r||r<=0)&&e?.commerce?.products&&e?.commerce?.products.length>0&&(r=e?.commerce?.products.map(a=>a&&a.unitPrice?a.unitPrice*(a.quantity||1):0).reduce((a,s)=>a+s,0),r&&(i=e?.commerce?.currencyCode||null,!i))){let a=e?.commerce?.products?.filter(s=>s.currencyCode)||[];a.length>0&&(i=a[0].currencyCode||null)}return(!r||r<=0)&&!i?null:{value:r===0&&t?null:r||null,currencyCode:i}};function yr(e,t,n){if(!e)return;let r=t.processing?.contentIdentificationBehavior,i=null;(n=="googleAnalytics"||n=="googleAds")&&(t.analytics?.libraries?.googleAnalytics?.merchant?.productItemIdBehavior!=null&&(r=t.analytics?.libraries?.googleAnalytics?.merchant?.productItemIdBehavior),i=m(t.analytics?.libraries?.googleAnalytics?.merchant?.productItemIdPrefix));let a;switch(r){case"sku":a=e?.sku;break;case"productId":a=e?.productIdentifier;break;case"variantId":a=e?.variantIdentifier;break;case"productIdAndVariantIdUnderscore":m(e.variantIdentifier)&&m(e.productIdentifier)?a=`${e.productIdentifier}_${e.variantIdentifier}`:m(e.variantIdentifier)?a=e.variantIdentifier:a=e.productIdentifier;break;case"variantIdOrProductId":m(e.variantIdentifier)?a=e.variantIdentifier:a=e.productIdentifier;break;default:a=m(e?.sku)||m(e?.variantIdentifier)||m(e?.productIdentifier);break}return i?`${i}${a}`:a}function Ir(e,t){return m(e?.variantName)||m(e?.productName)}function vr(e){if(!e||e.trim().length===0)return!1;let t=e.split(".").filter(n=>n.trim().length>0);return!(t.length!==4||t[0].toLowerCase()!=="sk".toLowerCase()||t[1].toLowerCase()!=="1".toLowerCase()||isNaN(parseInt(t[2],10))||isNaN(parseInt(t[3],10)))}var kr={defaultIssuerUrl:ze,defaultTelemetryUrl:Wt,defaultIngestUrl:Ve}});var $=xt(it());import{createClient as Ar}from"redis";import*as D from"winston";var Sr=()=>{let e=process.env.REDIS_CONNECTION_TLS==="true"?"rediss://":"redis://";return process.env.REDIS_CONNECTION_USER&&process.env.REDIS_CONNECTION_PASSWORD?`${e}${process.env.REDIS_CONNECTION_USER}:${process.env.REDIS_CONNECTION_PASSWORD}@${process.env.REDIS_CONNECTION_HOST}:${process.env.REDIS_CONNECTION_PORT}`:`${e}${process.env.REDIS_CONNECTION_HOST}:${process.env.REDIS_CONNECTION_PORT}`},ne="__SEEKA_REDIS_CLIENT__",P=e=>{if(global[ne])return global[ne];let t=Ar({url:Sr(),disableClientInfo:!0}).on("error",n=>e.error("Redis Client ",{ex:D.exceptions.getAllInfo(n)}));return global[ne]=t,t},Pr=async e=>{await P(e).connect()},at=async e=>P(e).isOpen,wr=async e=>{P(e).destroy()},st=e=>`seeka:app:${process.env.SEEKA_APP_ID}:${e}`,F=(e,t)=>`${st(e)}:${t}`,O=e=>e==="install",ot=()=>{let e=process.env.DATA_ENCRYPTION_KEY;if(!e)throw new Error("DATA_ENCRYPTION_KEY is required to encrypt/decrypt installation state");return e},ct=e=>{if(!e)return!1;let t=e.split("|");if(t.length!==2)return!1;let[n,r]=t;return!n||!r?!1:/^[0-9a-f]+$/i.test(n)&&/^[0-9a-f]{32}$/i.test(r)},ie=e=>{if(!ct(e))return{plainText:e,wasEncrypted:!1};let t=ot();return{plainText:(0,$.decryptText)(e,t),wasEncrypted:!0}},_=e=>{if(ct(e))return{encryptedText:e,wasEncrypted:!0};let t=ot();return{encryptedText:(0,$.encryptText)(e,t),wasEncrypted:!1}};async function Kr(e,t,n,r="string",i){let a=F(e,t),s=P(i),c=await gt(s,a);if(c){if(r==="string"&&O(e)){let{plainText:o,wasEncrypted:l}=ie(c);if(!l){let{encryptedText:d}=_(c);await s.set(a,d)}return JSON.parse(o)}return JSON.parse(c)}if(r==="json")await s.json.set(a,"$",n);else{let o=JSON.stringify(n);if(O(e)){let{encryptedText:l}=_(o);await s.set(a,l)}else await s.set(a,o)}return n}async function lt(e,t,n="string",r){let i=F(e,t),a=P(r);if(n==="json"){let s=await a.json.get(i);if(s)return s}else{let s=await gt(a,i);if(s){if(O(e)){let{plainText:c,wasEncrypted:o}=ie(s);if(!o){let{encryptedText:l}=_(s);await a.set(i,l)}return JSON.parse(c)}return JSON.parse(s)}}return null}async function pt(e,t){let n=st(e),r=P(t),i=await r.keys(`${n}:*`),a=await r.mGet(i);if(a){let s=[];for(let c=0;c<a.length;c++){let o=a[c],l=i[c];if(!o)continue;let d=o;if(O(e)){let{plainText:v,wasEncrypted:g}=ie(d);if(!g){let{encryptedText:p}=_(d);await r.set(l,p)}s.push(JSON.parse(v))}else s.push(JSON.parse(d))}return s}return[]}async function dt(e,t,n,r="string",i){let a=F(e,t),s=P(i);if(r==="json")await s.json.set(a,"$",n);else{let c=JSON.stringify(n);if(O(e)){let{encryptedText:o}=_(c);await s.set(a,o)}else await s.set(a,c)}}async function ut(e,t,n){let r=F(e,t);await P(n).del(r)}async function gt(e,t){let n=await e.get(t);return typeof n=="string"?n:n?n.toString():""}var ft=async e=>{e.debug(`Trying to connect to Redis - ${process.env.REDIS_CONNECTION_HOST}`);try{await at(e)?e.verbose(`Redis already connected - ${process.env.REDIS_CONNECTION_HOST}`):(e.profile("service.redis.connect"),await Pr(e),e.profile("service.redis.connect"),e.debug(`Redis connected - ${process.env.REDIS_CONNECTION_HOST}`))}catch(t){throw e.error(`Failed to connect to Redis - ${process.env.REDIS_CONNECTION_HOST}`,{ex:D.exceptions.getAllInfo(t)}),t}},Jr=async e=>{e.debug(`Trying to disconnect from Redis - ${process.env.REDIS_CONNECTION_HOST}`);try{await at(e)===!1?e.verbose(`Redis already disconnected - ${process.env.REDIS_CONNECTION_HOST}`):(e.profile("service.redis.disconnect"),await wr(e),e.profile("service.redis.disconnect"),e.verbose(`Redis disconnected - ${process.env.REDIS_CONNECTION_HOST}`))}catch(t){throw e.error(`Failed to disconnect from Redis - ${process.env.REDIS_CONNECTION_HOST}`,{ex:D.exceptions.getAllInfo(t)}),t}};var q="install",ae=async(e,t,n)=>{let r=await lt(q,e,"string",n);if(r==null&&t)throw n.error(`Seeka installation ${e} not found`),new Error(`Seeka installation ${e} not found`);return r},Yr=async e=>await pt(q,e),Qr=async(e,t)=>{e.installationState||(e.installationState={}),e.installedAt||(e.installedAt=new Date().toISOString());let n=await ae(e.applicationInstallId,!1,t)===null;return await dt(q,e.applicationInstallId,e,"string",t),t.info(n?"Created installation state":"Updated installation state",{applicationInstallId:e.applicationInstallId,organisationId:e.organisationId,organisationBrandId:e.organisationBrandId}),e},Xr=async(e,t)=>{await ut(q,e,t),t.info("Deleted installation state",{applicationInstallId:e})};var M=e=>"seeka_app_"+e+"_at_app",W=e=>"seeka_app_"+e+"_at_core",se="X-Seeka-App-Token",oe="X-Seeka-CoreApi-Token",j="at_app",H="at_core";import Cr from"jsonwebtoken";var mt=async(e,t,n,r)=>{let i=new URL(e),a=t.get("Cookie"),s=i.searchParams.get(j)||"";if(!s&&t.get(se)&&(s=t.get(se)?.split("Bearer ")[1]),!s&&a){let o=a.split(";").find(l=>l.trim().startsWith(M(process.env.SEEKA_APP_ID)));o&&(s=o.split("=")[1])}let c=i.searchParams.get(H)||"";if(!c&&t.get(oe)&&(c=t.get(oe)?.split("Bearer ")[1]),!c&&a){let o=a.split(";").find(l=>l.trim().startsWith(W(process.env.SEEKA_APP_ID)));o&&(c=o.split("=")[1])}return await Tr(s,c,n,r)},Tr=async(e,t,n,r)=>{let i,a,s;if(e)try{let o=Cr.verify(e,process.env.SEEKA_APP_SECRET,{ignoreNotBefore:!0});if(r.info("Decoded token",{decoded:o}),!o.appId||o.appId.replace(/-/g,"")!==process.env.SEEKA_APP_ID.replace(/-/g,"")){r.error("Invalid token - app id does not match",{decoded:o,appIdToken:o.appId,appIdEnv:process.env.SEEKA_APP_ID});return}else i=o.appId;if(o.appInstallId)a=o.appInstallId;else{r.error("Invalid token - no appInstallId",{decoded:o});return}s=o.exp}catch(o){r.error("Failed to validate token",{err:o});return}else{r.error("No access token present");return}n&&await n(r);let c=await ae(a,!1,r);if(c==null){r.warn("UI call cannot be processed as the installation ID is not known by this app",{seekaAppInstallId:a});return}return{appAccessToken:e,coreApiAccessToken:t,seekaAppId:i,seekaAppInstallId:a,expiresAt:s,installation:c}};import*as G from"fs/promises";import R from"path";import{OpenTelemetryTransportV3 as Nr}from"@opentelemetry/winston-transport";import*as I from"winston";var ht=[new I.transports.Console({level:process.env.LOGGING_LEVEL,format:I.format.combine(I.format.errors({stack:!0}),I.format.cli(),I.format.splat()),handleExceptions:!0,handleRejections:!0})];process.env.OTEL_SDK_DISABLED!=="true"&&ht.push(new Nr({handleExceptions:!0,handleRejections:!0}));var xr=I.createLogger({level:process.env.LOGGING_LEVEL,transports:ht,exitOnError:!1}),T=(e,t,n=xr,r={})=>n.child({...e,...t?{seekaAppInstallId:t.applicationInstallId,seekaAppInstallOrganisationBrandId:t.organisationBrandId,seekaAppInstallOrganisationId:t.organisationId,...r?.invocationId?{"faas.invocation_id":r.invocationId}:{}}:{}}),on=(e,t)=>{let n={seekaWebhookType:e.type,seekaWebhookIsTest:e.isTest,RequestId:e.requestId,"faas.invocation_id":t.invocationId,CausationId:e.causationId,CorrelationId:e.causationId},r=e.context;return r&&(n.seekaAppInstallId=r.applicationInstallId,n.seekaAppInstallOrganisationBrandId=r.organisationBrandId,n.seekaAppInstallOrganisationId=r.organisationId),T(n)},cn=(e,t,n)=>{let r={jobContext:t,jobName:e,"faas.invocation_id":n.invocationId,CausationId:t?.causationId,CorrelationId:t?.causationId,seekaAppInstallId:t?.applicationInstallId??t?.payload.applicationInstallId,seekaAppInstallOrganisationBrandId:t?.organisationBrandId,seekaAppInstallOrganisationId:t?.organisationId};return T(r)};async function yt(e,t){return await G.readFile(e,{encoding:t})}var ce="config.js",hn=async(e,t,n,r,i,a)=>{let s=T(null,void 0,void 0,r);s.profile("http.seeka.webhook.app.ui");let o=new URL(e).pathname?.replace(/^\/app/,"")||"/";s.verbose("Received Seeka UI request",{requestedPath:o,url:e,method:t});let l=R.resolve("./dist/src/ui/build"),d=null,v=null,g,p={},K=[],f,J=async()=>o==="/health"?null:(f=await mt(e,n,()=>ft(s),s),f?(d=f.seekaAppId,v=f.seekaAppInstallId,g=f.installation,s=T(null,g,s,r),s.verbose("Authenticated Seeka UI request",{requestedPath:o,url:e,method:t}),s=T(null,g,s,r),K.push({name:M(process.env.SEEKA_APP_ID),value:f.appAccessToken,httpOnly:!0,secure:!0,sameSite:"None",expires:new Date(f.expiresAt*1e3)}),K.push({name:W(process.env.SEEKA_APP_ID),value:f.coreApiAccessToken,httpOnly:!0,secure:!0,sameSite:"None",expires:new Date(f.expiresAt*1e3)}),null):{status:403,jsonBody:{error:"Invalid token"}}),k=R.join(l,o),w;try{if(o==="/health")return{status:200,jsonBody:{status:"ok"}};if(o==="/"+ce){let h=await J();if(h)return h;let C=process.env.APP_UI_BASE_PATH?`${process.env.APP_UI_BASE_PATH}`:"",N=`${process.env.SELF_HOST_BASEURL}${C}`,kt={seekaAppId:d||"",seekaAppInstallId:v||"",organisationBrandId:g?.organisationBrandId||"",appBaseUrl:N,state:await i(g,s)};w=`window.seekaAppConfig = ${JSON.stringify(kt)}`}if(o.startsWith("/api")){let h=await J();if(h)return h;let C=await a(o,t,g,s);return C||{status:404,jsonBody:{error:"Not found"}}}if(o==="/"||o==="/index.html"){let h=await J();if(h)return h;let C=`?${j}=${encodeURIComponent(f?.appAccessToken||"")}&${H}=${encodeURIComponent(f?.coreApiAccessToken||"")}&`;k=R.join(l,"index.html");let N=await yt(k,"utf-8");N=N.replace(ce+"?",ce+C),w=N}else w||(k=R.join(l,o),await G.access(k))}catch(h){k=R.join(l,"index.html"),console.log("File not found, serving index.html",{err:h,requestedPath:o,buildPath:l,filePath:k,content:w})}return w||(w=await yt(k)),{status:200,headers:{"Content-Type":br(k),"Referrer-Policy":"no-referrer",...p},cookies:K,body:w}};function br(e){return e.endsWith(".html")?"text/html":e.endsWith(".js")?"application/javascript":e.endsWith(".css")?"text/css":e.endsWith(".png")?"image/png":e.endsWith(".jpg")||e.endsWith(".jpeg")?"image/jpeg":e.endsWith(".gif")?"image/gif":"application/octet-stream"}import vt from"fs/promises";import It from"path";import Er from"winston";var Or=async e=>vt.stat(e).then(()=>!0).catch(()=>!1);async function Sn(e,t,n,r){let a=It.resolve(It.join(t,"seeka-browser-plugin.min.js"));return await _r(e,a,n,r)}async function _r(e,t,n,r){r.profile("http.seeka.browser.plugin");let i,a;try{r.verbose("Handling request for browser plugin content",{path:t}),await Or(t)?(r.verbose("Browser plugin content found",{path:t}),i=await vt.readFile(t,"utf8"),a=`${e}(${JSON.stringify(n)})`):r.error("Browser plugin content not found",{path:t})}catch(s){r.error("Failed to handle request for browser plugin content",{ex:Er.exceptions.getAllInfo(s)})}finally{r.profile("http.seeka.browser.plugin"),r.verbose("Request for browser plugin content handled")}if(!i||!a)throw new Error("Failed to handle request for browser plugin content");return{content:i,init:a}}export{xr as appLogger,cn as backgroundJobLogger,Tr as checkAuth,T as childLogger,Pr as connect,Qr as createOrUpdateInstallation,Xr as deleteInstallation,wr as disconnect,hn as generateAppUiHttpRequestResponse,mt as getAccessTokenAndCheck,F as getKey,pt as getList,Kr as getOrCreate,P as getOrCreateClient,Sn as getSeekaBrowserPlugin,_r as getSeekaBrowserPluginByName,at as isConnected,Yr as listInstallations,ut as remove,dt as set,ft as startServices,Jr as stopServices,lt as tryGet,ae as tryGetInstallation,on as webhookLogger};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seeka-labs/sdk-apps-server-host",
3
- "version": "3.7.0",
3
+ "version": "3.8.1",
4
4
  "description": "Seeka - Apps SDK - Node.js - hosting layer",
5
5
  "author": "SEEKA <platform@seeka.co>",
6
6
  "license": "MIT",
@@ -32,8 +32,8 @@
32
32
  "@jest/globals": "^30",
33
33
  "@redis/client": "^5",
34
34
  "@redis/json": "^5",
35
- "@seeka-labs/sdk-apps-core": "^3.7.0",
36
- "@seeka-labs/sdk-apps-server": "^3.7.0",
35
+ "@seeka-labs/sdk-apps-core": "^3.8.1",
36
+ "@seeka-labs/sdk-apps-server": "^3.8.1",
37
37
  "@types/jest": "^30",
38
38
  "@types/memory-cache": "^0",
39
39
  "@types/node": "^22",
@@ -62,5 +62,6 @@
62
62
  "redis": "^5",
63
63
  "undici": "^7",
64
64
  "winston": "^3"
65
- }
65
+ },
66
+ "gitHead": "d73cbf556675ad874197d84d149ba15c8d5cc80d"
66
67
  }