@analytics/aws-pinpoint
Advanced tools
Comparing version 0.3.0 to 0.4.0
@@ -6,2 +6,13 @@ # Change Log | ||
# [0.4.0](https://github.com/DavidWells/analytics/compare/@analytics/aws-pinpoint@0.3.0...@analytics/aws-pinpoint@0.4.0) (2021-02-02) | ||
### Features | ||
* add event mapping ([3cb45f3](https://github.com/DavidWells/analytics/commit/3cb45f3)) | ||
# [0.3.0](https://github.com/DavidWells/analytics/compare/@analytics/aws-pinpoint@0.2.1...@analytics/aws-pinpoint@0.3.0) (2021-02-01) | ||
@@ -8,0 +19,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=I(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=>I(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 I(e){return e.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}var O={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"},k=["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],U=400,C=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]||"")}}(),_=[];function R(){return{}}var H=/.+\@.+\..+/;function D(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=s({getContext:e.getContext||R,enrichEventAttributes:e.enrichEventAttributes||R,enrichEventMetrics:e.enrichEventMetrics||R,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]:{},_.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,e.getUserId);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,H.test(g))&&(d=k.EMAIL),!d&&a.Address&&(d="android"===C.platform?d||k.GCM:d||k.APNS),i&&console.log("CHANNEL_TYPE",d),l=_.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 _=[],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,I,k,P,T,M,j,U,C,R,H=arguments;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(l=H.length>1&&void 0!==H[1]?H[1]:{},p=H.length>2&&void 0!==H[2]?H[2]:{},h=!(H.length>3&&void 0!==H[3])||H[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!==O.PAGE_VIEW){t.next=11;break}return t.next=10,W(p,f,r.getUserId);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),I=v+(w.getTime()-b),k=l.metrics||{},P={sessionTime:I,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,{},k),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},U=m(),C=(new Date).toISOString(),u&&(console.log("".concat(U,":").concat(d)),console.log("eventAttributes",j.attributes),console.log("eventMetrics",j.metrics)),R=n({},U,{EventType:d,Timestamp:C,AppPackageName:o,AppTitle:a,AppVersionCode:c,Attributes:j.attributes,Metrics:j.metrics,Session:{Id:y,StartTimestamp:new Date(b).toISOString()}}),d===O.SESSION_STOP&&(R[U].Session.Duration=Date.now()-b,R[U].Session.StopTimestamp=C),_.push(R),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(),e.getUserId);var a=function(e){if("undefined"==typeof window)return R;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===U){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,p,f,g=arguments;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t=g.length>0&&void 0!==g[0]?g[0]:{},n=g.length>1&&void 0!==g[1]?g[1]:{},r=g.length>2?g[2]:void 0,i=K(),o=n.pageSession,a={},c={AppVersion:C.appVersion,Make:C.make,Model:C.model,ModelVersion:C.version,Platform:C.platform,Locale:C.language},u={Attributes:{},Demographic:s({AppVersion:C.appVersion||""},c,{},a.demographic),Location:{},Metrics:{}},C.device&&C.device.vendor&&(u.Attributes.DeviceMake=[C.device.vendor]),C.device&&C.device.model&&(u.Attributes.DeviceModel=[C.device.model]),C.device&&C.device.type&&(u.Attributes.DeviceType=[C.device.type]),C.engine&&C.engine.name&&(u.Demographic.Make=C.engine.name),C.browser&&C.browser.name&&(u.Demographic.Model=C.browser.name),C.browser&&C.browser.version&&(u.Demographic.ModelVersion=C.browser.version),C.os&&C.os.name&&(u.Demographic.Platform=C.os.name),C.os&&C.os.version&&(u.Demographic.PlatformVersion=C.os.version),!(t=h.all([u,i,t],{arrayMerge:B})).User||!t.User.UserId){e.next=22;break}return e.next=20,r();case 20:d=e.sent,t.User.UserId!==d&&(t.User.UserId=d);case 22:if(t.User&&t.User.UserId){e.next=27;break}return e.next=25,r();case 25:(l=e.sent)&&(t.User||(t.User={}),t.User.UserId=l);case 27:if(!t.User||!t.User.UserAttributes){e.next=31;break}return e.next=30,Z(t.User.UserAttributes,!0);case 30:t.User.UserAttributes=e.sent;case 31:return e.next=33,Z(t.Attributes,!0);case 33:return t.Attributes=e.sent,e.next=36,Y(t.Metrics);case 36:return t.Metrics=e.sent,p="sessions",n.sessionKey&&(p=n.sessionKey()),f="pageViews",n.pageViewKey&&(f=n.pageViewKey()),t.Attributes.lastSession?(t.Attributes.lastSession[0]!==N()&&(t.Attributes.lastSession=[N()],t.Metrics[p]+=1),t.Attributes.lastPageSession[0]!==o&&(t.Attributes.lastPageSession=[o],t.Metrics[f]+=1)):(t.Attributes.lastSession=[N()],t.Attributes.lastPageSession=[o],t.Metrics[p]=1,t.Metrics[f]=1),z(t),e.abrupt("return",t);case 44: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=D(s({},c,{appTitle:c.appTitle||f,appPackageName:c.appPackageName||f,appVersionCode:c.appVersionCode||g,getEndpointId:function(){return u.user("anonymousId")},getUserId:function(){return u.user("userId")},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(O.SESSION_STOP,!1)):(o=m(),a=Date.now(),e(O.SESSION_START))})},page:function(t){t.payload,t.config,e?e(O.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:k.EMAIL}:{},{},Object.keys(o).length?{User:o}:{}))}else console.log("Pinpoint not loaded")},loaded:function(){return!!e}}}}(); | ||
var analyticsAWSPinpoint=function(e){"use strict";function t(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 n(e){return function(){var n=this,r=arguments;return new Promise(function(s,i){var o=e.apply(n,r);function a(e){t(o,s,i,a,c,"next",e)}function c(e){t(o,s,i,a,c,"throw",e)}a(void 0)})}}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(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 i(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?s(n,!0).forEach(function(t){r(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):s(n).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var o=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===a}(e)}(e)};var a="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function c(e,t){return!1!==t.clone&&t.isMergeableObject(e)?h((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function u(e,t,n){return e.concat(t).map(function(e){return c(e,n)})}function d(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return e.propertyIsEnumerable(t)}):[]}(e))}function p(e,t){try{return t in e}catch(e){return!1}}function l(e,t,n){var r={};return n.isMergeableObject(e)&&d(e).forEach(function(t){r[t]=c(e[t],n)}),d(t).forEach(function(s){(function(e,t){return p(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,s)||(p(e,s)&&n.isMergeableObject(t[s])?r[s]=function(e,t){if(!t.customMerge)return h;var n=t.customMerge(e);return"function"==typeof n?n:h}(s,n)(e[s],t[s],n):r[s]=c(t[s],n))}),r}function h(e,t,n){(n=n||{}).arrayMerge=n.arrayMerge||u,n.isMergeableObject=n.isMergeableObject||o,n.cloneUnlessOtherwiseSpecified=c;var r=Array.isArray(t);return r===Array.isArray(e)?r?n.arrayMerge(e,t,n):l(e,t,n):c(t,n)}h.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,n){return h(e,n,t)},{})};var f=h;function g(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 m(e){return(m="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":m(self))&&self.self===self&&self||"object"===("undefined"==typeof global?"undefined":m(global))&&global.global===global&&global,function(){try{g("_c_","1");var e=-1!==document.cookie.indexOf("_c_");g("_c_","",-1)}catch(e){return!1}}();function y(){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 b=new TextEncoder,v={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"},w=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"];class S{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 A(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 A{constructor({method:e,url:t,headers:n,body:r,accessKeyId:s,secretAccessKey:i,sessionToken:o,service:a,region:c,cache:u,datetime:d,signQuery:p,appendSessionToken:l,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[v[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=p,this.appendSessionToken=l||"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||!w.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=I(this.encodedPath);const b=new Set;this.encodedSearch=[...this.url.searchParams].filter(([e])=>{if(!e)return!1;if("s3"===this.service){if(b.has(e))return!1;b.add(e)}return!0}).map(e=>e.map(e=>I(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 x("AWS4"+this.secretAccessKey,e),s=await x(r,this.region),i=await x(s,this.service);n=await x(i,"aws4_request"),this.cache.set(t,n)}return k(await x(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,k(await E(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=k(await E(this.body||""))}return e}}async function x(e,t){const n=await crypto.subtle.importKey("raw","string"==typeof e?b.encode(e):e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,b.encode(t))}async function E(e){return crypto.subtle.digest("SHA-256","string"==typeof e?b.encode(e):e)}function k(e){return Array.prototype.map.call(new Uint8Array(e),e=>("0"+e.toString(16)).slice(-2)).join("")}function I(e){return e.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}function O(e,t){return t[e]||e}var M=["PUSH","GCM","APNS","APNS_SANDBOX","APNS_VOIP","APNS_VOIP_SANDBOX","ADM","SMS","VOICE","EMAIL","BAIDU","CUSTOM"],P=M.reduce(function(e,t){return e[t]=t,e},{}),T=("undefined"!=typeof navigator&&navigator&&navigator.sendBeacon,"__session_id"),j="__endpoint",U=[429,500],C=[202],_=400,R=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]||"")}}(),H=[];function D(){return{}}var N=/.+\@.+\..+/;function K(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=i({getContext:e.getContext||D,enrichEventAttributes:e.enrichEventAttributes||D,enrichEventMetrics:e.enrichEventMetrics||D,credentials:e.credentials||{},getEndpointId:e.getEndpointId},e),s=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.getEndpointId,s=e.debug;return function(){var o=n(regeneratorRuntime.mark(function n(){var o,a,c,u,d,p,l,h,f=arguments;return regeneratorRuntime.wrap(function(n){for(;;)switch(n.prev=n.next){case 0:if(o=f.length>0&&void 0!==f[0]?f[0]:{},H.length||Object.keys(o).length){n.next=4;break}return s&&console.log("No events, return early"),n.abrupt("return");case 4:return a=o,n.next=7,t();case 7:if(c=n.sent,s&&console.log("resolved endpointId",c),c){n.next=12;break}return console.error("No User ID found. Call Auth()"),n.abrupt("return");case 12:if(!Object.entries(o).length){n.next=19;break}return u=e.getContext(),n.next=16,B(o,u,e.getUserId);case 16:a=n.sent,n.next=20;break;case 19:a=V()||{};case 20:return s&&console.log("endpointData",a),d=a.ChannelType,a.Address&&(g=a.Address,N.test(g))&&(d=P.EMAIL),!d&&a.Address&&(d="android"===R.platform?d||P.GCM:d||P.APNS),s&&console.log("CHANNEL_TYPE",d),p=H.reduce(function(e,t){return i({},t,{},e)},{}),(l=a).RequestId=y(),l.ChannelType=d,l.Address&&(l.OptOut=a.OptOut||"NONE"),h={BatchItem:r({},c,{Endpoint:l,Events:p})},n.prev=31,n.next=34,L(h,e);case 34:n.sent,n.next=40;break;case 37:n.prev=37,n.t0=n.catch(31),console.log("callPinPoint err",n.t0);case 40:return H=[],n.abrupt("return",a);case 42:case"end":return n.stop()}var g},n,null,[[31,37]])}));return function(){return o.apply(this,arguments)}}()}(t),o=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=t.sentDataToPinpoint,o=t.appPackageName,a=t.appTitle,c=t.appVersionCode,u=t.debug;return function(){var d=n(regeneratorRuntime.mark(function n(d){var p,l,h,f,g,m,b,v,w,S,A,x,E,k,I,M,P,T,j,U,C,_,R,D,N,K=arguments;return regeneratorRuntime.wrap(function(n){for(;;)switch(n.prev=n.next){case 0:if(p=K.length>1&&void 0!==K[1]?K[1]:{},l=K.length>2&&void 0!==K[2]?K[2]:{},h=!(K.length>3&&void 0!==K[3])||K[3],f=O(d,t.eventMapping),"boolean"==typeof p&&(h=p,p={}),"boolean"==typeof l&&(h=l,l={}),g=t.getContext(),m=g.pageSession,b=g.subSessionId,v=g.subSessionStart,w=g.elapsed,S=O(void 0,t.eventMapping),!Object.entries(l).length&&f!==S){n.next=13;break}return n.next=12,B(l,g,t.getUserId);case 12:l=n.sent;case 13:return A=new Date,x=p.attributes||{},E={date:A.toISOString(),session:z(),pageSession:m,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},n.next=18,t.enrichEventAttributes();case 18:return k=n.sent,I=i({},E,{},k,{},x),M=w+(A.getTime()-v),P=p.metrics||{},T={sessionTime:M,hour:A.getHours(),day:A.getDay()+1,month:A.getMonth()+1,year:A.getFullYear()},n.next=25,t.enrichEventMetrics();case 25:return j=n.sent,U=i({},T,{},j,{},P),n.next=29,Y(I);case 29:return n.t0=n.sent,n.next=32,te(U);case 32:n.t1=n.sent,C={attributes:n.t0,metrics:n.t1},_=y(),R=(new Date).toISOString(),u&&(console.log("".concat(_,":").concat(f)),console.log("eventAttributes",C.attributes),console.log("eventMetrics",C.metrics)),D=r({},_,{EventType:f,Timestamp:R,AppPackageName:o,AppTitle:a,AppVersionCode:c,Attributes:C.attributes,Metrics:C.metrics,Session:{Id:b,StartTimestamp:new Date(v).toISOString()}}),N=O(void 0,t.eventMapping),f===N&&(D[_].Session.Duration=Date.now()-v,D[_].Session.StopTimestamp=R),H.push(D),n.next=43;break;case 43:if(h){n.next=45;break}return n.abrupt("return",s());case 45:e&&clearTimeout(e),e=setTimeout(s,5e3);case 47:case"end":return n.stop()}},n)}));return function(e){return d.apply(this,arguments)}}()}(i({sentDataToPinpoint:s},t));B({},t.getContext(),e.getUserId);var a=function(e){if("undefined"==typeof window)return D;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:s,recordEvent:o,disable:function(){a()}}}function z(){if(void 0===window.sessionStorage)return null;var e=window.sessionStorage.getItem(T);if(e)return e;var t=y();return window.sessionStorage.setItem(T,t),t}function V(){try{return JSON.parse(localStorage.getItem(j))||{}}catch(e){return{}}}function X(e){localStorage.setItem(j,JSON.stringify(e))}function L(e,t){return q.apply(this,arguments)}function q(){return(q=n(regeneratorRuntime.mark(function e(t,n){var r,s,i,o,a,c,u,d,p,l,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 p=new S({accessKeyId:d.accessKeyId||d.AccessKeyId,secretAccessKey:d.secretAccessKey||d.SecretKey,sessionToken:d.sessionToken||d.SessionToken,retries:5}),l=r||o,h="https://lambda.".concat(o||r,".amazonaws.com/2015-03-31/functions/").concat(i,"/invocations"),f="https://pinpoint.".concat(l,".amazonaws.com/v1/apps/").concat(s,"/events"),g=i?h:f,e.next=20,p.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),C.includes(t.StatusCode)||U.includes(t.StatusCode)||W(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 W(e,t){var n=e.StatusCode,r=e.Message;if(n===_){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 B(){return F.apply(this,arguments)}function F(){return(F=n(regeneratorRuntime.mark(function e(){var t,n,r,s,o,a,c,u,d,p,l,h,g=arguments;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t=g.length>0&&void 0!==g[0]?g[0]:{},n=g.length>1&&void 0!==g[1]?g[1]:{},r=g.length>2?g[2]:void 0,s=V(),o=n.pageSession,a={},c={AppVersion:R.appVersion,Make:R.make,Model:R.model,ModelVersion:R.version,Platform:R.platform,Locale:R.language},u={Attributes:{},Demographic:i({AppVersion:R.appVersion||""},c,{},a.demographic),Location:{},Metrics:{}},R.device&&R.device.vendor&&(u.Attributes.DeviceMake=[R.device.vendor]),R.device&&R.device.model&&(u.Attributes.DeviceModel=[R.device.model]),R.device&&R.device.type&&(u.Attributes.DeviceType=[R.device.type]),R.engine&&R.engine.name&&(u.Demographic.Make=R.engine.name),R.browser&&R.browser.name&&(u.Demographic.Model=R.browser.name),R.browser&&R.browser.version&&(u.Demographic.ModelVersion=R.browser.version),R.os&&R.os.name&&(u.Demographic.Platform=R.os.name),R.os&&R.os.version&&(u.Demographic.PlatformVersion=R.os.version),!(t=f.all([u,s,t],{arrayMerge:G})).User||!t.User.UserId){e.next=22;break}return e.next=20,r();case 20:d=e.sent,t.User.UserId!==d&&(t.User.UserId=d);case 22:if(t.User&&t.User.UserId){e.next=27;break}return e.next=25,r();case 25:(p=e.sent)&&(t.User||(t.User={}),t.User.UserId=p);case 27:if(!t.User||!t.User.UserAttributes){e.next=31;break}return e.next=30,Y(t.User.UserAttributes,!0);case 30:t.User.UserAttributes=e.sent;case 31:return e.next=33,Y(t.Attributes,!0);case 33:return t.Attributes=e.sent,e.next=36,te(t.Metrics);case 36:return t.Metrics=e.sent,l="sessions",n.sessionKey&&(l=n.sessionKey()),h="pageViews",n.pageViewKey&&(h=n.pageViewKey()),t.Attributes.lastSession?(t.Attributes.lastSession[0]!==z()&&(t.Attributes.lastSession=[z()],t.Metrics[l]+=1),t.Attributes.lastPageSession[0]!==o&&(t.Attributes.lastPageSession=[o],t.Metrics[h]+=1)):(t.Attributes.lastSession=[z()],t.Attributes.lastPageSession=[o],t.Metrics[l]=1,t.Metrics[h]=1),X(t),e.abrupt("return",t);case 44:case"end":return e.stop()}},e)}))).apply(this,arguments)}function G(e,t){return t}function Q(e,t){return $.apply(this,arguments)}function $(){return($=n(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 Z(e){return Array.isArray(e)?e.map(function(e){return e.toString()}):e.toString()}function J(e){return parseFloat(Number(Array.isArray(e)?e[0]:e))}function Y(e){return ee.apply(this,arguments)}function ee(){return(ee=n(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,Q(i,Z);case 9:r[s]=e.sent,e.next=15;break;case 12:return e.next=14,Q(i[0],Z);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 te(e){return ne.apply(this,arguments)}function ne(){return(ne=n(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,Q(t[r],J);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)}var re="_session.start",se="_session.stop",ie="pageView",oe=Object.freeze({SESSION_START:re,SESSION_STOP:se,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:ie});function ae(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 ce={disableAnonymousTraffic:!1,pinpointRegion:"us-east-1",eventMapping:{}};var ue=function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=n.eventMapping||{},s=0,o=y(),a=y(),c=Date.now();return{name:"aws-pinpoint",config:i({},ce,{},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 u=n.config,d=n.instance,p=u.disableAnonymousTraffic,l=d.getState(),h=(l.user||{}).userId,f=l.context||{},g=f.app,m=f.version;if(!h&&p)return!1;var b=K(i({},u,{appTitle:u.appTitle||g,appPackageName:u.appPackageName||g,appVersionCode:u.appVersionCode||m,getEndpointId:function(){return d.user("anonymousId")},getUserId:function(){return d.user("userId")},getContext:function(){return{elapsed:s,pageSession:o,subSessionId:a,subSessionStart:c,sessionKey:u.sessionKey,pageViewKey:u.pageViewKey}},enrichEventAttributes:function(){return{}},enrichEventMetrics:function(){return{}},eventMapping:r}));e=b.recordEvent,t=b.updateEndpoint,e(re),ae(function(t){t?(s+=Date.now()-c,e(se,!1)):(a=y(),c=Date.now(),e(re))})},page:function(t){t.payload,t.config,e?e(ie,!1).then(function(){o=y()}):console.log("Pinpoint not loaded")},reset:function(e){e.instance,storage.removeItem(j)},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,s=n.traits;if(t){var o={};r&&(o.UserId=r),s&&Object.keys(s).length&&(o.UserAttributes=s),t(i({},s.email?{Address:s.email,ChannelType:P.EMAIL}:{},{},Object.keys(o).length?{User:o}:{}))}else console.log("Pinpoint not loaded")},loaded:function(){return!!e}}};return e.default=ue,e.PINPOINT_EVENTS=oe,e}({}); |
'use strict'; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } | ||
@@ -95,37 +97,2 @@ | ||
var EVENTS = { | ||
/* The endpoint began a new session. */ | ||
SESSION_START: '_session.start', | ||
/* The endpoint ended a session. */ | ||
SESSION_STOP: '_session.stop', | ||
/* The endpoint paused a session. Paused sessions can be resumed so that you can continue to collect metrics without starting an entirely new session. */ | ||
SESSION_PAUSE: '_session.pause', | ||
/* The endpoint resumed a session. */ | ||
SESSION_RESUME: '_session.resume', | ||
/* The endpoint logged in to your app. */ | ||
AUTH_SIGN_IN: '_userauth.sign_in', | ||
/* A new endpoint completed the registration process in your app. */ | ||
AUTH_SIGN_UP: '_userauth.sign_up', | ||
/* The endpoint attempted to sign in to your app, but wasn't able to complete the process. */ | ||
AUTH_FAIL: '_userauth.auth_fail', | ||
/* The endpoint made a purchase in your app. */ | ||
ECOM_PURCHASE: '_monetization.purchase', | ||
/* The pageview event */ | ||
PAGE_VIEW: 'pageView' // https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-endpoints.html#apps-application-id-endpoints-prop-endpointbatchitem-channeltype | ||
}; | ||
var ALLOWED_CHANNELS = ['PUSH', 'GCM', 'APNS', 'APNS_SANDBOX', 'APNS_VOIP', 'APNS_VOIP_SANDBOX', 'ADM', 'SMS', 'VOICE', 'EMAIL', 'BAIDU', 'CUSTOM']; | ||
var CHANNEL_TYPES = ALLOWED_CHANNELS.reduce(function (acc, curr) { | ||
acc[curr] = curr; | ||
return acc; | ||
}, {}); | ||
function browserClientInfo() { | ||
@@ -231,2 +198,17 @@ if (typeof window === 'undefined') { | ||
function getEventName(key, eventMap) { | ||
return eventMap[key] || key; | ||
} | ||
var ALLOWED_CHANNELS = ['PUSH', 'GCM', 'APNS', 'APNS_SANDBOX', 'APNS_VOIP', 'APNS_VOIP_SANDBOX', 'ADM', 'SMS', 'VOICE', 'EMAIL', 'BAIDU', 'CUSTOM']; | ||
var CHANNEL_TYPES = ALLOWED_CHANNELS.reduce(function (acc, curr) { | ||
acc[curr] = curr; | ||
return acc; | ||
}, {}); | ||
var PINPOINT_EVENTS = /*#__PURE__*/Object.freeze({ | ||
ALLOWED_CHANNELS: ALLOWED_CHANNELS, | ||
CHANNEL_TYPES: CHANNEL_TYPES | ||
}); | ||
// import 'navigator.sendbeacon' | ||
@@ -354,6 +336,7 @@ | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee(type) { | ||
regeneratorRuntime.mark(function _callee(_type) { | ||
var data, | ||
endpoint, | ||
queue, | ||
type, | ||
contextInfo, | ||
@@ -364,2 +347,3 @@ pageSession, | ||
elapsed, | ||
pageViewEvent, | ||
time, | ||
@@ -379,2 +363,3 @@ userDefinedAttributes, | ||
Event, | ||
sessionStopEvent, | ||
_args = arguments; | ||
@@ -388,2 +373,4 @@ return regeneratorRuntime.wrap(function _callee$(_context) { | ||
queue = _args.length > 3 && _args[3] !== undefined ? _args[3] : true; | ||
// Event name mapping | ||
type = getEventName(_type, config.eventMapping); | ||
@@ -404,14 +391,16 @@ if (typeof data === 'boolean') { | ||
if (!(Object.entries(endpoint).length || type === EVENTS.PAGE_VIEW)) { | ||
_context.next = 11; | ||
pageViewEvent = getEventName(undefined, config.eventMapping); | ||
if (!(Object.entries(endpoint).length || type === pageViewEvent)) { | ||
_context.next = 13; | ||
break; | ||
} | ||
_context.next = 10; | ||
_context.next = 12; | ||
return mergeEndpointData(endpoint, contextInfo, config.getUserId); | ||
case 10: | ||
case 12: | ||
endpoint = _context.sent; | ||
case 11: | ||
case 13: | ||
time = new Date(); | ||
@@ -431,6 +420,6 @@ userDefinedAttributes = data.attributes || {}; | ||
}; | ||
_context.next = 16; | ||
_context.next = 18; | ||
return config.enrichEventAttributes(); | ||
case 16: | ||
case 18: | ||
extraAttributes = _context.sent; | ||
@@ -454,17 +443,17 @@ | ||
}; | ||
_context.next = 23; | ||
_context.next = 25; | ||
return config.enrichEventMetrics(); | ||
case 23: | ||
case 25: | ||
extraMetrics = _context.sent; | ||
eventMetrics = _objectSpread2({}, defaultMetrics, {}, extraMetrics, {}, userDefinedMetrics); | ||
_context.next = 27; | ||
_context.next = 29; | ||
return prepareAttributes(eventAttributes); | ||
case 27: | ||
case 29: | ||
_context.t0 = _context.sent; | ||
_context.next = 30; | ||
_context.next = 32; | ||
return prepareMetrics(eventMetrics); | ||
case 30: | ||
case 32: | ||
_context.t1 = _context.sent; | ||
@@ -505,4 +494,5 @@ preparedData = { | ||
}); | ||
sessionStopEvent = getEventName(undefined, config.eventMapping); | ||
if (type === EVENTS.SESSION_STOP) { | ||
if (type === sessionStopEvent) { | ||
Event[eventId].Session.Duration = Date.now() - subSessionStart; | ||
@@ -516,3 +506,3 @@ Event[eventId].Session.StopTimestamp = timeStamp; | ||
{ | ||
_context.next = 40; | ||
_context.next = 43; | ||
break; | ||
@@ -523,5 +513,5 @@ } | ||
case 40: | ||
case 43: | ||
if (queue) { | ||
_context.next = 42; | ||
_context.next = 45; | ||
break; | ||
@@ -532,3 +522,3 @@ } | ||
case 42: | ||
case 45: | ||
if (timer) { | ||
@@ -541,3 +531,3 @@ clearTimeout(timer); | ||
case 44: | ||
case 47: | ||
case "end": | ||
@@ -767,3 +757,4 @@ return _context.stop(); | ||
secretAccessKey: creds.secretAccessKey || creds.SecretKey, | ||
sessionToken: creds.sessionToken || creds.SessionToken | ||
sessionToken: creds.sessionToken || creds.SessionToken, | ||
retries: 5 | ||
}); | ||
@@ -1324,2 +1315,41 @@ lambda_region = lambdaRegion || pinpointRegion; | ||
/* The endpoint began a new session. */ | ||
var SESSION_START = '_session.start'; | ||
/* The endpoint ended a session. */ | ||
var SESSION_STOP = '_session.stop'; | ||
/* The endpoint paused a session. Paused sessions can be resumed so that you can continue to collect metrics without starting an entirely new session. */ | ||
var SESSION_PAUSE = '_session.pause'; | ||
/* The endpoint resumed a session. */ | ||
var SESSION_RESUME = '_session.resume'; | ||
/* The endpoint logged in to your app. */ | ||
var AUTH_SIGN_IN = '_userauth.sign_in'; | ||
/* A new endpoint completed the registration process in your app. */ | ||
var AUTH_SIGN_UP = '_userauth.sign_up'; | ||
/* The endpoint attempted to sign in to your app, but wasn't able to complete the process. */ | ||
var AUTH_FAIL = '_userauth.auth_fail'; | ||
/* The endpoint made a purchase in your app. */ | ||
var ECOM_PURCHASE = '_monetization.purchase'; | ||
/* The pageview event */ | ||
var PAGE_VIEW = 'pageView'; | ||
var events = /*#__PURE__*/Object.freeze({ | ||
SESSION_START: SESSION_START, | ||
SESSION_STOP: SESSION_STOP, | ||
SESSION_PAUSE: SESSION_PAUSE, | ||
SESSION_RESUME: SESSION_RESUME, | ||
AUTH_SIGN_IN: AUTH_SIGN_IN, | ||
AUTH_SIGN_UP: AUTH_SIGN_UP, | ||
AUTH_FAIL: AUTH_FAIL, | ||
ECOM_PURCHASE: ECOM_PURCHASE, | ||
PAGE_VIEW: PAGE_VIEW | ||
}); | ||
var config = { | ||
@@ -1329,3 +1359,5 @@ /* Disable anonymous MTU */ | ||
// Pinpoint service region | ||
pinpointRegion: 'us-east-1' | ||
pinpointRegion: 'us-east-1', | ||
// Custom event mapping | ||
eventMapping: {} | ||
/** | ||
@@ -1355,2 +1387,3 @@ * AWS Pinpoint analytics integration | ||
var pluginConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var eventMap = pluginConfig.eventMapping || {}; | ||
var recordEvent; | ||
@@ -1444,3 +1477,5 @@ var updateEndpoint; | ||
*/ | ||
} | ||
}, | ||
// Custom event mapping | ||
eventMapping: eventMap | ||
})); | ||
@@ -1452,3 +1487,3 @@ | ||
recordEvent('_session.start'); | ||
recordEvent(SESSION_START); | ||
/* Scroll tracking | ||
@@ -1477,3 +1512,3 @@ function pageScrolled(data) { | ||
recordEvent(EVENTS.SESSION_STOP, false); | ||
recordEvent(SESSION_STOP, false); | ||
} else { | ||
@@ -1484,3 +1519,3 @@ // Reset subSessions. | ||
recordEvent(EVENTS.SESSION_START); | ||
recordEvent(SESSION_START); | ||
} | ||
@@ -1499,3 +1534,3 @@ }); | ||
recordEvent(EVENTS.PAGE_VIEW, false).then(function () { | ||
recordEvent(PAGE_VIEW, false).then(function () { | ||
pageSession = analyticsUtils.uuid(); | ||
@@ -1594,2 +1629,3 @@ }); | ||
module.exports = index; | ||
exports.default = index; | ||
exports.PINPOINT_EVENTS = events; |
@@ -91,37 +91,2 @@ import deepmerge from 'deepmerge'; | ||
var EVENTS = { | ||
/* The endpoint began a new session. */ | ||
SESSION_START: '_session.start', | ||
/* The endpoint ended a session. */ | ||
SESSION_STOP: '_session.stop', | ||
/* The endpoint paused a session. Paused sessions can be resumed so that you can continue to collect metrics without starting an entirely new session. */ | ||
SESSION_PAUSE: '_session.pause', | ||
/* The endpoint resumed a session. */ | ||
SESSION_RESUME: '_session.resume', | ||
/* The endpoint logged in to your app. */ | ||
AUTH_SIGN_IN: '_userauth.sign_in', | ||
/* A new endpoint completed the registration process in your app. */ | ||
AUTH_SIGN_UP: '_userauth.sign_up', | ||
/* The endpoint attempted to sign in to your app, but wasn't able to complete the process. */ | ||
AUTH_FAIL: '_userauth.auth_fail', | ||
/* The endpoint made a purchase in your app. */ | ||
ECOM_PURCHASE: '_monetization.purchase', | ||
/* The pageview event */ | ||
PAGE_VIEW: 'pageView' // https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-endpoints.html#apps-application-id-endpoints-prop-endpointbatchitem-channeltype | ||
}; | ||
var ALLOWED_CHANNELS = ['PUSH', 'GCM', 'APNS', 'APNS_SANDBOX', 'APNS_VOIP', 'APNS_VOIP_SANDBOX', 'ADM', 'SMS', 'VOICE', 'EMAIL', 'BAIDU', 'CUSTOM']; | ||
var CHANNEL_TYPES = ALLOWED_CHANNELS.reduce(function (acc, curr) { | ||
acc[curr] = curr; | ||
return acc; | ||
}, {}); | ||
function browserClientInfo() { | ||
@@ -227,2 +192,17 @@ if (typeof window === 'undefined') { | ||
function getEventName(key, eventMap) { | ||
return eventMap[key] || key; | ||
} | ||
var ALLOWED_CHANNELS = ['PUSH', 'GCM', 'APNS', 'APNS_SANDBOX', 'APNS_VOIP', 'APNS_VOIP_SANDBOX', 'ADM', 'SMS', 'VOICE', 'EMAIL', 'BAIDU', 'CUSTOM']; | ||
var CHANNEL_TYPES = ALLOWED_CHANNELS.reduce(function (acc, curr) { | ||
acc[curr] = curr; | ||
return acc; | ||
}, {}); | ||
var PINPOINT_EVENTS = /*#__PURE__*/Object.freeze({ | ||
ALLOWED_CHANNELS: ALLOWED_CHANNELS, | ||
CHANNEL_TYPES: CHANNEL_TYPES | ||
}); | ||
// import 'navigator.sendbeacon' | ||
@@ -350,6 +330,7 @@ | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee(type) { | ||
regeneratorRuntime.mark(function _callee(_type) { | ||
var data, | ||
endpoint, | ||
queue, | ||
type, | ||
contextInfo, | ||
@@ -360,2 +341,3 @@ pageSession, | ||
elapsed, | ||
pageViewEvent, | ||
time, | ||
@@ -375,2 +357,3 @@ userDefinedAttributes, | ||
Event, | ||
sessionStopEvent, | ||
_args = arguments; | ||
@@ -384,2 +367,4 @@ return regeneratorRuntime.wrap(function _callee$(_context) { | ||
queue = _args.length > 3 && _args[3] !== undefined ? _args[3] : true; | ||
// Event name mapping | ||
type = getEventName(_type, config.eventMapping); | ||
@@ -400,14 +385,16 @@ if (typeof data === 'boolean') { | ||
if (!(Object.entries(endpoint).length || type === EVENTS.PAGE_VIEW)) { | ||
_context.next = 11; | ||
pageViewEvent = getEventName(undefined, config.eventMapping); | ||
if (!(Object.entries(endpoint).length || type === pageViewEvent)) { | ||
_context.next = 13; | ||
break; | ||
} | ||
_context.next = 10; | ||
_context.next = 12; | ||
return mergeEndpointData(endpoint, contextInfo, config.getUserId); | ||
case 10: | ||
case 12: | ||
endpoint = _context.sent; | ||
case 11: | ||
case 13: | ||
time = new Date(); | ||
@@ -427,6 +414,6 @@ userDefinedAttributes = data.attributes || {}; | ||
}; | ||
_context.next = 16; | ||
_context.next = 18; | ||
return config.enrichEventAttributes(); | ||
case 16: | ||
case 18: | ||
extraAttributes = _context.sent; | ||
@@ -450,17 +437,17 @@ | ||
}; | ||
_context.next = 23; | ||
_context.next = 25; | ||
return config.enrichEventMetrics(); | ||
case 23: | ||
case 25: | ||
extraMetrics = _context.sent; | ||
eventMetrics = _objectSpread2({}, defaultMetrics, {}, extraMetrics, {}, userDefinedMetrics); | ||
_context.next = 27; | ||
_context.next = 29; | ||
return prepareAttributes(eventAttributes); | ||
case 27: | ||
case 29: | ||
_context.t0 = _context.sent; | ||
_context.next = 30; | ||
_context.next = 32; | ||
return prepareMetrics(eventMetrics); | ||
case 30: | ||
case 32: | ||
_context.t1 = _context.sent; | ||
@@ -501,4 +488,5 @@ preparedData = { | ||
}); | ||
sessionStopEvent = getEventName(undefined, config.eventMapping); | ||
if (type === EVENTS.SESSION_STOP) { | ||
if (type === sessionStopEvent) { | ||
Event[eventId].Session.Duration = Date.now() - subSessionStart; | ||
@@ -512,3 +500,3 @@ Event[eventId].Session.StopTimestamp = timeStamp; | ||
{ | ||
_context.next = 40; | ||
_context.next = 43; | ||
break; | ||
@@ -519,5 +507,5 @@ } | ||
case 40: | ||
case 43: | ||
if (queue) { | ||
_context.next = 42; | ||
_context.next = 45; | ||
break; | ||
@@ -528,3 +516,3 @@ } | ||
case 42: | ||
case 45: | ||
if (timer) { | ||
@@ -537,3 +525,3 @@ clearTimeout(timer); | ||
case 44: | ||
case 47: | ||
case "end": | ||
@@ -763,3 +751,4 @@ return _context.stop(); | ||
secretAccessKey: creds.secretAccessKey || creds.SecretKey, | ||
sessionToken: creds.sessionToken || creds.SessionToken | ||
sessionToken: creds.sessionToken || creds.SessionToken, | ||
retries: 5 | ||
}); | ||
@@ -1320,2 +1309,41 @@ lambda_region = lambdaRegion || pinpointRegion; | ||
/* The endpoint began a new session. */ | ||
var SESSION_START = '_session.start'; | ||
/* The endpoint ended a session. */ | ||
var SESSION_STOP = '_session.stop'; | ||
/* The endpoint paused a session. Paused sessions can be resumed so that you can continue to collect metrics without starting an entirely new session. */ | ||
var SESSION_PAUSE = '_session.pause'; | ||
/* The endpoint resumed a session. */ | ||
var SESSION_RESUME = '_session.resume'; | ||
/* The endpoint logged in to your app. */ | ||
var AUTH_SIGN_IN = '_userauth.sign_in'; | ||
/* A new endpoint completed the registration process in your app. */ | ||
var AUTH_SIGN_UP = '_userauth.sign_up'; | ||
/* The endpoint attempted to sign in to your app, but wasn't able to complete the process. */ | ||
var AUTH_FAIL = '_userauth.auth_fail'; | ||
/* The endpoint made a purchase in your app. */ | ||
var ECOM_PURCHASE = '_monetization.purchase'; | ||
/* The pageview event */ | ||
var PAGE_VIEW = 'pageView'; | ||
var events = /*#__PURE__*/Object.freeze({ | ||
SESSION_START: SESSION_START, | ||
SESSION_STOP: SESSION_STOP, | ||
SESSION_PAUSE: SESSION_PAUSE, | ||
SESSION_RESUME: SESSION_RESUME, | ||
AUTH_SIGN_IN: AUTH_SIGN_IN, | ||
AUTH_SIGN_UP: AUTH_SIGN_UP, | ||
AUTH_FAIL: AUTH_FAIL, | ||
ECOM_PURCHASE: ECOM_PURCHASE, | ||
PAGE_VIEW: PAGE_VIEW | ||
}); | ||
var config = { | ||
@@ -1325,3 +1353,5 @@ /* Disable anonymous MTU */ | ||
// Pinpoint service region | ||
pinpointRegion: 'us-east-1' | ||
pinpointRegion: 'us-east-1', | ||
// Custom event mapping | ||
eventMapping: {} | ||
/** | ||
@@ -1351,2 +1381,3 @@ * AWS Pinpoint analytics integration | ||
var pluginConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var eventMap = pluginConfig.eventMapping || {}; | ||
var recordEvent; | ||
@@ -1440,3 +1471,5 @@ var updateEndpoint; | ||
*/ | ||
} | ||
}, | ||
// Custom event mapping | ||
eventMapping: eventMap | ||
})); | ||
@@ -1448,3 +1481,3 @@ | ||
recordEvent('_session.start'); | ||
recordEvent(SESSION_START); | ||
/* Scroll tracking | ||
@@ -1473,3 +1506,3 @@ function pageScrolled(data) { | ||
recordEvent(EVENTS.SESSION_STOP, false); | ||
recordEvent(SESSION_STOP, false); | ||
} else { | ||
@@ -1480,3 +1513,3 @@ // Reset subSessions. | ||
recordEvent(EVENTS.SESSION_START); | ||
recordEvent(SESSION_START); | ||
} | ||
@@ -1495,3 +1528,3 @@ }); | ||
recordEvent(EVENTS.PAGE_VIEW, false).then(function () { | ||
recordEvent(PAGE_VIEW, false).then(function () { | ||
pageSession = uuid(); | ||
@@ -1591,1 +1624,2 @@ }); | ||
export default index; | ||
export { events as PINPOINT_EVENTS }; |
'use strict'; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
require('deepmerge'); | ||
@@ -18,8 +20,2 @@ require('analytics-utils'); | ||
var ALLOWED_CHANNELS = ['PUSH', 'GCM', 'APNS', 'APNS_SANDBOX', 'APNS_VOIP', 'APNS_VOIP_SANDBOX', 'ADM', 'SMS', 'VOICE', 'EMAIL', 'BAIDU', 'CUSTOM']; | ||
var CHANNEL_TYPES = ALLOWED_CHANNELS.reduce(function (acc, curr) { | ||
acc[curr] = curr; | ||
return acc; | ||
}, {}); | ||
function browserClientInfo() { | ||
@@ -125,2 +121,8 @@ if (typeof window === 'undefined') { | ||
var ALLOWED_CHANNELS = ['PUSH', 'GCM', 'APNS', 'APNS_SANDBOX', 'APNS_VOIP', 'APNS_VOIP_SANDBOX', 'ADM', 'SMS', 'VOICE', 'EMAIL', 'BAIDU', 'CUSTOM']; | ||
var CHANNEL_TYPES = ALLOWED_CHANNELS.reduce(function (acc, curr) { | ||
acc[curr] = curr; | ||
return acc; | ||
}, {}); | ||
// import 'navigator.sendbeacon' | ||
@@ -131,2 +133,41 @@ | ||
/* The endpoint began a new session. */ | ||
var SESSION_START = '_session.start'; | ||
/* The endpoint ended a session. */ | ||
var SESSION_STOP = '_session.stop'; | ||
/* The endpoint paused a session. Paused sessions can be resumed so that you can continue to collect metrics without starting an entirely new session. */ | ||
var SESSION_PAUSE = '_session.pause'; | ||
/* The endpoint resumed a session. */ | ||
var SESSION_RESUME = '_session.resume'; | ||
/* The endpoint logged in to your app. */ | ||
var AUTH_SIGN_IN = '_userauth.sign_in'; | ||
/* A new endpoint completed the registration process in your app. */ | ||
var AUTH_SIGN_UP = '_userauth.sign_up'; | ||
/* The endpoint attempted to sign in to your app, but wasn't able to complete the process. */ | ||
var AUTH_FAIL = '_userauth.auth_fail'; | ||
/* The endpoint made a purchase in your app. */ | ||
var ECOM_PURCHASE = '_monetization.purchase'; | ||
/* The pageview event */ | ||
var PAGE_VIEW = 'pageView'; | ||
var events = /*#__PURE__*/Object.freeze({ | ||
SESSION_START: SESSION_START, | ||
SESSION_STOP: SESSION_STOP, | ||
SESSION_PAUSE: SESSION_PAUSE, | ||
SESSION_RESUME: SESSION_RESUME, | ||
AUTH_SIGN_IN: AUTH_SIGN_IN, | ||
AUTH_SIGN_UP: AUTH_SIGN_UP, | ||
AUTH_FAIL: AUTH_FAIL, | ||
ECOM_PURCHASE: ECOM_PURCHASE, | ||
PAGE_VIEW: PAGE_VIEW | ||
}); | ||
/* This module will shake out unused code + work in browser and node 🎉 */ | ||
@@ -136,2 +177,3 @@ | ||
module.exports = index; | ||
exports.default = index; | ||
exports.PINPOINT_EVENTS = events; |
@@ -16,8 +16,2 @@ import 'deepmerge'; | ||
var ALLOWED_CHANNELS = ['PUSH', 'GCM', 'APNS', 'APNS_SANDBOX', 'APNS_VOIP', 'APNS_VOIP_SANDBOX', 'ADM', 'SMS', 'VOICE', 'EMAIL', 'BAIDU', 'CUSTOM']; | ||
var CHANNEL_TYPES = ALLOWED_CHANNELS.reduce(function (acc, curr) { | ||
acc[curr] = curr; | ||
return acc; | ||
}, {}); | ||
function browserClientInfo() { | ||
@@ -123,2 +117,8 @@ if (typeof window === 'undefined') { | ||
var ALLOWED_CHANNELS = ['PUSH', 'GCM', 'APNS', 'APNS_SANDBOX', 'APNS_VOIP', 'APNS_VOIP_SANDBOX', 'ADM', 'SMS', 'VOICE', 'EMAIL', 'BAIDU', 'CUSTOM']; | ||
var CHANNEL_TYPES = ALLOWED_CHANNELS.reduce(function (acc, curr) { | ||
acc[curr] = curr; | ||
return acc; | ||
}, {}); | ||
// import 'navigator.sendbeacon' | ||
@@ -129,2 +129,41 @@ | ||
/* The endpoint began a new session. */ | ||
var SESSION_START = '_session.start'; | ||
/* The endpoint ended a session. */ | ||
var SESSION_STOP = '_session.stop'; | ||
/* The endpoint paused a session. Paused sessions can be resumed so that you can continue to collect metrics without starting an entirely new session. */ | ||
var SESSION_PAUSE = '_session.pause'; | ||
/* The endpoint resumed a session. */ | ||
var SESSION_RESUME = '_session.resume'; | ||
/* The endpoint logged in to your app. */ | ||
var AUTH_SIGN_IN = '_userauth.sign_in'; | ||
/* A new endpoint completed the registration process in your app. */ | ||
var AUTH_SIGN_UP = '_userauth.sign_up'; | ||
/* The endpoint attempted to sign in to your app, but wasn't able to complete the process. */ | ||
var AUTH_FAIL = '_userauth.auth_fail'; | ||
/* The endpoint made a purchase in your app. */ | ||
var ECOM_PURCHASE = '_monetization.purchase'; | ||
/* The pageview event */ | ||
var PAGE_VIEW = 'pageView'; | ||
var events = /*#__PURE__*/Object.freeze({ | ||
SESSION_START: SESSION_START, | ||
SESSION_STOP: SESSION_STOP, | ||
SESSION_PAUSE: SESSION_PAUSE, | ||
SESSION_RESUME: SESSION_RESUME, | ||
AUTH_SIGN_IN: AUTH_SIGN_IN, | ||
AUTH_SIGN_UP: AUTH_SIGN_UP, | ||
AUTH_FAIL: AUTH_FAIL, | ||
ECOM_PURCHASE: ECOM_PURCHASE, | ||
PAGE_VIEW: PAGE_VIEW | ||
}); | ||
/* This module will shake out unused code + work in browser and node 🎉 */ | ||
@@ -135,1 +174,2 @@ | ||
export default index; | ||
export { events as PINPOINT_EVENTS }; |
{ | ||
"name": "@analytics/aws-pinpoint", | ||
"version": "0.3.0", | ||
"version": "0.4.0", | ||
"description": "AWS Pinpoint integration for 'analytics' module", | ||
@@ -59,3 +59,3 @@ "projectMeta": { | ||
}, | ||
"gitHead": "f9633269d1487617cc9fb9b72f244c77370de1e8" | ||
"gitHead": "36b0d0cf7eb7546b2481ceafd10145705d9438e1" | ||
} |
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
210286
4728