@analytics/aws-pinpoint
Advanced tools
Comparing version 0.2.0 to 0.2.1
@@ -6,2 +6,10 @@ # Change Log | ||
## [0.2.1](https://github.com/DavidWells/analytics/compare/@analytics/aws-pinpoint@0.2.0...@analytics/aws-pinpoint@0.2.1) (2021-01-28) | ||
**Note:** Version bump only for package @analytics/aws-pinpoint | ||
# [0.2.0](https://github.com/DavidWells/analytics/compare/@analytics/aws-pinpoint@0.1.0...@analytics/aws-pinpoint@0.2.0) (2021-01-28) | ||
@@ -8,0 +16,0 @@ |
@@ -1,1 +0,1 @@ | ||
var analyticsAWSPinpoint=function(){"use strict";function e(e,t,n,r,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,s)}function t(t){return function(){var n=this,r=arguments;return new Promise(function(s,i){var o=t.apply(n,r);function a(t){e(o,s,i,a,c,"next",t)}function c(t){e(o,s,i,a,c,"throw",t)}a(void 0)})}}function n(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function s(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?r(s,!0).forEach(function(t){n(e,t,s[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):r(s).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))})}return e}var i=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===o}(e)}(e)};var o="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function a(e,t){return!1!==t.clone&&t.isMergeableObject(e)?p((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function c(e,t,n){return e.concat(t).map(function(e){return a(e,n)})}function u(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return e.propertyIsEnumerable(t)}):[]}(e))}function d(e,t){try{return t in e}catch(e){return!1}}function l(e,t,n){var r={};return n.isMergeableObject(e)&&u(e).forEach(function(t){r[t]=a(e[t],n)}),u(t).forEach(function(s){(function(e,t){return d(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,s)||(d(e,s)&&n.isMergeableObject(t[s])?r[s]=function(e,t){if(!t.customMerge)return p;var n=t.customMerge(e);return"function"==typeof n?n:p}(s,n)(e[s],t[s],n):r[s]=a(t[s],n))}),r}function p(e,t,n){(n=n||{}).arrayMerge=n.arrayMerge||c,n.isMergeableObject=n.isMergeableObject||i,n.cloneUnlessOtherwiseSpecified=a;var r=Array.isArray(t);return r===Array.isArray(e)?r?n.arrayMerge(e,t,n):l(e,t,n):a(t,n)}p.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,n){return p(e,n,t)},{})};var h=p;function f(e,t,n,r,s,i){if("undefined"!=typeof window)return arguments.length>1?document.cookie=e+"="+encodeURIComponent(t)+(n?"; expires="+new Date(+new Date+1e3*n).toUTCString()+(r?"; path="+r:"")+(s?"; domain="+s:"")+(i?"; secure":""):""):decodeURIComponent((("; "+document.cookie).split("; "+e+"=")[1]||"").split(";")[0])}function g(e){return(g="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}"object"===("undefined"==typeof self?"undefined":g(self))&&self.self===self&&self||"object"===("undefined"==typeof global?"undefined":g(global))&&global.global===global&&global,function(){try{f("_c_","1");var e=-1!==document.cookie.indexOf("_c_");f("_c_","",-1)}catch(e){return!1}}();function m(){for(var e="",t=0,n=4294967295*Math.random()|0;t++<36;){var r="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"[t-1],s=15&n;e+="-"==r||"4"==r?r:("x"==r?s:3&s|8).toString(16),n=t%8==0?4294967295*Math.random()|0:n>>4}return e}const y=new TextEncoder,b={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},v=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"];class w{constructor({accessKeyId:e,secretAccessKey:t,sessionToken:n,service:r,region:s,cache:i,retries:o,initRetryMs:a}){if(null==e)throw new TypeError("accessKeyId is a required option");if(null==t)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=n,this.service=r,this.region=s,this.cache=i||new Map,this.retries=null!=o?o:10,this.initRetryMs=a||50}async sign(e,t){if(e instanceof Request){const{method:n,url:r,headers:s,body:i}=e;null==(t=Object.assign({method:n,url:r,headers:s},t)).body&&s.has("Content-Type")&&(t.body=null!=i&&s.has("X-Amz-Content-Sha256")?i:await e.clone().arrayBuffer()),e=r}const n=new S(Object.assign({url:e},t,this,t&&t.aws)),r=Object.assign({},t,await n.sign());return delete r.aws,new Request(r.url.toString(),r)}async fetch(e,t){for(let n=0;n<=this.retries;n++){const r=fetch(await this.sign(e,t));if(n===this.retries)return r;const s=await r;if(s.status<500&&429!==s.status)return s;await new Promise(e=>setTimeout(e,Math.random()*this.initRetryMs*Math.pow(2,n)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class S{constructor({method:e,url:t,headers:n,body:r,accessKeyId:s,secretAccessKey:i,sessionToken:o,service:a,region:c,cache:u,datetime:d,signQuery:l,appendSessionToken:p,allHeaders:h,singleEncode:f}){if(null==t)throw new TypeError("url is a required option");if(null==s)throw new TypeError("accessKeyId is a required option");if(null==i)throw new TypeError("secretAccessKey is a required option");let g,m;this.method=e||(r?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(n||{}),this.body=r,this.accessKeyId=s,this.secretAccessKey=i,this.sessionToken=o,a&&c||([g,m]=function(e,t){const{hostname:n,pathname:r}=e,s=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/);let[i,o]=(s||["",""]).slice(1,3);if("us-gov"===o)o="us-gov-west-1";else if("s3"===o||"s3-accelerate"===o)o="us-east-1",i="s3";else if("iot"===i)i=n.startsWith("iot.")?"execute-api":n.startsWith("data.jobs.iot.")?"iot-jobs-data":"/mqtt"===r?"iotdevicegateway":"iotdata";else if("autoscaling"===i){const e=(t.get("X-Amz-Target")||"").split(".")[0];"AnyScaleFrontendService"===e?i="application-autoscaling":"AnyScaleScalingPlannerFrontendService"===e&&(i="autoscaling-plans")}else null==o&&i.startsWith("s3-")?(o=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):o&&/-\d$/.test(i)&&!/-\d$/.test(o)&&([i,o]=[o,i]);return[b[i]||i,o]}(this.url,this.headers)),this.service=a||g||"",this.region=c||m||"us-east-1",this.cache=u||new Map,this.datetime=d||(new Date).toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=l,this.appendSessionToken=p||"iotdevicegateway"===this.service,this.headers.delete("Host");const y=this.signQuery?this.url.searchParams:this.headers;if("s3"!==this.service||this.headers.has("X-Amz-Content-Sha256")||this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),y.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&y.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(e=>h||!v.includes(e)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(e=>e+":"+("host"===e?this.url.host:(this.headers.get(e)||"").replace(/\s+/g," "))).join("\n"),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&("s3"!==this.service||y.has("X-Amz-Expires")||y.set("X-Amz-Expires","86400"),y.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),y.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),y.set("X-Amz-SignedHeaders",this.signedHeaders)),"s3"===this.service)try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(e){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");f||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=O(this.encodedPath);const w=new Set;this.encodedSearch=[...this.url.searchParams].filter(([e])=>{if(!e)return!1;if("s3"===this.service){if(w.has(e))return!1;w.add(e)}return!0}).map(e=>e.map(e=>O(encodeURIComponent(e)))).sort(([e,t],[n,r])=>e<n?-1:e>n?1:t<r?-1:t>r?1:0).map(e=>e.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){const e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join();let n=this.cache.get(t);if(!n){const r=await A("AWS4"+this.secretAccessKey,e),s=await A(r,this.region),i=await A(s,this.service);n=await A(i,"aws4_request"),this.cache.set(t,n)}return E(await A(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,E(await x(await this.canonicalString()))].join("\n")}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+"\n",this.signedHeaders,await this.hexBodyHash()].join("\n")}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(null==e){if(this.body&&"string"!=typeof this.body&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=E(await x(this.body||""))}return e}}async function A(e,t){const n=await crypto.subtle.importKey("raw","string"==typeof e?y.encode(e):e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,y.encode(t))}async function x(e){return crypto.subtle.digest("SHA-256","string"==typeof e?y.encode(e):e)}function E(e){return Array.prototype.map.call(new Uint8Array(e),e=>("0"+e.toString(16)).slice(-2)).join("")}function O(e){return e.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}var k={SESSION_START:"_session.start",SESSION_STOP:"_session.stop",SESSION_PAUSE:"_session.pause",SESSION_RESUME:"_session.resume",AUTH_SIGN_IN:"_userauth.sign_in",AUTH_SIGN_UP:"_userauth.sign_up",AUTH_FAIL:"_userauth.auth_fail",ECOM_PURCHASE:"_monetization.purchase",PAGE_VIEW:"pageView"},I=["PUSH","GCM","APNS","APNS_SANDBOX","APNS_VOIP","APNS_VOIP_SANDBOX","ADM","SMS","VOICE","EMAIL","BAIDU","CUSTOM"].reduce(function(e,t){return e[t]=t,e},{});"undefined"!=typeof navigator&&navigator&&navigator.sendBeacon;var T="__session_id",P="__endpoint",M=[429,500],j=[202],C=400,_=function(){if("undefined"==typeof window)return{};if(!window.navigator)return{};var e,t,n,r,s,i=window.navigator,o=i.platform,a=i.product,c=i.vendor,u=function(e){var t=/.+(Opera[\s[A-Z]*|OPR[\sA-Z]*)\/([0-9\.]+).*/i.exec(e);if(t)return{type:t[1],version:t[2]};var n=/.+(Trident|Edge)\/([0-9\.]+).*/i.exec(e);if(n)return{type:n[1],version:n[2]};var r=/.+(Chrome|Firefox|FxiOS)\/([0-9\.]+).*/i.exec(e);if(r)return{type:r[1],version:r[2]};var s=/.+(Safari)\/([0-9\.]+).*/i.exec(e);if(s)return{type:s[1],version:s[2]};var i=/.+(AppleWebKit)\/([0-9\.]+).*/i.exec(e);if(i)return{type:i[1],version:i[2]};var o=/.*([A-Z]+)\/([0-9\.]+).*/i.exec(e);return o?{type:o[1],version:o[2]}:{type:"",version:""}}(i.userAgent);return{platform:o,make:a||c,model:u.type,version:u.version,appVersion:[u.type,u.version].join("/"),language:(t=window.navigator,n=t.language,r=t.browserLanguage,s=t.languages,(n||r||(s||["en_US"])[0]).toLowerCase().replace("-","_")),timezone:(e=/\(([A-Za-z\s].*)\)/.exec((new Date).toString()),e&&e[1]||"")}}(),R=[];function H(){return{}}var D=/.+\@.+\..+/;function U(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=s({getContext:e.getContext||H,enrichEventAttributes:e.enrichEventAttributes||H,enrichEventMetrics:e.enrichEventMetrics||H,credentials:e.credentials||{},getEndpointId:e.getEndpointId},e),i=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.getEndpointId,i=e.debug;return function(){var o=t(regeneratorRuntime.mark(function t(){var o,a,c,u,d,l,p,h,f=arguments;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(o=f.length>0&&void 0!==f[0]?f[0]:{},R.length||Object.keys(o).length){t.next=4;break}return i&&console.log("No events, return early"),t.abrupt("return");case 4:return a=o,t.next=7,r();case 7:if(c=t.sent,i&&console.log("resolved endpointId",c),c){t.next=12;break}return console.error("No User ID found. Call Auth()"),t.abrupt("return");case 12:if(!Object.entries(o).length){t.next=19;break}return u=e.getContext(),t.next=16,q(o,u);case 16:a=t.sent,t.next=20;break;case 19:a=K()||{};case 20:return i&&console.log("endpointData",a),d=a.ChannelType,a.Address&&(g=a.Address,D.test(g))&&(d=I.EMAIL),!d&&a.Address&&(d="android"===_.platform?d||I.GCM:d||I.APNS),i&&console.log("CHANNEL_TYPE",d),l=R.reduce(function(e,t){return s({},t,{},e)},{}),(p=a).RequestId=m(),p.ChannelType=d,p.Address&&(p.OptOut=a.OptOut||"NONE"),h={BatchItem:n({},c,{Endpoint:p,Events:l})},t.prev=31,t.next=34,V(h,e);case 34:t.sent,t.next=40;break;case 37:t.prev=37,t.t0=t.catch(31),console.log("callPinPoint err",t.t0);case 40:return R=[],t.abrupt("return",a);case 42:case"end":return t.stop()}var g},t,null,[[31,37]])}));return function(){return o.apply(this,arguments)}}()}(r),o=function(){var e,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=r.sentDataToPinpoint,o=r.appPackageName,a=r.appTitle,c=r.appVersionCode,u=r.debug;return function(){var d=t(regeneratorRuntime.mark(function t(d){var l,p,h,f,g,y,b,v,w,S,A,x,E,O,I,T,P,M,j,C,_,H,D=arguments;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(l=D.length>1&&void 0!==D[1]?D[1]:{},p=D.length>2&&void 0!==D[2]?D[2]:{},h=!(D.length>3&&void 0!==D[3])||D[3],"boolean"==typeof l&&(h=l,l={}),"boolean"==typeof p&&(h=p,p={}),f=r.getContext(),g=f.pageSession,y=f.subSessionId,b=f.subSessionStart,v=f.elapsed,!Object.entries(p).length){t.next=11;break}return t.next=10,q(p,f);case 10:p=t.sent;case 11:return w=new Date,S=l.attributes||{},A={date:w.toISOString(),session:N(),pageSession:g,hash:window.location.hash,path:window.location.pathname,referrer:document.referrer,search:window.location.search,title:document.title,host:window.location.hostname,url:window.location.origin+window.location.pathname},t.next=16,r.enrichEventAttributes();case 16:return x=t.sent,E=s({},A,{},x,{},S),O=v+(w.getTime()-b),I=l.metrics||{},T={sessionTime:O,hour:w.getHours(),day:w.getDay()+1,month:w.getMonth()+1,year:w.getFullYear()},t.next=23,r.enrichEventMetrics();case 23:return P=t.sent,M=s({},T,{},P,{},I),t.next=27,Z(E);case 27:return t.t0=t.sent,t.next=30,Y(M);case 30:t.t1=t.sent,j={attributes:t.t0,metrics:t.t1},C=m(),_=(new Date).toISOString(),u&&(console.log("".concat(C,":").concat(d)),console.log("eventAttributes",j.attributes),console.log("eventMetrics",j.metrics)),H=n({},C,{EventType:d,Timestamp:_,AppPackageName:o,AppTitle:a,AppVersionCode:c,Attributes:j.attributes,Metrics:j.metrics,Session:{Id:y,StartTimestamp:new Date(b).toISOString()}}),d===k.SESSION_STOP&&(H[C].Session.Duration=Date.now()-b,H[C].Session.StopTimestamp=_),R.push(H),t.next=40;break;case 40:if(h){t.next=42;break}return t.abrupt("return",i());case 42:e&&clearTimeout(e),e=setTimeout(i,5e3);case 44:case"end":return t.stop()}},t)}));return function(e){return d.apply(this,arguments)}}()}(s({sentDataToPinpoint:i},r));q({},r.getContext());var a=function(e){if("undefined"==typeof window)return H;var t=function(e){return function(){console.log("Fire stop session"),e("_session.stop",!1)}}(e);return window.addEventListener("beforeunload",t),function(){return window.removeEventListener("beforeunload",t)}}(o);return{updateEndpoint:i,recordEvent:o,disable:function(){a()}}}function N(){if(void 0===window.sessionStorage)return null;var e=window.sessionStorage.getItem(T);if(e)return e;var t=m();return window.sessionStorage.setItem(T,t),t}function K(){try{return JSON.parse(localStorage.getItem(P))||{}}catch(e){return{}}}function z(e){localStorage.setItem(P,JSON.stringify(e))}function V(e,t){return X.apply(this,arguments)}function X(){return(X=t(regeneratorRuntime.mark(function e(t,n){var r,s,i,o,a,c,u,d,l,p,h,f,g,m;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=n.pinpointRegion,n.pinpointEndpoint,s=n.pinpointAppId,i=n.lambdaArn,o=n.lambdaRegion,a=n.credentials,c=n.getCredentials,u=n.debug,d=a,Object.keys(d).length||!c){e.next=12;break}return e.prev=3,e.next=6,c();case 6:d=e.sent,e.next=12;break;case 9:throw e.prev=9,e.t0=e.catch(3),new Error(e.t0);case 12:return l=new w({accessKeyId:d.accessKeyId||d.AccessKeyId,secretAccessKey:d.secretAccessKey||d.SecretKey,sessionToken:d.sessionToken||d.SessionToken}),p=r||o,h="https://lambda.".concat(o||r,".amazonaws.com/2015-03-31/functions/").concat(i,"/invocations"),f="https://pinpoint.".concat(p,".amazonaws.com/v1/apps/").concat(s,"/events"),g=i?h:f,e.next=20,l.fetch(g,{body:JSON.stringify(t)}).then(function(e){return e.json()});case 20:return(m=e.sent)&&m.Results&&Object.keys(m.Results).map(function(e){return m.Results[e]}).forEach(function(e){var t=e.EndpointItemResponse||{},n=e.EventsItemResponse||{};Object.keys(t).length&&(u&&console.log("EndpointItemResponse",t),j.includes(t.StatusCode)||M.includes(t.StatusCode)||L(t,Endpoint));var r=Object.keys(n);r.length&&(u&&console.log("EventsResponse",n),r.forEach(function(e){}))}),e.abrupt("return",m);case 23:case"end":return e.stop()}},e,null,[[3,9]])}))).apply(this,arguments)}function L(e,t){var n=e.StatusCode,r=e.Message;if(n===C){if(r.startsWith("Missing ChannelType"))throw new Error("Missing ChannelType");if(r.startsWith("Exceeded maximum endpoint per user count"))throw new Error("Exceeded maximum endpoint per user count")}}function q(){return W.apply(this,arguments)}function W(){return(W=t(regeneratorRuntime.mark(function e(){var t,n,r,i,o,a,c,u,d,l=arguments;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t=l.length>0&&void 0!==l[0]?l[0]:{},n=l.length>1&&void 0!==l[1]?l[1]:{},r=K(),i=n.pageSession,o={},a={AppVersion:_.appVersion,Make:_.make,Model:_.model,ModelVersion:_.version,Platform:_.platform,Locale:_.language},c={Attributes:{},Demographic:s({AppVersion:_.appVersion||""},a,{},o.demographic),Location:{},Metrics:{}},_.device&&_.device.vendor&&(c.Attributes.DeviceMake=[_.device.vendor]),_.device&&_.device.model&&(c.Attributes.DeviceModel=[_.device.model]),_.device&&_.device.type&&(c.Attributes.DeviceType=[_.device.type]),_.engine&&_.engine.name&&(c.Demographic.Make=_.engine.name),_.browser&&_.browser.name&&(c.Demographic.Model=_.browser.name),_.browser&&_.browser.version&&(c.Demographic.ModelVersion=_.browser.version),_.os&&_.os.name&&(c.Demographic.Platform=_.os.name),_.os&&_.os.version&&(c.Demographic.PlatformVersion=_.os.version),!(t=h.all([c,r,t],{arrayMerge:B})).User||!t.User.UserAttributes){e.next=20;break}return e.next=19,Z(t.User.UserAttributes,!0);case 19:t.User.UserAttributes=e.sent;case 20:return e.next=22,Z(t.Attributes,!0);case 22:return t.Attributes=e.sent,e.next=25,Y(t.Metrics);case 25:return t.Metrics=e.sent,u="sessions",n.sessionKey&&(u=n.sessionKey()),d="pageViews",n.pageViewKey&&(d=n.pageViewKey()),t.Attributes.lastSession?(t.Attributes.lastSession[0]!==N()&&(t.Attributes.lastSession=[N()],t.Metrics[u]+=1),t.Attributes.lastPageSession[0]!==i&&(t.Attributes.lastPageSession=[i],t.Metrics[d]+=1)):(t.Attributes.lastSession=[N()],t.Attributes.lastPageSession=[i],t.Metrics[u]=1,t.Metrics[d]=1),z(t),e.abrupt("return",t);case 33:case"end":return e.stop()}},e)}))).apply(this,arguments)}function B(e,t){return t}function F(e,t){return G.apply(this,arguments)}function G(){return(G=t(regeneratorRuntime.mark(function e(t,n){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("function"!=typeof t){e.next=4;break}return e.next=3,t();case 3:t=e.sent;case 4:return e.abrupt("return",n(t));case 5:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Q(e){return Array.isArray(e)?e.map(function(e){return e.toString()}):e.toString()}function $(e){return parseFloat(Number(Array.isArray(e)?e[0]:e))}function Z(e){return J.apply(this,arguments)}function J(){return(J=t(regeneratorRuntime.mark(function e(t){var n,r,s,i,o=arguments;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n=o.length>1&&void 0!==o[1]&&o[1],r={},e.t0=regeneratorRuntime.keys(t);case 3:if((e.t1=e.t0()).done){e.next=17;break}if(s=e.t1.value,i=Array.isArray(t[s])?t[s]:[t[s]],!n){e.next=12;break}return e.next=9,F(i,Q);case 9:r[s]=e.sent,e.next=15;break;case 12:return e.next=14,F(i[0],Q);case 14:r[s]=e.sent;case 15:e.next=3;break;case 17:return e.abrupt("return",r);case 18:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Y(e){return ee.apply(this,arguments)}function ee(){return(ee=t(regeneratorRuntime.mark(function e(t){var n,r;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n={},e.t0=regeneratorRuntime.keys(t);case 2:if((e.t1=e.t0()).done){e.next=9;break}return r=e.t1.value,e.next=6,F(t[r],$);case 6:n[r]=e.sent,e.next=2;break;case 9:return e.abrupt("return",n);case 10:case"end":return e.stop()}},e)}))).apply(this,arguments)}function te(e){if("undefined"==typeof window)return!1;var t="hidden"in document?"hidden":["webkit","moz","ms","o"].reduce(function(e,t){return!e&&"".concat(t,"Hidden")in document?"".concat(t,"Hidden"):e},null);if(!t)return!1;var n="".concat(t.replace(/[H|h]idden/,""),"visibilitychange"),r=function(){return document[t]?e(!0):e(!1)};return document.addEventListener(n,r),function(){return document.removeEventListener(n,r)}}var ne={disableAnonymousTraffic:!1,pinpointRegion:"us-east-1"};return function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=m(),i=0,o=m(),a=Date.now();return{name:"aws-pinpoint",config:s({},ne,{},n),bootstrap:function(e){var t=e.config,n=e.instance;t.disableAnonymousTraffic&&!n.user("userId")&&n.once("identifyStart",function(e){e.plugins["aws-pinpoint"].loaded()||n.loadPlugin("aws-pinpoint")})},initialize:function(n){var c=n.config,u=n.instance,d=c.disableAnonymousTraffic,l=u.getState(),p=(l.user||{}).userId,h=l.context||{},f=h.app,g=h.version;if(!p&&d)return!1;var y=U(s({},c,{appTitle:c.appTitle||f,appPackageName:c.appPackageName||f,appVersionCode:c.appVersionCode||g,getEndpointId:function(){return u.user("anonymousId")},getContext:function(){return{elapsed:i,pageSession:r,subSessionId:o,subSessionStart:a,sessionKey:c.sessionKey,pageViewKey:c.pageViewKey}},enrichEventAttributes:function(){return{}},enrichEventMetrics:function(){return{}}}));e=y.recordEvent,t=y.updateEndpoint,e("_session.start"),te(function(t){t?(i+=Date.now()-a,e(k.SESSION_STOP,!1)):(o=m(),a=Date.now(),e(k.SESSION_START))})},page:function(t){t.payload,t.config,e?e(k.PAGE_VIEW,!1):console.log("Pinpoint not loaded")},reset:function(e){e.instance,storage.removeItem(P)},track:function(t){var n=t.payload,r=t.config;if(t.instance,e){if(!r.disableAnonymousTraffic||n.userId){var s,i=(s=n.properties,Object.keys(s).reduce(function(e,t){var n=s[t];return"number"==typeof n&&(e.metrics[t]=n),"string"==typeof n&&(e.attributes[t]=n),e},{attributes:{},metrics:{}}));e(n.event,i)}}else console.log("Pinpoint not loaded")},identify:function(e){var n=e.payload,r=n.userId,i=n.traits;if(t){var o={};r&&(o.UserId=r),i&&Object.keys(i).length&&(o.UserAttributes=i),t(s({},i.email?{Address:i.email,ChannelType:I.EMAIL}:{},{},Object.keys(o).length?{User:o}:{}))}else console.log("Pinpoint not loaded")},loaded:function(){return!!e}}}}(); | ||
var analyticsAWSPinpoint=function(){"use strict";function e(e,t,n,r,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,s)}function t(t){return function(){var n=this,r=arguments;return new Promise(function(s,i){var o=t.apply(n,r);function a(t){e(o,s,i,a,c,"next",t)}function c(t){e(o,s,i,a,c,"throw",t)}a(void 0)})}}function n(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function s(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?r(s,!0).forEach(function(t){n(e,t,s[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):r(s).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))})}return e}var i=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===o}(e)}(e)};var o="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function a(e,t){return!1!==t.clone&&t.isMergeableObject(e)?p((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function c(e,t,n){return e.concat(t).map(function(e){return a(e,n)})}function u(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return e.propertyIsEnumerable(t)}):[]}(e))}function d(e,t){try{return t in e}catch(e){return!1}}function l(e,t,n){var r={};return n.isMergeableObject(e)&&u(e).forEach(function(t){r[t]=a(e[t],n)}),u(t).forEach(function(s){(function(e,t){return d(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,s)||(d(e,s)&&n.isMergeableObject(t[s])?r[s]=function(e,t){if(!t.customMerge)return p;var n=t.customMerge(e);return"function"==typeof n?n:p}(s,n)(e[s],t[s],n):r[s]=a(t[s],n))}),r}function p(e,t,n){(n=n||{}).arrayMerge=n.arrayMerge||c,n.isMergeableObject=n.isMergeableObject||i,n.cloneUnlessOtherwiseSpecified=a;var r=Array.isArray(t);return r===Array.isArray(e)?r?n.arrayMerge(e,t,n):l(e,t,n):a(t,n)}p.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,n){return p(e,n,t)},{})};var h=p;function f(e,t,n,r,s,i){if("undefined"!=typeof window)return arguments.length>1?document.cookie=e+"="+encodeURIComponent(t)+(n?"; expires="+new Date(+new Date+1e3*n).toUTCString()+(r?"; path="+r:"")+(s?"; domain="+s:"")+(i?"; secure":""):""):decodeURIComponent((("; "+document.cookie).split("; "+e+"=")[1]||"").split(";")[0])}function g(e){return(g="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}"object"===("undefined"==typeof self?"undefined":g(self))&&self.self===self&&self||"object"===("undefined"==typeof global?"undefined":g(global))&&global.global===global&&global,function(){try{f("_c_","1");var e=-1!==document.cookie.indexOf("_c_");f("_c_","",-1)}catch(e){return!1}}();function m(){for(var e="",t=0,n=4294967295*Math.random()|0;t++<36;){var r="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"[t-1],s=15&n;e+="-"==r||"4"==r?r:("x"==r?s:3&s|8).toString(16),n=t%8==0?4294967295*Math.random()|0:n>>4}return e}const y=new TextEncoder,b={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},v=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"];class w{constructor({accessKeyId:e,secretAccessKey:t,sessionToken:n,service:r,region:s,cache:i,retries:o,initRetryMs:a}){if(null==e)throw new TypeError("accessKeyId is a required option");if(null==t)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=n,this.service=r,this.region=s,this.cache=i||new Map,this.retries=null!=o?o:10,this.initRetryMs=a||50}async sign(e,t){if(e instanceof Request){const{method:n,url:r,headers:s,body:i}=e;null==(t=Object.assign({method:n,url:r,headers:s},t)).body&&s.has("Content-Type")&&(t.body=null!=i&&s.has("X-Amz-Content-Sha256")?i:await e.clone().arrayBuffer()),e=r}const n=new S(Object.assign({url:e},t,this,t&&t.aws)),r=Object.assign({},t,await n.sign());return delete r.aws,new Request(r.url.toString(),r)}async fetch(e,t){for(let n=0;n<=this.retries;n++){const r=fetch(await this.sign(e,t));if(n===this.retries)return r;const s=await r;if(s.status<500&&429!==s.status)return s;await new Promise(e=>setTimeout(e,Math.random()*this.initRetryMs*Math.pow(2,n)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class S{constructor({method:e,url:t,headers:n,body:r,accessKeyId:s,secretAccessKey:i,sessionToken:o,service:a,region:c,cache:u,datetime:d,signQuery:l,appendSessionToken:p,allHeaders:h,singleEncode:f}){if(null==t)throw new TypeError("url is a required option");if(null==s)throw new TypeError("accessKeyId is a required option");if(null==i)throw new TypeError("secretAccessKey is a required option");let g,m;this.method=e||(r?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(n||{}),this.body=r,this.accessKeyId=s,this.secretAccessKey=i,this.sessionToken=o,a&&c||([g,m]=function(e,t){const{hostname:n,pathname:r}=e,s=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/);let[i,o]=(s||["",""]).slice(1,3);if("us-gov"===o)o="us-gov-west-1";else if("s3"===o||"s3-accelerate"===o)o="us-east-1",i="s3";else if("iot"===i)i=n.startsWith("iot.")?"execute-api":n.startsWith("data.jobs.iot.")?"iot-jobs-data":"/mqtt"===r?"iotdevicegateway":"iotdata";else if("autoscaling"===i){const e=(t.get("X-Amz-Target")||"").split(".")[0];"AnyScaleFrontendService"===e?i="application-autoscaling":"AnyScaleScalingPlannerFrontendService"===e&&(i="autoscaling-plans")}else null==o&&i.startsWith("s3-")?(o=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):o&&/-\d$/.test(i)&&!/-\d$/.test(o)&&([i,o]=[o,i]);return[b[i]||i,o]}(this.url,this.headers)),this.service=a||g||"",this.region=c||m||"us-east-1",this.cache=u||new Map,this.datetime=d||(new Date).toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=l,this.appendSessionToken=p||"iotdevicegateway"===this.service,this.headers.delete("Host");const y=this.signQuery?this.url.searchParams:this.headers;if("s3"!==this.service||this.headers.has("X-Amz-Content-Sha256")||this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),y.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&y.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(e=>h||!v.includes(e)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(e=>e+":"+("host"===e?this.url.host:(this.headers.get(e)||"").replace(/\s+/g," "))).join("\n"),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&("s3"!==this.service||y.has("X-Amz-Expires")||y.set("X-Amz-Expires","86400"),y.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),y.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),y.set("X-Amz-SignedHeaders",this.signedHeaders)),"s3"===this.service)try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(e){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");f||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=O(this.encodedPath);const w=new Set;this.encodedSearch=[...this.url.searchParams].filter(([e])=>{if(!e)return!1;if("s3"===this.service){if(w.has(e))return!1;w.add(e)}return!0}).map(e=>e.map(e=>O(encodeURIComponent(e)))).sort(([e,t],[n,r])=>e<n?-1:e>n?1:t<r?-1:t>r?1:0).map(e=>e.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){const e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join();let n=this.cache.get(t);if(!n){const r=await A("AWS4"+this.secretAccessKey,e),s=await A(r,this.region),i=await A(s,this.service);n=await A(i,"aws4_request"),this.cache.set(t,n)}return E(await A(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,E(await x(await this.canonicalString()))].join("\n")}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+"\n",this.signedHeaders,await this.hexBodyHash()].join("\n")}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(null==e){if(this.body&&"string"!=typeof this.body&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=E(await x(this.body||""))}return e}}async function A(e,t){const n=await crypto.subtle.importKey("raw","string"==typeof e?y.encode(e):e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,y.encode(t))}async function x(e){return crypto.subtle.digest("SHA-256","string"==typeof e?y.encode(e):e)}function E(e){return Array.prototype.map.call(new Uint8Array(e),e=>("0"+e.toString(16)).slice(-2)).join("")}function O(e){return e.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}var k={SESSION_START:"_session.start",SESSION_STOP:"_session.stop",SESSION_PAUSE:"_session.pause",SESSION_RESUME:"_session.resume",AUTH_SIGN_IN:"_userauth.sign_in",AUTH_SIGN_UP:"_userauth.sign_up",AUTH_FAIL:"_userauth.auth_fail",ECOM_PURCHASE:"_monetization.purchase",PAGE_VIEW:"pageView"},I=["PUSH","GCM","APNS","APNS_SANDBOX","APNS_VOIP","APNS_VOIP_SANDBOX","ADM","SMS","VOICE","EMAIL","BAIDU","CUSTOM"].reduce(function(e,t){return e[t]=t,e},{});"undefined"!=typeof navigator&&navigator&&navigator.sendBeacon;var P="__session_id",T="__endpoint",M=[429,500],j=[202],C=400,_=function(){if("undefined"==typeof window)return{};if(!window.navigator)return{};var e,t,n,r,s,i=window.navigator,o=i.platform,a=i.product,c=i.vendor,u=function(e){var t=/.+(Opera[\s[A-Z]*|OPR[\sA-Z]*)\/([0-9\.]+).*/i.exec(e);if(t)return{type:t[1],version:t[2]};var n=/.+(Trident|Edge)\/([0-9\.]+).*/i.exec(e);if(n)return{type:n[1],version:n[2]};var r=/.+(Chrome|Firefox|FxiOS)\/([0-9\.]+).*/i.exec(e);if(r)return{type:r[1],version:r[2]};var s=/.+(Safari)\/([0-9\.]+).*/i.exec(e);if(s)return{type:s[1],version:s[2]};var i=/.+(AppleWebKit)\/([0-9\.]+).*/i.exec(e);if(i)return{type:i[1],version:i[2]};var o=/.*([A-Z]+)\/([0-9\.]+).*/i.exec(e);return o?{type:o[1],version:o[2]}:{type:"",version:""}}(i.userAgent);return{platform:o,make:a||c,model:u.type,version:u.version,appVersion:[u.type,u.version].join("/"),language:(t=window.navigator,n=t.language,r=t.browserLanguage,s=t.languages,(n||r||(s||["en_US"])[0]).toLowerCase().replace("-","_")),timezone:(e=/\(([A-Za-z\s].*)\)/.exec((new Date).toString()),e&&e[1]||"")}}(),R=[];function H(){return{}}var D=/.+\@.+\..+/;function U(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=s({getContext:e.getContext||H,enrichEventAttributes:e.enrichEventAttributes||H,enrichEventMetrics:e.enrichEventMetrics||H,credentials:e.credentials||{},getEndpointId:e.getEndpointId},e),i=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.getEndpointId,i=e.debug;return function(){var o=t(regeneratorRuntime.mark(function t(){var o,a,c,u,d,l,p,h,f=arguments;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(o=f.length>0&&void 0!==f[0]?f[0]:{},R.length||Object.keys(o).length){t.next=4;break}return i&&console.log("No events, return early"),t.abrupt("return");case 4:return a=o,t.next=7,r();case 7:if(c=t.sent,i&&console.log("resolved endpointId",c),c){t.next=12;break}return console.error("No User ID found. Call Auth()"),t.abrupt("return");case 12:if(!Object.entries(o).length){t.next=19;break}return u=e.getContext(),t.next=16,W(o,u);case 16:a=t.sent,t.next=20;break;case 19:a=K()||{};case 20:return i&&console.log("endpointData",a),d=a.ChannelType,a.Address&&(g=a.Address,D.test(g))&&(d=I.EMAIL),!d&&a.Address&&(d="android"===_.platform?d||I.GCM:d||I.APNS),i&&console.log("CHANNEL_TYPE",d),l=R.reduce(function(e,t){return s({},t,{},e)},{}),(p=a).RequestId=m(),p.ChannelType=d,p.Address&&(p.OptOut=a.OptOut||"NONE"),h={BatchItem:n({},c,{Endpoint:p,Events:l})},t.prev=31,t.next=34,V(h,e);case 34:t.sent,t.next=40;break;case 37:t.prev=37,t.t0=t.catch(31),console.log("callPinPoint err",t.t0);case 40:return R=[],t.abrupt("return",a);case 42:case"end":return t.stop()}var g},t,null,[[31,37]])}));return function(){return o.apply(this,arguments)}}()}(r),o=function(){var e,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=r.sentDataToPinpoint,o=r.appPackageName,a=r.appTitle,c=r.appVersionCode,u=r.debug;return function(){var d=t(regeneratorRuntime.mark(function t(d){var l,p,h,f,g,y,b,v,w,S,A,x,E,O,I,P,T,M,j,C,_,H,D=arguments;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(l=D.length>1&&void 0!==D[1]?D[1]:{},p=D.length>2&&void 0!==D[2]?D[2]:{},h=!(D.length>3&&void 0!==D[3])||D[3],"boolean"==typeof l&&(h=l,l={}),"boolean"==typeof p&&(h=p,p={}),f=r.getContext(),g=f.pageSession,y=f.subSessionId,b=f.subSessionStart,v=f.elapsed,!Object.entries(p).length&&d!==k.PAGE_VIEW){t.next=11;break}return t.next=10,W(p,f);case 10:p=t.sent;case 11:return w=new Date,S=l.attributes||{},A={date:w.toISOString(),session:N(),pageSession:g,hash:window.location.hash,path:window.location.pathname,referrer:document.referrer,search:window.location.search,title:document.title,host:window.location.hostname,url:window.location.origin+window.location.pathname},t.next=16,r.enrichEventAttributes();case 16:return x=t.sent,E=s({},A,{},x,{},S),O=v+(w.getTime()-b),I=l.metrics||{},P={sessionTime:O,hour:w.getHours(),day:w.getDay()+1,month:w.getMonth()+1,year:w.getFullYear()},t.next=23,r.enrichEventMetrics();case 23:return T=t.sent,M=s({},P,{},T,{},I),t.next=27,Z(E);case 27:return t.t0=t.sent,t.next=30,Y(M);case 30:t.t1=t.sent,j={attributes:t.t0,metrics:t.t1},C=m(),_=(new Date).toISOString(),u&&(console.log("".concat(C,":").concat(d)),console.log("eventAttributes",j.attributes),console.log("eventMetrics",j.metrics)),H=n({},C,{EventType:d,Timestamp:_,AppPackageName:o,AppTitle:a,AppVersionCode:c,Attributes:j.attributes,Metrics:j.metrics,Session:{Id:y,StartTimestamp:new Date(b).toISOString()}}),d===k.SESSION_STOP&&(H[C].Session.Duration=Date.now()-b,H[C].Session.StopTimestamp=_),R.push(H),t.next=40;break;case 40:if(h){t.next=42;break}return t.abrupt("return",i());case 42:e&&clearTimeout(e),e=setTimeout(i,5e3);case 44:case"end":return t.stop()}},t)}));return function(e){return d.apply(this,arguments)}}()}(s({sentDataToPinpoint:i},r));W({},r.getContext());var a=function(e){if("undefined"==typeof window)return H;var t=function(e){return function(){console.log("Fire stop session"),e("_session.stop",!1)}}(e);return window.addEventListener("beforeunload",t),function(){return window.removeEventListener("beforeunload",t)}}(o);return{updateEndpoint:i,recordEvent:o,disable:function(){a()}}}function N(){if(void 0===window.sessionStorage)return null;var e=window.sessionStorage.getItem(P);if(e)return e;var t=m();return window.sessionStorage.setItem(P,t),t}function K(){try{return JSON.parse(localStorage.getItem(T))||{}}catch(e){return{}}}function z(e){localStorage.setItem(T,JSON.stringify(e))}function V(e,t){return X.apply(this,arguments)}function X(){return(X=t(regeneratorRuntime.mark(function e(t,n){var r,s,i,o,a,c,u,d,l,p,h,f,g,m;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=n.pinpointRegion,n.pinpointEndpoint,s=n.pinpointAppId,i=n.lambdaArn,o=n.lambdaRegion,a=n.credentials,c=n.getCredentials,u=n.debug,d=a,Object.keys(d).length||!c){e.next=12;break}return e.prev=3,e.next=6,c();case 6:d=e.sent,e.next=12;break;case 9:throw e.prev=9,e.t0=e.catch(3),new Error(e.t0);case 12:return l=new w({accessKeyId:d.accessKeyId||d.AccessKeyId,secretAccessKey:d.secretAccessKey||d.SecretKey,sessionToken:d.sessionToken||d.SessionToken}),p=r||o,h="https://lambda.".concat(o||r,".amazonaws.com/2015-03-31/functions/").concat(i,"/invocations"),f="https://pinpoint.".concat(p,".amazonaws.com/v1/apps/").concat(s,"/events"),g=i?h:f,e.next=20,l.fetch(g,{body:JSON.stringify(t)}).then(function(e){return e.json()});case 20:return(m=e.sent)&&m.Results&&Object.keys(m.Results).map(function(e){return m.Results[e]}).forEach(function(e){var t=e.EndpointItemResponse||{},n=e.EventsItemResponse||{};Object.keys(t).length&&(u&&console.log("EndpointItemResponse",t),j.includes(t.StatusCode)||M.includes(t.StatusCode)||L(t,Endpoint));var r=Object.keys(n);r.length&&(u&&console.log("EventsResponse",n),r.forEach(function(e){}))}),e.abrupt("return",m);case 23:case"end":return e.stop()}},e,null,[[3,9]])}))).apply(this,arguments)}function L(e,t){var n=e.StatusCode,r=e.Message;if(n===C){if(r.startsWith("Missing ChannelType"))throw new Error("Missing ChannelType");if(r.startsWith("Exceeded maximum endpoint per user count"))throw new Error("Exceeded maximum endpoint per user count")}}function W(){return q.apply(this,arguments)}function q(){return(q=t(regeneratorRuntime.mark(function e(){var t,n,r,i,o,a,c,u,d,l=arguments;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t=l.length>0&&void 0!==l[0]?l[0]:{},n=l.length>1&&void 0!==l[1]?l[1]:{},r=K(),i=n.pageSession,o={},a={AppVersion:_.appVersion,Make:_.make,Model:_.model,ModelVersion:_.version,Platform:_.platform,Locale:_.language},c={Attributes:{},Demographic:s({AppVersion:_.appVersion||""},a,{},o.demographic),Location:{},Metrics:{}},_.device&&_.device.vendor&&(c.Attributes.DeviceMake=[_.device.vendor]),_.device&&_.device.model&&(c.Attributes.DeviceModel=[_.device.model]),_.device&&_.device.type&&(c.Attributes.DeviceType=[_.device.type]),_.engine&&_.engine.name&&(c.Demographic.Make=_.engine.name),_.browser&&_.browser.name&&(c.Demographic.Model=_.browser.name),_.browser&&_.browser.version&&(c.Demographic.ModelVersion=_.browser.version),_.os&&_.os.name&&(c.Demographic.Platform=_.os.name),_.os&&_.os.version&&(c.Demographic.PlatformVersion=_.os.version),!(t=h.all([c,r,t],{arrayMerge:B})).User||!t.User.UserAttributes){e.next=20;break}return e.next=19,Z(t.User.UserAttributes,!0);case 19:t.User.UserAttributes=e.sent;case 20:return e.next=22,Z(t.Attributes,!0);case 22:return t.Attributes=e.sent,e.next=25,Y(t.Metrics);case 25:return t.Metrics=e.sent,u="sessions",n.sessionKey&&(u=n.sessionKey()),d="pageViews",n.pageViewKey&&(d=n.pageViewKey()),t.Attributes.lastSession?(t.Attributes.lastSession[0]!==N()&&(t.Attributes.lastSession=[N()],t.Metrics[u]+=1),t.Attributes.lastPageSession[0]!==i&&(t.Attributes.lastPageSession=[i],t.Metrics[d]+=1)):(t.Attributes.lastSession=[N()],t.Attributes.lastPageSession=[i],t.Metrics[u]=1,t.Metrics[d]=1),z(t),e.abrupt("return",t);case 33:case"end":return e.stop()}},e)}))).apply(this,arguments)}function B(e,t){return t}function F(e,t){return G.apply(this,arguments)}function G(){return(G=t(regeneratorRuntime.mark(function e(t,n){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("function"!=typeof t){e.next=4;break}return e.next=3,t();case 3:t=e.sent;case 4:return e.abrupt("return",n(t));case 5:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Q(e){return Array.isArray(e)?e.map(function(e){return e.toString()}):e.toString()}function $(e){return parseFloat(Number(Array.isArray(e)?e[0]:e))}function Z(e){return J.apply(this,arguments)}function J(){return(J=t(regeneratorRuntime.mark(function e(t){var n,r,s,i,o=arguments;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n=o.length>1&&void 0!==o[1]&&o[1],r={},e.t0=regeneratorRuntime.keys(t);case 3:if((e.t1=e.t0()).done){e.next=17;break}if(s=e.t1.value,i=Array.isArray(t[s])?t[s]:[t[s]],!n){e.next=12;break}return e.next=9,F(i,Q);case 9:r[s]=e.sent,e.next=15;break;case 12:return e.next=14,F(i[0],Q);case 14:r[s]=e.sent;case 15:e.next=3;break;case 17:return e.abrupt("return",r);case 18:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Y(e){return ee.apply(this,arguments)}function ee(){return(ee=t(regeneratorRuntime.mark(function e(t){var n,r;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n={},e.t0=regeneratorRuntime.keys(t);case 2:if((e.t1=e.t0()).done){e.next=9;break}return r=e.t1.value,e.next=6,F(t[r],$);case 6:n[r]=e.sent,e.next=2;break;case 9:return e.abrupt("return",n);case 10:case"end":return e.stop()}},e)}))).apply(this,arguments)}function te(e){if("undefined"==typeof window)return!1;var t="hidden"in document?"hidden":["webkit","moz","ms","o"].reduce(function(e,t){return!e&&"".concat(t,"Hidden")in document?"".concat(t,"Hidden"):e},null);if(!t)return!1;var n="".concat(t.replace(/[H|h]idden/,""),"visibilitychange"),r=function(){return document[t]?e(!0):e(!1)};return document.addEventListener(n,r),function(){return document.removeEventListener(n,r)}}var ne={disableAnonymousTraffic:!1,pinpointRegion:"us-east-1"};return function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=0,i=m(),o=m(),a=Date.now();return{name:"aws-pinpoint",config:s({},ne,{},n),bootstrap:function(e){var t=e.config,n=e.instance;t.disableAnonymousTraffic&&!n.user("userId")&&n.once("identifyStart",function(e){e.plugins["aws-pinpoint"].loaded()||n.loadPlugin("aws-pinpoint")})},initialize:function(n){var c=n.config,u=n.instance,d=c.disableAnonymousTraffic,l=u.getState(),p=(l.user||{}).userId,h=l.context||{},f=h.app,g=h.version;if(!p&&d)return!1;var y=U(s({},c,{appTitle:c.appTitle||f,appPackageName:c.appPackageName||f,appVersionCode:c.appVersionCode||g,getEndpointId:function(){return u.user("anonymousId")},getContext:function(){return{elapsed:r,pageSession:i,subSessionId:o,subSessionStart:a,sessionKey:c.sessionKey,pageViewKey:c.pageViewKey}},enrichEventAttributes:function(){return{}},enrichEventMetrics:function(){return{}}}));e=y.recordEvent,t=y.updateEndpoint,e("_session.start"),te(function(t){t?(r+=Date.now()-a,e(k.SESSION_STOP,!1)):(o=m(),a=Date.now(),e(k.SESSION_START))})},page:function(t){t.payload,t.config,e?e(k.PAGE_VIEW,!1).then(function(){i=m()}):console.log("Pinpoint not loaded")},reset:function(e){e.instance,storage.removeItem(T)},track:function(t){var n=t.payload,r=t.config;if(t.instance,e){if(!r.disableAnonymousTraffic||n.userId){var s,i=(s=n.properties,Object.keys(s).reduce(function(e,t){var n=s[t];return"number"==typeof n&&(e.metrics[t]=n),"string"==typeof n&&(e.attributes[t]=n),e},{attributes:{},metrics:{}}));e(n.event,i)}}else console.log("Pinpoint not loaded")},identify:function(e){var n=e.payload,r=n.userId,i=n.traits;if(t){var o={};r&&(o.UserId=r),i&&Object.keys(i).length&&(o.UserAttributes=i),t(s({},i.email?{Address:i.email,ChannelType:I.EMAIL}:{},{},Object.keys(o).length?{User:o}:{}))}else console.log("Pinpoint not loaded")},loaded:function(){return!!e}}}}(); |
@@ -398,3 +398,3 @@ 'use strict'; | ||
if (!Object.entries(endpoint).length) { | ||
if (!(Object.entries(endpoint).length || type === EVENTS.PAGE_VIEW)) { | ||
_context.next = 11; | ||
@@ -749,6 +749,3 @@ break; | ||
case 12: | ||
/* | ||
console.log('credentials in plugin', creds) | ||
console.log('credentials.identityId', creds.identityId) | ||
/**/ | ||
// console.log('credentials', creds) | ||
aws = new aws4fetch.AwsClient({ | ||
@@ -1020,2 +1017,4 @@ // Support amplify and raw client auth params | ||
} // Increment pageViews. | ||
// console.log('[pageViews] lastPageSession', endpoint.Attributes.lastPageSession[0]) | ||
// console.log('[pageViews] pageSession', pageSession) | ||
@@ -1025,3 +1024,3 @@ | ||
endpoint.Attributes.lastPageSession = [pageSession]; | ||
endpoint.Metrics[pageKey] += 1.0; | ||
endpoint.Metrics[pageKey] += 1.0; // console.log('[pageViews] Its different increment page views. New Count', endpoint.Metrics[pageKey]) | ||
} | ||
@@ -1306,3 +1305,2 @@ } // Store the endpoint data. | ||
var pluginConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var pageSession = analyticsUtils.uuid(); | ||
var recordEvent; | ||
@@ -1312,2 +1310,5 @@ var updateEndpoint; | ||
var elapsedSessionTime = 0; | ||
/* Page-session (on route changes) */ | ||
var pageSession = analyticsUtils.uuid(); | ||
/* Sub-session (visibility changes) */ | ||
@@ -1439,6 +1440,8 @@ | ||
return; | ||
} // console.log('fire', EVENTS.pageView) | ||
} // Fire page view and update pageSession Id | ||
recordEvent(EVENTS.PAGE_VIEW, false); | ||
recordEvent(EVENTS.PAGE_VIEW, false).then(function () { | ||
pageSession = analyticsUtils.uuid(); | ||
}); | ||
}, | ||
@@ -1445,0 +1448,0 @@ reset: function reset(_ref4) { |
@@ -394,3 +394,3 @@ import deepmerge from 'deepmerge'; | ||
if (!Object.entries(endpoint).length) { | ||
if (!(Object.entries(endpoint).length || type === EVENTS.PAGE_VIEW)) { | ||
_context.next = 11; | ||
@@ -745,6 +745,3 @@ break; | ||
case 12: | ||
/* | ||
console.log('credentials in plugin', creds) | ||
console.log('credentials.identityId', creds.identityId) | ||
/**/ | ||
// console.log('credentials', creds) | ||
aws = new AwsClient({ | ||
@@ -1016,2 +1013,4 @@ // Support amplify and raw client auth params | ||
} // Increment pageViews. | ||
// console.log('[pageViews] lastPageSession', endpoint.Attributes.lastPageSession[0]) | ||
// console.log('[pageViews] pageSession', pageSession) | ||
@@ -1021,3 +1020,3 @@ | ||
endpoint.Attributes.lastPageSession = [pageSession]; | ||
endpoint.Metrics[pageKey] += 1.0; | ||
endpoint.Metrics[pageKey] += 1.0; // console.log('[pageViews] Its different increment page views. New Count', endpoint.Metrics[pageKey]) | ||
} | ||
@@ -1302,3 +1301,2 @@ } // Store the endpoint data. | ||
var pluginConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var pageSession = uuid(); | ||
var recordEvent; | ||
@@ -1308,2 +1306,5 @@ var updateEndpoint; | ||
var elapsedSessionTime = 0; | ||
/* Page-session (on route changes) */ | ||
var pageSession = uuid(); | ||
/* Sub-session (visibility changes) */ | ||
@@ -1435,6 +1436,8 @@ | ||
return; | ||
} // console.log('fire', EVENTS.pageView) | ||
} // Fire page view and update pageSession Id | ||
recordEvent(EVENTS.PAGE_VIEW, false); | ||
recordEvent(EVENTS.PAGE_VIEW, false).then(function () { | ||
pageSession = uuid(); | ||
}); | ||
}, | ||
@@ -1441,0 +1444,0 @@ reset: function reset(_ref4) { |
{ | ||
"name": "@analytics/aws-pinpoint", | ||
"version": "0.2.0", | ||
"version": "0.2.1", | ||
"description": "AWS Pinpoint integration for 'analytics' module", | ||
@@ -59,3 +59,3 @@ "projectMeta": { | ||
}, | ||
"gitHead": "c813970f88292449694aba5272e6c6beca909886" | ||
"gitHead": "91317e44fd04c3544373e7aec1fe85419848e29b" | ||
} |
Sorry, the diff of this file is too big to display
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
200877
4492