@inploi/sdk 1.14.13 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cdn/index.js +1 -1
- package/dist/index.d.mts +94 -9
- package/dist/index.d.ts +94 -9
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -3
package/cdn/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// This is an inploi sdk script. Learn more at https://inploi.com
|
|
2
2
|
|
|
3
|
-
"use strict";(()=>{var C=Object.defineProperty,F=Object.defineProperties;var M=Object.getOwnPropertyDescriptors;var h=Object.getOwnPropertySymbols;var j=Object.prototype.hasOwnProperty,q=Object.prototype.propertyIsEnumerable;var b=(e,t,n)=>t in e?C(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,d=(e,t)=>{for(var n in t||(t={}))j.call(t,n)&&b(e,n,t[n]);if(h)for(var n of h(t))q.call(t,n)&&b(e,n,t[n]);return e},x=(e,t)=>F(e,M(t));var c=(e,t,n)=>new Promise((r,s)=>{var p=o=>{try{i(n.next(o))}catch(a){s(a)}},u=o=>{try{i(n.throw(o))}catch(a){s(a)}},i=o=>o.done?r(o.value):Promise.resolve(o.value).then(p,u);i((n=n.apply(e,t)).next())});function _(e,t){if(!e)throw new Error(t)}var ee=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});var E="1.14.13";var P={sandbox:"https://api.staging.inploi.com",production:"https://api.inploi.com",_internal_local:"http://api.test"},I=E,S="/log",l="isdk_session";var A=e=>{let t=new Date;return t.setTime(t.getTime()+7*24*60*60*1e3),`${l}=${e};expires=${t.toUTCString()};path=/`},U=(e,t)=>{let n=e.get("session_id");if(t||n)return n;let r=sessionStorage.getItem(`${l}-session_id`);return typeof r=="string"?r:null},$=new RegExp(`${l}=([^;]+)`),L=e=>{let t=e?e.url:location.href,{searchParams:n}=new URL(t),r=n.get("anonymous_id"),s=U(n,typeof window=="undefined");if(r)return{anonymous_id:r,session_id:s};let p=e?e.headers.get("cookie"):document.cookie;if(p){let u=$.exec(p),i=u==null?void 0:u[1];return{anonymous_id:i!=null?i:null,session_id:s}}return{anonymous_id:r,session_id:s}},B=e=>typeof e!="object"||e===null?null:{anonymous_id:"anonymous_id"in e&&typeof e.anonymous_id=="string"?e.anonymous_id:null,session_id:"session_id"in e&&typeof e.session_id=="string"?e.session_id:null},H=e=>e==="about:client"?"":e,T=({apiClient:e,logger:t})=>({log:r=>c(void 0,null,function*(){_(r.request||typeof window!="undefined","Cannot log on the server without a request. Please pass a request to `log`.");let s="request"in r&&r.request?{href:r.request.url,referrer:H(r.request.referrer),title:""}:{href:location.href,referrer:document.referrer,title:document.title};try{let p={library:{name:"inploi-sdk",version:I},page:s},u=L(r.request),i={anonymous_id:u.anonymous_id,session_id:u.session_id,event:r.event,sent_at:new Date().toISOString(),context:p,properties:r.properties,custom_properties:r.customProperties},o=yield e.fetch(S,{method:"POST",body:JSON.stringify(i)}),a=B(o);return a!=null&&a.anonymous_id&&(i.anonymous_id=a.anonymous_id),a!=null&&a.session_id&&(i.session_id=a.session_id),typeof window!="undefined"&&i.anonymous_id&&(i.session_id&&sessionStorage.setItem(`${l}-session_id`,i.session_id.toString()),document.cookie=A(i.anonymous_id)),{success:!0,data:i}}catch(p){return t.error("Failed to send log to API. Inspect error response of `log` for more information."),{success:!1,error:p}}}),getHeaders:r=>{let s=new Headers;return r!=null&&r.anonymous_id&&s.append("Set-Cookie",A(r.anonymous_id)),s},getSessionInfo:L});var J="Unauthenticated",Y="This action is unauthorized.",v=class extends Error{constructor(){super("Not found"),this.name="NotFoundError"}},g=class extends Error{constructor(t){super(t!=null?t:"You are not authorised to perform this action."),this.name="UnauthorisedError"}},f=class extends Error{constructor(n,r){super(`API error: \u201C${n}\u201D`);this.name="ApiError",this.errors=r}},w=class extends Error{constructor(n){super("Error parsing response into JSON.");this.response=n;this.name="ParsingError"}},k=e=>{let t={Accept:"application/json","Content-Type":"application/json","x-publishable-key":e.publishableKey};return{fetch:(s,...p)=>c(void 0,[s,...p],function*(n,r={}){let u=x(d({},r),{headers:d(d({},r.headers),t)}),i=yield fetch(`${e.baseUrl}${n}`,u);if(i.status===404)throw new v;let o=yield i.json().catch(()=>c(void 0,null,function*(){throw new w(i)}));if(typeof o=="object"&&o!==null&&"message"in o&&typeof o.message=="string"){if(o.message===J)throw new g("You are not authenticated.");if(o.message===Y)throw new g;if("exception"in o)throw new f(o.message,[o.exception]);if("errors"in o)throw new f(o.message,Array.isArray(o.errors)?o.errors:[o.errors])}return o})}};var m="%c[inploi SDK]",y="color: #65BC67; font-weight: bold;",R={warn:(...e)=>console.warn(m,y,...e),error:(...e)=>console.error(m,y,...e),info:(...e)=>console.info(m,y,...e),log:(...e)=>console.log(m,y,...e)},O={info:()=>{},error:()=>{},log:()=>{},warn:()=>{}};function N({publishableKey:e,env:t,logger:n=R}){let r=k({baseUrl:P[t],publishableKey:e}),s=n===!1?O:n,p=T({apiClient:r,logger:s});return{register:i=>i({logger:s,apiClient:r,analytics:p}),analytics:p,apiClient:r}}typeof window.inploi!="object"&&(window.inploi={});window.process=window.process||{};window.process.env=window.process.env||{};window.process.env.NODE_ENV="production";window.inploi.initialiseSdk=N;})();
|
|
3
|
+
"use strict";(()=>{var be=Object.defineProperty,we=Object.defineProperties;var _e=Object.getOwnPropertyDescriptors;var ne=Object.getOwnPropertySymbols;var Se=Object.prototype.hasOwnProperty,ve=Object.prototype.propertyIsEnumerable;var oe=(e,r,n)=>r in e?be(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n,N=(e,r)=>{for(var n in r||(r={}))Se.call(r,n)&&oe(e,n,r[n]);if(ne)for(var n of ne(r))ve.call(r,n)&&oe(e,n,r[n]);return e},ie=(e,r)=>we(e,_e(r));var _=(e,r,n)=>new Promise((t,a)=>{var l=c=>{try{o(n.next(c))}catch(i){a(i)}},p=c=>{try{o(n.throw(c))}catch(i){a(i)}},o=c=>c.done?t(c.value):Promise.resolve(c.value).then(l,p);o((n=n.apply(e,r)).next())});function H(e,r){if(!e)throw new Error(r)}var Ge=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});var C="%c[inploi SDK]",D="color: #65BC67; font-weight: bold;",U={warn:(...e)=>console.warn(C,D,...e),error:(...e)=>console.error(C,D,...e),info:(...e)=>console.info(C,D,...e),log:(...e)=>console.log(C,D,...e)},$={info:()=>{},error:()=>{},log:()=>{},warn:()=>{}};var Te="Unauthenticated",xe="This action is unauthorized.",F=class extends Error{constructor(){super("Not found"),this.name="NotFoundError"}},E=class extends Error{constructor(r){super(r!=null?r:"You are not authorised to perform this action."),this.name="UnauthorisedError"}},S=class extends Error{constructor(n){super("Schema validation failed");this.issues=n;this.name="SchemaValidationError"}},I=class extends Error{constructor(n,t){super(n);this.name="ApiError",this.errors=t}},T=class extends Error{constructor(n){super("Error parsing response into JSON.");this.response=n;this.name="ParsingError"}};function J(e){if(typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"){if(e.message===Te)throw new E("You are not authenticated.");if(e.message===xe)throw new E;if("exception"in e)throw new I(e.message,[e.exception]);if("errors"in e)throw new I(e.message,Array.isArray(e.errors)?e.errors:[e.errors])}}var se=e=>{let r={Accept:"application/json","Content-Type":"application/json","x-publishable-key":e.publishableKey};return{fetch:(a,...l)=>_(void 0,[a,...l],function*(n,t={}){let p=ie(N({},t),{headers:N(N({},t.headers),r)}),o=yield fetch(`${e.baseUrl}${n}`,p);if(o.status===404)throw new F;let c=yield o.json().catch(()=>_(void 0,null,function*(){throw new T(o)}));return J(c),c})}};var Q="RFC3986",G={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},Pe="RFC1738";var Ee=Array.isArray,h=(()=>{let e=[];for(let r=0;r<256;++r)e.push("%"+((r<16?"0":"")+r.toString(16)).toUpperCase());return e})();var W=1024,Ie=(e,r,n,t,a)=>{if(e.length===0)return e;let l=e;if(typeof e=="symbol"?l=Symbol.prototype.toString.call(e):typeof e!="string"&&(l=String(e)),n==="iso-8859-1")return escape(l).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let p="";for(let o=0;o<l.length;o+=W){let c=l.length>=W?l.slice(o,o+W):l,i=[];for(let f=0;f<c.length;++f){let s=c.charCodeAt(f);if(s===45||s===46||s===95||s===126||s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||a===Pe&&(s===40||s===41)){i[i.length]=c.charAt(f);continue}if(s<128){i[i.length]=h[s];continue}if(s<2048){i[i.length]=h[192|s>>6]+h[128|s&63];continue}if(s<55296||s>=57344){i[i.length]=h[224|s>>12]+h[128|s>>6&63]+h[128|s&63];continue}f+=1,s=65536+((s&1023)<<10|c.charCodeAt(f)&1023),i[i.length]=h[240|s>>18]+h[128|s>>12&63]+h[128|s>>6&63]+h[128|s&63]}p+=i.join("")}return p};function ke(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function ae(e,r){if(Ee(e)){let n=[];for(let t=0;t<e.length;t+=1)n.push(r(e[t]));return n}return r(e)}var tr=Array.isArray;var Ae=Object.prototype.hasOwnProperty,le={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,r){return String(e)+"["+r+"]"},repeat(e){return String(e)}},b=Array.isArray,Re=Array.prototype.push,ce=function(e,r){Re.apply(e,b(r)?r:[r])},Oe=Date.prototype.toISOString,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ie,encodeValuesOnly:!1,format:Q,formatter:G[Q],indices:!1,serializeDate(e){return Oe.call(e)},skipNulls:!1,strictNullHandling:!1};function Le(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}var Y={};function de(e,r,n,t,a,l,p,o,c,i,f,s,g,w,m,x,R,V){let d=e,O=V,L=0,Z=!1;for(;(O=O.get(Y))!==void 0&&!Z;){let y=O.get(e);if(L+=1,typeof y!="undefined"){if(y===L)throw new RangeError("Cyclic object value");Z=!0}typeof O.get(Y)=="undefined"&&(L=0)}if(typeof i=="function"?d=i(r,d):d instanceof Date?d=g==null?void 0:g(d):n==="comma"&&b(d)&&(d=ae(d,function(y){return y instanceof Date?g==null?void 0:g(y):y})),d===null){if(l)return c&&!x?c(r,u.encoder,R,"key",w):r;d=""}if(Le(d)||ke(d)){if(c){let y=x?r:c(r,u.encoder,R,"key",w);return[(m==null?void 0:m(y))+"="+(m==null?void 0:m(c(d,u.encoder,R,"value",w)))]}return[(m==null?void 0:m(r))+"="+(m==null?void 0:m(String(d)))]}let q=[];if(typeof d=="undefined")return q;let P;if(n==="comma"&&b(d))x&&c&&(d=ae(d,c)),P=[{value:d.length>0?d.join(",")||null:void 0}];else if(b(i))P=i;else{let y=Object.keys(d);P=f?y.sort(f):y}let ee=o?String(r).replace(/\./g,"%2E"):String(r),j=t&&b(d)&&d.length===1?ee+"[]":ee;if(a&&b(d)&&d.length===0)return j+"[]";for(let y=0;y<P.length;++y){let v=P[y],re=typeof v=="object"&&typeof v.value!="undefined"?v.value:d[v];if(p&&re===null)continue;let B=s&&o?v.replace(/\./g,"%2E"):v,he=b(d)?typeof n=="function"?n(j,B):j:j+(s?"."+B:"["+B+"]");V.set(e,L);let te=new WeakMap;te.set(Y,V),ce(q,de(re,he,n,t,a,l,p,o,n==="comma"&&x&&b(d)?null:c,i,f,s,g,w,m,x,R,te))}return q}function je(e=u){if(typeof e.allowEmptyArrays!="undefined"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys!="undefined"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder!="undefined"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");let r=e.charset||u.charset;if(typeof e.charset!="undefined"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=Q;if(typeof e.format!="undefined"){if(!Ae.call(G,e.format))throw new TypeError("Unknown format option provided.");n=e.format}let t=G[n],a=u.filter;(typeof e.filter=="function"||b(e.filter))&&(a=e.filter);let l;if(e.arrayFormat&&e.arrayFormat in le?l=e.arrayFormat:"indices"in e?l=e.indices?"indices":"repeat":l=u.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let p=typeof e.allowDots=="undefined"?e.encodeDotInKeys?!0:u.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:u.addQueryPrefix,allowDots:p,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:l,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:u.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter=="undefined"?u.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:u.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:u.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:u.encodeValuesOnly,filter:a,format:n,formatter:t,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:u.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:u.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:u.strictNullHandling}}function pe(e,r={}){let n=e,t=je(r),a,l;typeof t.filter=="function"?(l=t.filter,n=l("",n)):b(t.filter)&&(l=t.filter,a=l);let p=[];if(typeof n!="object"||n===null)return"";let o=le[t.arrayFormat],c=o==="comma"&&t.commaRoundTrip;a||(a=Object.keys(n)),t.sort&&a.sort(t.sort);let i=new WeakMap;for(let g=0;g<a.length;++g){let w=a[g];t.skipNulls&&n[w]===null||ce(p,de(n[w],w,o,c,t.allowEmptyArrays,t.strictNullHandling,t.skipNulls,t.encodeDotInKeys,t.encode?t.encoder:null,t.filter,t.sort,t.allowDots,t.serializeDate,t.format,t.formatter,t.encodeValuesOnly,t.charset,i))}let f=p.join(t.delimiter),s=t.addQueryPrefix===!0?"?":"";return t.charsetSentinel&&(t.charset==="iso-8859-1"?s+="utf8=%26%2310003%3B&":s+="utf8=%E2%9C%93&"),f.length>0?s+f:""}var ue="1.15.0";var K={sandbox:"https://api.staging.inploi.com",production:"https://api.inploi.com",_internal_local:"http://api.test"},fe=ue;var k="isdk_session";function z(e,r){let n=e["~standard"].validate(r);if(n instanceof Promise)throw new TypeError("Async schema");if(n.issues)throw new S(n.issues);return n.value}function Ce(e,r){try{return{success:!0,output:z(e,r)}}catch(n){if(n instanceof S)return{success:!1,issues:n.issues};throw n}}var A=class{constructor(r){if(this.baseUrl=K[r.environment],this.headers=new Headers({"Content-Type":"application/json",Accept:"application/json"}),r.apiKey.type==="secret"){if(typeof window!="undefined")throw new Error("Secret key cannot be used in a browser environment");this.headers.set("x-secret-key",r.apiKey.key)}else this.headers.set("x-publishable-key",r.apiKey.key);this.logger=r.logger}request(r,n){return _(this,null,function*(){try{let t=new URL(this.baseUrl),a=r.pathname;if("params"in n&&n.params)for(let[i,f]of Object.entries(n.params))a=a.replace(`:${i}`,String(f));t.pathname=a,r.schema.searchParams&&(t.search=pe(z(r.schema.searchParams,"searchParams"in n?n.searchParams:{})));let l=r.schema.body?z(r.schema.body,"body"in n?n.body:{}):void 0,p=yield fetch(t.toString(),{method:r.method,body:l?JSON.stringify(l):void 0,headers:this.headers,signal:n.signal}),o=yield p.json().catch(i=>{throw this.logger.error(i),new T(p)}),c=Ce(r.schema.response,o);if(!c.success)throw J(o),new S(c.issues);return c.output}catch(t){throw t instanceof S?this.logger.error(t.message,t.issues):this.logger.error(t),t}})}};function M(){return{"~standard":{vendor:"inploi",version:1,validate:e=>({value:e})}}}var ye=e=>{let r=new Date;return r.setTime(r.getTime()+7*24*60*60*1e3),`${k}=${e};expires=${r.toUTCString()};path=/`},Fe=(e,r)=>{let n=e.get("session_id");if(r||n)return n;let t=sessionStorage.getItem(`${k}-session_id`);return typeof t=="string"?t:null},Ke=new RegExp(`${k}=([^;]+)`),me=e=>{let r=e?e.url:location.href,{searchParams:n}=new URL(r),t=n.get("anonymous_id"),a=Fe(n,typeof window=="undefined");if(t)return{anonymous_id:t,session_id:a};let l=e?e.headers.get("cookie"):document.cookie;if(l){let p=Ke.exec(l),o=p==null?void 0:p[1];return{anonymous_id:o!=null?o:null,session_id:a}}return{anonymous_id:t,session_id:a}},Me=e=>typeof e!="object"||e===null?null:{anonymous_id:"anonymous_id"in e&&typeof e.anonymous_id=="string"?e.anonymous_id:null,session_id:"session_id"in e&&typeof e.session_id=="string"?e.session_id:null},Ve=e=>e==="about:client"?"":e,qe={pathname:"/log",method:"POST",schema:{response:M(),searchParams:M()}},ge=({rpcClient:e,logger:r})=>({log:t=>_(void 0,null,function*(){H(t.request||typeof window!="undefined","Cannot log on the server without a request. Please pass a request to `log`.");let a="request"in t&&t.request?{href:t.request.url,referrer:Ve(t.request.referrer),title:""}:{href:location.href,referrer:document.referrer,title:document.title};try{let l={library:{name:"inploi-sdk",version:fe},page:a},p=me(t.request),o={anonymous_id:p.anonymous_id,session_id:p.session_id,event:t.event,sent_at:new Date().toISOString(),context:l,properties:t.properties,custom_properties:t.customProperties},c=yield e.request(qe,{searchParams:o}),i=Me(c);return i!=null&&i.anonymous_id&&(o.anonymous_id=i.anonymous_id),i!=null&&i.session_id&&(o.session_id=i.session_id),typeof window!="undefined"&&o.anonymous_id&&(o.session_id&&sessionStorage.setItem(`${k}-session_id`,o.session_id.toString()),document.cookie=ye(o.anonymous_id)),{success:!0,data:o}}catch(l){return r.error("Failed to send log to API. Inspect error response of `log` for more information."),{success:!1,error:l}}}),getHeaders:t=>{let a=new Headers;return t!=null&&t.anonymous_id&&a.append("Set-Cookie",ye(t.anonymous_id)),a},getSessionInfo:me});function X({publishableKey:e,env:r,logger:n=U}){let t=se({baseUrl:K[r],publishableKey:e}),a=n===!1?$:n,l=new A({environment:r,apiKey:{type:"publishable",key:e},logger:a}),p=ge({rpcClient:l,logger:a});return{register:c=>c({logger:a,apiClient:t,analytics:p,rpcClient:l}),analytics:p,apiClient:t}}typeof window.inploi!="object"&&(window.inploi={});window.process=window.process||{};window.process.env=window.process.env||{};window.process.env.NODE_ENV="production";window.inploi.initialiseSdk=X;})();
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ResponseObj } from '@inploi/core/common';
|
|
2
|
+
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
3
|
|
|
3
4
|
type LogMessage = (...data: any[]) => void;
|
|
4
5
|
type Logger = {
|
|
@@ -182,7 +183,7 @@ declare class ApiError extends Error {
|
|
|
182
183
|
errors: unknown[];
|
|
183
184
|
constructor(message: string, errors: unknown[]);
|
|
184
185
|
}
|
|
185
|
-
declare class
|
|
186
|
+
declare class JsonParsingError extends Error {
|
|
186
187
|
response?: Response | undefined;
|
|
187
188
|
constructor(response?: Response | undefined);
|
|
188
189
|
}
|
|
@@ -190,25 +191,109 @@ type ApiClient = {
|
|
|
190
191
|
fetch: (pathname: string, options?: RequestInit) => Promise<unknown>;
|
|
191
192
|
};
|
|
192
193
|
|
|
194
|
+
/**
|
|
195
|
+
* The environment the SDK should run in.
|
|
196
|
+
* - `production`: data will be stored and displayed on dashboards
|
|
197
|
+
* - `sandbox`: data will be stored temporarily and purged periodically
|
|
198
|
+
*/
|
|
199
|
+
type InploiSdkEnvironment = 'production' | 'sandbox';
|
|
200
|
+
|
|
201
|
+
type RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
202
|
+
/** Extract parameter names from a pathname string */
|
|
203
|
+
type ExtractParamNames<T extends string> = T extends `${infer _Before}:${infer Param}/${infer After}` ? Param | ExtractParamNames<`/${After}`> : T extends `${infer _Before}:${infer Param}` ? Param : never;
|
|
204
|
+
/** Create params object from parameter names */
|
|
205
|
+
type ExtractPathParams<T extends string> = string extends T ? Record<string, string | number> : ExtractParamNames<T> extends never ? Record<string, never> : {
|
|
206
|
+
[K in ExtractParamNames<T>]: string | number;
|
|
207
|
+
};
|
|
208
|
+
interface InploiRpcClientParams {
|
|
209
|
+
environment: InploiSdkEnvironment;
|
|
210
|
+
logger: Logger;
|
|
211
|
+
apiKey: {
|
|
212
|
+
/** Makes the API call with an x-secret-key header
|
|
213
|
+
* This will error if used in a browser environment.
|
|
214
|
+
*/
|
|
215
|
+
type: 'secret';
|
|
216
|
+
key: string;
|
|
217
|
+
} | {
|
|
218
|
+
/** Makes the API call with an x-publishable-key header
|
|
219
|
+
* This can be called in a browser or server environment.
|
|
220
|
+
*/
|
|
221
|
+
type: 'publishable';
|
|
222
|
+
key: string;
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
/** RPC client for making API calls to the Inploi API. */
|
|
226
|
+
declare class InploiRpcClient {
|
|
227
|
+
private baseUrl;
|
|
228
|
+
private headers;
|
|
229
|
+
private logger;
|
|
230
|
+
constructor(params: InploiRpcClientParams);
|
|
231
|
+
/** Fetches, parses and validates an API endpoint.
|
|
232
|
+
* Logs errors and throws them again so that the caller can handle them.
|
|
233
|
+
*
|
|
234
|
+
* @throws {JsonParsingError} - If the response is not valid JSON.
|
|
235
|
+
* @throws {SchemaValidationError} - If the searchParams, body or response does not match the schema.
|
|
236
|
+
* @throws {ApiError} - If the API responded with an error message.
|
|
237
|
+
* @throws {UnauthorisedError} - If the request is unauthorised either by missing key or unmet permissions.
|
|
238
|
+
* @throws {NotFoundError} - If the endpoint is not found.
|
|
239
|
+
* @throws {Error} - Another unhandled error.
|
|
240
|
+
*/
|
|
241
|
+
request<T extends RpcEndpoint>(endpoint: T, options: T extends RpcEndpoint<infer _, infer _TPathname, infer TPathParams, infer TSearch, infer TBody> ? GetSchemaValues<{
|
|
242
|
+
body: TBody;
|
|
243
|
+
searchParams: TSearch;
|
|
244
|
+
params: TPathParams;
|
|
245
|
+
}> & {
|
|
246
|
+
signal?: AbortSignal;
|
|
247
|
+
} : never): Promise<StandardSchemaV1.InferOutput<T["schema"]["response"]>>;
|
|
248
|
+
}
|
|
249
|
+
type GetSchemaValues<T extends {
|
|
250
|
+
searchParams: any;
|
|
251
|
+
body: any;
|
|
252
|
+
params?: any;
|
|
253
|
+
}> = {
|
|
254
|
+
[K in keyof T as T[K] extends never ? never : T[K] extends Record<string, never> ? never : K]: T[K] extends never ? never : T[K];
|
|
255
|
+
};
|
|
256
|
+
/**
|
|
257
|
+
* Typed but *not runtime validated* schema
|
|
258
|
+
* useful for type-checking the schema without bundling validation schemas
|
|
259
|
+
*/
|
|
260
|
+
declare function typed<T>(): StandardSchemaV1<T, T>;
|
|
261
|
+
interface RpcEndpoint<TMethod extends RequestMethod = RequestMethod, TPathname extends string = string, TPathParams = any, TSearch = any, TBody = any, TResponse = any> {
|
|
262
|
+
pathname: TPathname;
|
|
263
|
+
method: TMethod;
|
|
264
|
+
headers?: Headers;
|
|
265
|
+
schema: {
|
|
266
|
+
searchParams?: StandardSchemaV1<TSearch, TSearch>;
|
|
267
|
+
body?: StandardSchemaV1<TBody, TBody>;
|
|
268
|
+
response: StandardSchemaV1<TResponse, TResponse>;
|
|
269
|
+
};
|
|
270
|
+
/** Type-only property to store path parameter types */
|
|
271
|
+
readonly __pathParams?: TPathParams;
|
|
272
|
+
}
|
|
273
|
+
declare function endpoint<TMethod extends RequestMethod, TPathname extends string, TSearch extends StandardSchemaV1 | never = never, TBody extends StandardSchemaV1 | never = never, TResponse extends StandardSchemaV1 | never = never>(endpoint: {
|
|
274
|
+
pathname: TPathname;
|
|
275
|
+
method: TMethod;
|
|
276
|
+
headers?: Headers;
|
|
277
|
+
schema: {
|
|
278
|
+
searchParams?: TSearch;
|
|
279
|
+
body?: TBody;
|
|
280
|
+
response: TResponse;
|
|
281
|
+
};
|
|
282
|
+
}): RpcEndpoint<TMethod, TPathname, ExtractPathParams<TPathname>, StandardSchemaV1.InferInput<TSearch>, StandardSchemaV1.InferInput<TBody>, StandardSchemaV1.InferOutput<TResponse>>;
|
|
283
|
+
|
|
193
284
|
type PluginParams = {
|
|
194
285
|
apiClient: ApiClient;
|
|
195
286
|
logger: Logger;
|
|
196
287
|
};
|
|
197
288
|
type PluginDependencies = {
|
|
198
289
|
apiClient: ApiClient;
|
|
290
|
+
rpcClient: InploiRpcClient;
|
|
199
291
|
logger: Logger;
|
|
200
292
|
analytics: AnalyticsService;
|
|
201
293
|
};
|
|
202
294
|
type InploiSdkPlugin = (dependencies: PluginDependencies) => any;
|
|
203
295
|
declare const createPlugin: <T extends InploiSdkPlugin>(pluginFn: T) => T;
|
|
204
296
|
|
|
205
|
-
/**
|
|
206
|
-
* The environment the SDK should run in.
|
|
207
|
-
* - `production`: data will be stored and displayed on dashboards
|
|
208
|
-
* - `sandbox`: data will be stored temporarily and purged periodically
|
|
209
|
-
*/
|
|
210
|
-
type InploiSdkEnvironment = 'production' | 'sandbox';
|
|
211
|
-
|
|
212
297
|
type InitialiseInploiSdkParams = {
|
|
213
298
|
/** Your public API key for the inploi SDK. */
|
|
214
299
|
publishableKey: string;
|
|
@@ -228,4 +313,4 @@ declare function initialiseSdk({ publishableKey, env, logger }: InitialiseInploi
|
|
|
228
313
|
};
|
|
229
314
|
type InploiSdk = ReturnType<typeof initialiseSdk>;
|
|
230
315
|
|
|
231
|
-
export { AnalyticsLogEvent, AnalyticsService, ApiClient, ApiError, InitialiseInploiSdkParams, InploiSdk, InploiSdkEnvironment, InploiSdkPlugin, Logger, NotFoundError, ParsingError, PluginParams, UnauthorisedError, createPlugin, initialiseSdk, inploiBrandedLogger, noLogging };
|
|
316
|
+
export { AnalyticsLogEvent, AnalyticsService, ApiClient, ApiError, InitialiseInploiSdkParams, InploiRpcClient, InploiSdk, InploiSdkEnvironment, InploiSdkPlugin, Logger, NotFoundError, JsonParsingError as ParsingError, PluginParams, RpcEndpoint, UnauthorisedError, createPlugin, endpoint, initialiseSdk, inploiBrandedLogger, noLogging, typed };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ResponseObj } from '@inploi/core/common';
|
|
2
|
+
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
3
|
|
|
3
4
|
type LogMessage = (...data: any[]) => void;
|
|
4
5
|
type Logger = {
|
|
@@ -182,7 +183,7 @@ declare class ApiError extends Error {
|
|
|
182
183
|
errors: unknown[];
|
|
183
184
|
constructor(message: string, errors: unknown[]);
|
|
184
185
|
}
|
|
185
|
-
declare class
|
|
186
|
+
declare class JsonParsingError extends Error {
|
|
186
187
|
response?: Response | undefined;
|
|
187
188
|
constructor(response?: Response | undefined);
|
|
188
189
|
}
|
|
@@ -190,25 +191,109 @@ type ApiClient = {
|
|
|
190
191
|
fetch: (pathname: string, options?: RequestInit) => Promise<unknown>;
|
|
191
192
|
};
|
|
192
193
|
|
|
194
|
+
/**
|
|
195
|
+
* The environment the SDK should run in.
|
|
196
|
+
* - `production`: data will be stored and displayed on dashboards
|
|
197
|
+
* - `sandbox`: data will be stored temporarily and purged periodically
|
|
198
|
+
*/
|
|
199
|
+
type InploiSdkEnvironment = 'production' | 'sandbox';
|
|
200
|
+
|
|
201
|
+
type RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
202
|
+
/** Extract parameter names from a pathname string */
|
|
203
|
+
type ExtractParamNames<T extends string> = T extends `${infer _Before}:${infer Param}/${infer After}` ? Param | ExtractParamNames<`/${After}`> : T extends `${infer _Before}:${infer Param}` ? Param : never;
|
|
204
|
+
/** Create params object from parameter names */
|
|
205
|
+
type ExtractPathParams<T extends string> = string extends T ? Record<string, string | number> : ExtractParamNames<T> extends never ? Record<string, never> : {
|
|
206
|
+
[K in ExtractParamNames<T>]: string | number;
|
|
207
|
+
};
|
|
208
|
+
interface InploiRpcClientParams {
|
|
209
|
+
environment: InploiSdkEnvironment;
|
|
210
|
+
logger: Logger;
|
|
211
|
+
apiKey: {
|
|
212
|
+
/** Makes the API call with an x-secret-key header
|
|
213
|
+
* This will error if used in a browser environment.
|
|
214
|
+
*/
|
|
215
|
+
type: 'secret';
|
|
216
|
+
key: string;
|
|
217
|
+
} | {
|
|
218
|
+
/** Makes the API call with an x-publishable-key header
|
|
219
|
+
* This can be called in a browser or server environment.
|
|
220
|
+
*/
|
|
221
|
+
type: 'publishable';
|
|
222
|
+
key: string;
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
/** RPC client for making API calls to the Inploi API. */
|
|
226
|
+
declare class InploiRpcClient {
|
|
227
|
+
private baseUrl;
|
|
228
|
+
private headers;
|
|
229
|
+
private logger;
|
|
230
|
+
constructor(params: InploiRpcClientParams);
|
|
231
|
+
/** Fetches, parses and validates an API endpoint.
|
|
232
|
+
* Logs errors and throws them again so that the caller can handle them.
|
|
233
|
+
*
|
|
234
|
+
* @throws {JsonParsingError} - If the response is not valid JSON.
|
|
235
|
+
* @throws {SchemaValidationError} - If the searchParams, body or response does not match the schema.
|
|
236
|
+
* @throws {ApiError} - If the API responded with an error message.
|
|
237
|
+
* @throws {UnauthorisedError} - If the request is unauthorised either by missing key or unmet permissions.
|
|
238
|
+
* @throws {NotFoundError} - If the endpoint is not found.
|
|
239
|
+
* @throws {Error} - Another unhandled error.
|
|
240
|
+
*/
|
|
241
|
+
request<T extends RpcEndpoint>(endpoint: T, options: T extends RpcEndpoint<infer _, infer _TPathname, infer TPathParams, infer TSearch, infer TBody> ? GetSchemaValues<{
|
|
242
|
+
body: TBody;
|
|
243
|
+
searchParams: TSearch;
|
|
244
|
+
params: TPathParams;
|
|
245
|
+
}> & {
|
|
246
|
+
signal?: AbortSignal;
|
|
247
|
+
} : never): Promise<StandardSchemaV1.InferOutput<T["schema"]["response"]>>;
|
|
248
|
+
}
|
|
249
|
+
type GetSchemaValues<T extends {
|
|
250
|
+
searchParams: any;
|
|
251
|
+
body: any;
|
|
252
|
+
params?: any;
|
|
253
|
+
}> = {
|
|
254
|
+
[K in keyof T as T[K] extends never ? never : T[K] extends Record<string, never> ? never : K]: T[K] extends never ? never : T[K];
|
|
255
|
+
};
|
|
256
|
+
/**
|
|
257
|
+
* Typed but *not runtime validated* schema
|
|
258
|
+
* useful for type-checking the schema without bundling validation schemas
|
|
259
|
+
*/
|
|
260
|
+
declare function typed<T>(): StandardSchemaV1<T, T>;
|
|
261
|
+
interface RpcEndpoint<TMethod extends RequestMethod = RequestMethod, TPathname extends string = string, TPathParams = any, TSearch = any, TBody = any, TResponse = any> {
|
|
262
|
+
pathname: TPathname;
|
|
263
|
+
method: TMethod;
|
|
264
|
+
headers?: Headers;
|
|
265
|
+
schema: {
|
|
266
|
+
searchParams?: StandardSchemaV1<TSearch, TSearch>;
|
|
267
|
+
body?: StandardSchemaV1<TBody, TBody>;
|
|
268
|
+
response: StandardSchemaV1<TResponse, TResponse>;
|
|
269
|
+
};
|
|
270
|
+
/** Type-only property to store path parameter types */
|
|
271
|
+
readonly __pathParams?: TPathParams;
|
|
272
|
+
}
|
|
273
|
+
declare function endpoint<TMethod extends RequestMethod, TPathname extends string, TSearch extends StandardSchemaV1 | never = never, TBody extends StandardSchemaV1 | never = never, TResponse extends StandardSchemaV1 | never = never>(endpoint: {
|
|
274
|
+
pathname: TPathname;
|
|
275
|
+
method: TMethod;
|
|
276
|
+
headers?: Headers;
|
|
277
|
+
schema: {
|
|
278
|
+
searchParams?: TSearch;
|
|
279
|
+
body?: TBody;
|
|
280
|
+
response: TResponse;
|
|
281
|
+
};
|
|
282
|
+
}): RpcEndpoint<TMethod, TPathname, ExtractPathParams<TPathname>, StandardSchemaV1.InferInput<TSearch>, StandardSchemaV1.InferInput<TBody>, StandardSchemaV1.InferOutput<TResponse>>;
|
|
283
|
+
|
|
193
284
|
type PluginParams = {
|
|
194
285
|
apiClient: ApiClient;
|
|
195
286
|
logger: Logger;
|
|
196
287
|
};
|
|
197
288
|
type PluginDependencies = {
|
|
198
289
|
apiClient: ApiClient;
|
|
290
|
+
rpcClient: InploiRpcClient;
|
|
199
291
|
logger: Logger;
|
|
200
292
|
analytics: AnalyticsService;
|
|
201
293
|
};
|
|
202
294
|
type InploiSdkPlugin = (dependencies: PluginDependencies) => any;
|
|
203
295
|
declare const createPlugin: <T extends InploiSdkPlugin>(pluginFn: T) => T;
|
|
204
296
|
|
|
205
|
-
/**
|
|
206
|
-
* The environment the SDK should run in.
|
|
207
|
-
* - `production`: data will be stored and displayed on dashboards
|
|
208
|
-
* - `sandbox`: data will be stored temporarily and purged periodically
|
|
209
|
-
*/
|
|
210
|
-
type InploiSdkEnvironment = 'production' | 'sandbox';
|
|
211
|
-
|
|
212
297
|
type InitialiseInploiSdkParams = {
|
|
213
298
|
/** Your public API key for the inploi SDK. */
|
|
214
299
|
publishableKey: string;
|
|
@@ -228,4 +313,4 @@ declare function initialiseSdk({ publishableKey, env, logger }: InitialiseInploi
|
|
|
228
313
|
};
|
|
229
314
|
type InploiSdk = ReturnType<typeof initialiseSdk>;
|
|
230
315
|
|
|
231
|
-
export { AnalyticsLogEvent, AnalyticsService, ApiClient, ApiError, InitialiseInploiSdkParams, InploiSdk, InploiSdkEnvironment, InploiSdkPlugin, Logger, NotFoundError, ParsingError, PluginParams, UnauthorisedError, createPlugin, initialiseSdk, inploiBrandedLogger, noLogging };
|
|
316
|
+
export { AnalyticsLogEvent, AnalyticsService, ApiClient, ApiError, InitialiseInploiSdkParams, InploiRpcClient, InploiSdk, InploiSdkEnvironment, InploiSdkPlugin, Logger, NotFoundError, JsonParsingError as ParsingError, PluginParams, RpcEndpoint, UnauthorisedError, createPlugin, endpoint, initialiseSdk, inploiBrandedLogger, noLogging, typed };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var P=Object.defineProperty,j=Object.defineProperties,H=Object.getOwnPropertyDescriptor,J=Object.getOwnPropertyDescriptors,Y=Object.getOwnPropertyNames,A=Object.getOwnPropertySymbols;var C=Object.prototype.hasOwnProperty,W=Object.prototype.propertyIsEnumerable;var L=(e,r,t)=>r in e?P(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t,T=(e,r)=>{for(var t in r||(r={}))C.call(r,t)&&L(e,t,r[t]);if(A)for(var t of A(r))W.call(r,t)&&L(e,t,r[t]);return e},O=(e,r)=>j(e,J(r));var z=(e,r)=>{for(var t in r)P(e,t,{get:r[t],enumerable:!0})},G=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of Y(r))!C.call(e,o)&&o!==t&&P(e,o,{get:()=>r[o],enumerable:!(n=H(r,o))||n.enumerable});return e};var X=e=>G(P({},"__esModule",{value:!0}),e);var d=(e,r,t)=>new Promise((n,o)=>{var c=i=>{try{s(t.next(i))}catch(p){o(p)}},a=i=>{try{s(t.throw(i))}catch(p){o(p)}},s=i=>i.done?n(i.value):Promise.resolve(i.value).then(c,a);s((t=t.apply(e,r)).next())});var ae={};z(ae,{ApiError:()=>g,InploiRpcClient:()=>f,NotFoundError:()=>y,ParsingError:()=>l,UnauthorisedError:()=>m,createPlugin:()=>N,endpoint:()=>k,initialiseSdk:()=>D,inploiBrandedLogger:()=>v,noLogging:()=>b,typed:()=>_});module.exports=X(ae);var x="%c[inploi SDK]",S="color: #65BC67; font-weight: bold;",v={warn:(...e)=>console.warn(x,S,...e),error:(...e)=>console.error(x,S,...e),info:(...e)=>console.info(x,S,...e),log:(...e)=>console.log(x,S,...e)},b={info:()=>{},error:()=>{},log:()=>{},warn:()=>{}};var N=e=>e;var Z="Unauthenticated",Q="This action is unauthorized.",y=class extends Error{constructor(){super("Not found"),this.name="NotFoundError"}},m=class extends Error{constructor(r){super(r!=null?r:"You are not authorised to perform this action."),this.name="UnauthorisedError"}},u=class extends Error{constructor(t){super("Schema validation failed");this.issues=t;this.name="SchemaValidationError"}},g=class extends Error{constructor(t,n){super(t);this.name="ApiError",this.errors=n}},l=class extends Error{constructor(t){super("Error parsing response into JSON.");this.response=t;this.name="ParsingError"}};function E(e){if(typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"){if(e.message===Z)throw new m("You are not authenticated.");if(e.message===Q)throw new m;if("exception"in e)throw new g(e.message,[e.exception]);if("errors"in e)throw new g(e.message,Array.isArray(e.errors)?e.errors:[e.errors])}}var M=e=>{let r={Accept:"application/json","Content-Type":"application/json","x-publishable-key":e.publishableKey};return{fetch:(o,...c)=>d(void 0,[o,...c],function*(t,n={}){let a=O(T({},n),{headers:T(T({},n.headers),r)}),s=yield fetch(`${e.baseUrl}${t}`,a);if(s.status===404)throw new y;let i=yield s.json().catch(()=>d(void 0,null,function*(){throw new l(s)}));return E(i),i})}};function I(e,r){if(!e)throw new Error(r)}var Te=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});var V="1.15.0";var w={sandbox:"https://api.staging.inploi.com",production:"https://api.inploi.com",_internal_local:"http://api.test"},q=V;var h="isdk_session";var F=e=>{let r=new Date;return r.setTime(r.getTime()+7*24*60*60*1e3),`${h}=${e};expires=${r.toUTCString()};path=/`},re=(e,r)=>{let t=e.get("session_id");if(r||t)return t;let n=sessionStorage.getItem(`${h}-session_id`);return typeof n=="string"?n:null},te=new RegExp(`${h}=([^;]+)`),B=e=>{let r=e?e.url:location.href,{searchParams:t}=new URL(r),n=t.get("anonymous_id"),o=re(t,typeof window=="undefined");if(n)return{anonymous_id:n,session_id:o};let c=e?e.headers.get("cookie"):document.cookie;if(c){let a=te.exec(c),s=a==null?void 0:a[1];return{anonymous_id:s!=null?s:null,session_id:o}}return{anonymous_id:n,session_id:o}},ne=e=>typeof e!="object"||e===null?null:{anonymous_id:"anonymous_id"in e&&typeof e.anonymous_id=="string"?e.anonymous_id:null,session_id:"session_id"in e&&typeof e.session_id=="string"?e.session_id:null},oe=e=>e==="about:client"?"":e,se={pathname:"/log",method:"POST",schema:{response:_(),searchParams:_()}},K=({rpcClient:e,logger:r})=>({log:n=>d(void 0,null,function*(){I(n.request||typeof window!="undefined","Cannot log on the server without a request. Please pass a request to `log`.");let o="request"in n&&n.request?{href:n.request.url,referrer:oe(n.request.referrer),title:""}:{href:location.href,referrer:document.referrer,title:document.title};try{let c={library:{name:"inploi-sdk",version:q},page:o},a=B(n.request),s={anonymous_id:a.anonymous_id,session_id:a.session_id,event:n.event,sent_at:new Date().toISOString(),context:c,properties:n.properties,custom_properties:n.customProperties},i=yield e.request(se,{searchParams:s}),p=ne(i);return p!=null&&p.anonymous_id&&(s.anonymous_id=p.anonymous_id),p!=null&&p.session_id&&(s.session_id=p.session_id),typeof window!="undefined"&&s.anonymous_id&&(s.session_id&&sessionStorage.setItem(`${h}-session_id`,s.session_id.toString()),document.cookie=F(s.anonymous_id)),{success:!0,data:s}}catch(c){return r.error("Failed to send log to API. Inspect error response of `log` for more information."),{success:!1,error:c}}}),getHeaders:n=>{let o=new Headers;return n!=null&&n.anonymous_id&&o.append("Set-Cookie",F(n.anonymous_id)),o},getSessionInfo:B});var U=require("neoqs");function R(e,r){let t=e["~standard"].validate(r);if(t instanceof Promise)throw new TypeError("Async schema");if(t.issues)throw new u(t.issues);return t.value}function ie(e,r){try{return{success:!0,output:R(e,r)}}catch(t){if(t instanceof u)return{success:!1,issues:t.issues};throw t}}var f=class{constructor(r){if(this.baseUrl=w[r.environment],this.headers=new Headers({"Content-Type":"application/json",Accept:"application/json"}),r.apiKey.type==="secret"){if(typeof window!="undefined")throw new Error("Secret key cannot be used in a browser environment");this.headers.set("x-secret-key",r.apiKey.key)}else this.headers.set("x-publishable-key",r.apiKey.key);this.logger=r.logger}request(r,t){return d(this,null,function*(){try{let n=new URL(this.baseUrl),o=r.pathname;if("params"in t&&t.params)for(let[p,$]of Object.entries(t.params))o=o.replace(`:${p}`,String($));n.pathname=o,r.schema.searchParams&&(n.search=(0,U.stringify)(R(r.schema.searchParams,"searchParams"in t?t.searchParams:{})));let c=r.schema.body?R(r.schema.body,"body"in t?t.body:{}):void 0,a=yield fetch(n.toString(),{method:r.method,body:c?JSON.stringify(c):void 0,headers:this.headers,signal:t.signal}),s=yield a.json().catch(p=>{throw this.logger.error(p),new l(a)}),i=ie(r.schema.response,s);if(!i.success)throw E(s),new u(i.issues);return i.output}catch(n){throw n instanceof u?this.logger.error(n.message,n.issues):this.logger.error(n),n}})}};function _(){return{"~standard":{vendor:"inploi",version:1,validate:e=>({value:e})}}}function k(e){return e}function D({publishableKey:e,env:r,logger:t=v}){let n=M({baseUrl:w[r],publishableKey:e}),o=t===!1?b:t,c=new f({environment:r,apiKey:{type:"publishable",key:e},logger:o}),a=K({rpcClient:c,logger:o});return{register:i=>i({logger:o,apiClient:n,analytics:a,rpcClient:c}),analytics:a,apiClient:n}}0&&(module.exports={ApiError,InploiRpcClient,NotFoundError,ParsingError,UnauthorisedError,createPlugin,endpoint,initialiseSdk,inploiBrandedLogger,noLogging,typed});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/sdk.logger.ts","../src/sdk.plugins.ts","../src/sdk.api.ts","../../core/src/common/common.utils.ts","../../core/src/common/common.currency.ts","../../core/src/common/common.datetime.ts","../package.json","../src/sdk.constants.ts","../src/sdk.analytics.ts","../src/sdk.ts"],"sourcesContent":["export { inploiBrandedLogger, noLogging } from './sdk.logger';\nexport type { Logger } from './sdk.logger';\n\nexport type { PluginParams, InploiSdkPlugin } from './sdk.plugins';\nexport { createPlugin } from './sdk.plugins';\n\nexport type { InploiSdkEnvironment } from './sdk.constants';\n\nexport type { ApiClient } from './sdk.api';\nexport { ApiError, NotFoundError, ParsingError, UnauthorisedError } from './sdk.api';\n\nexport { initialiseSdk } from './sdk';\nexport type { InitialiseInploiSdkParams, InploiSdk } from './sdk';\n\nexport type { AnalyticsService, AnalyticsLogEvent } from './sdk.analytics';\n","export const CONSOLE_PREFIX = '%c[inploi SDK]';\nexport const CONSOLE_STYLE = 'color: #65BC67; font-weight: bold;';\n\ntype LogMessage = (...data: any[]) => void;\nexport type Logger = {\n\twarn: LogMessage;\n\terror: LogMessage;\n\tinfo: LogMessage;\n\tlog: LogMessage;\n};\n\nexport const inploiBrandedLogger: Logger = {\n\twarn: (...args) => console.warn(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\terror: (...args) => console.error(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\tinfo: (...args) => console.info(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\tlog: (...args) => console.log(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n};\n\nexport const noLogging: Logger = { info: () => void 0, error: () => void 0, log: () => void 0, warn: () => void 0 };\n","import { AnalyticsService } from './sdk.analytics';\nimport { ApiClient } from './sdk.api';\nimport { Logger } from './sdk.logger';\n\nexport type PluginParams = {\n\tapiClient: ApiClient;\n\tlogger: Logger;\n};\n\nexport type Plugin<T extends string, P extends Record<string, unknown>> = {\n\tpluginName: T;\n\tpure_createActions: (params: PluginParams) => P;\n};\n\ntype PluginDependencies = {\n\tapiClient: ApiClient;\n\tlogger: Logger;\n\tanalytics: AnalyticsService;\n};\n\nexport type InploiSdkPlugin = (dependencies: PluginDependencies) => any;\n\nexport const createPlugin = <T extends InploiSdkPlugin>(pluginFn: T) => pluginFn;\n","export const unauthenticatedMessage = 'Unauthenticated';\nexport const unauthorisedMessage = 'This action is unauthorized.';\n\nexport class NotFoundError extends Error {\n\tconstructor() {\n\t\tsuper('Not found');\n\t\tthis.name = 'NotFoundError';\n\t}\n}\n\nexport class UnauthorisedError extends Error {\n\tconstructor(message?: string) {\n\t\tsuper(message ?? 'You are not authorised to perform this action.');\n\t\tthis.name = 'UnauthorisedError';\n\t}\n}\n\nexport class ApiError extends Error {\n\terrors: unknown[];\n\tconstructor(message: string, errors: unknown[]) {\n\t\tsuper(`API error: “${message}”`);\n\t\tthis.name = 'ApiError';\n\t\tthis.errors = errors;\n\t}\n}\n\nexport class ParsingError extends Error {\n\tconstructor(public response?: Response) {\n\t\tsuper('Error parsing response into JSON.');\n\t\tthis.name = 'ParsingError';\n\t}\n}\n\nexport type ApiClient = {\n\tfetch: (pathname: string, options?: RequestInit) => Promise<unknown>;\n};\n\nexport const createApiClient = (params: { baseUrl: string; publishableKey: string }): ApiClient => {\n\tconst defaultHeaders: HeadersInit = {\n\t\tAccept: 'application/json',\n\t\t'Content-Type': 'application/json',\n\t\t'x-publishable-key': params.publishableKey,\n\t};\n\n\treturn {\n\t\t/** Fetches from a pathname with a pre-established base path.\n\t\t * Parses received output as JSON, and throw if one of the common error messages is received.\n\t\t */\n\t\tfetch: async (pathname, options = {}) => {\n\t\t\tconst init = { ...options, headers: { ...options.headers, ...defaultHeaders } };\n\t\t\tconst response = await fetch(`${params.baseUrl}${pathname}`, init);\n\t\t\tif (response.status === 404) throw new NotFoundError();\n\n\t\t\tconst json = await response.json().catch(async () => {\n\t\t\t\tthrow new ParsingError(response);\n\t\t\t});\n\n\t\t\tif (typeof json === 'object' && json !== null && 'message' in json && typeof json.message === 'string') {\n\t\t\t\tif (json.message === unauthenticatedMessage) {\n\t\t\t\t\tthrow new UnauthorisedError('You are not authenticated.');\n\t\t\t\t}\n\t\t\t\tif (json.message === unauthorisedMessage) {\n\t\t\t\t\tthrow new UnauthorisedError();\n\t\t\t\t}\n\t\t\t\tif ('exception' in json) {\n\t\t\t\t\tthrow new ApiError(json.message, [json.exception]);\n\t\t\t\t}\n\t\t\t\tif ('errors' in json) {\n\t\t\t\t\tthrow new ApiError(json.message, Array.isArray(json.errors) ? json.errors : [json.errors]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// We’re assuming no other exceptions have happened.\n\t\t\treturn json;\n\t\t},\n\t};\n};\n","export const exhaustive = (value: never) => {\n\tthrow new Error(`Unhandled discriminated union member: ${JSON.stringify(value)}`);\n};\n\nexport function invariant(condition: any, message?: string): asserts condition {\n\tif (condition) {\n\t\treturn;\n\t}\n\n\tthrow new Error(message);\n}\n\nexport const uniqueOrThrow = <T>(array: T[]) => {\n\tconst uniqueValues = new Set(array);\n\n\tif (array.length !== uniqueValues.size) {\n\t\tthrow new Error('Duplicate values found');\n\t}\n\treturn true;\n};\n\nexport const uniqueByPropertyOrThrow =\n\t<T extends PropertyKey>(propertyKey: T) =>\n\t(array: { [K in T]: any }[]) => {\n\t\tconst values = array.map(item => item[propertyKey]);\n\t\tconst uniqueValues = new Set(values);\n\n\t\tif (values.length !== uniqueValues.size) {\n\t\t\tthrow new Error(`Duplicate values found for property: ${propertyKey.toString()}`);\n\t\t}\n\t\treturn true;\n\t};\n\n/**\n * A destructive way to ensure an object has a property.\n * This is useful when working with unknowns.\n */\nexport function hasProp<K extends PropertyKey>(data: object, prop: K): data is Record<K, unknown> {\n\treturn prop in data;\n}\n\n/**\n * A sort of type-safe way to check whether a key exists in an object.\n */\nexport function isKeyInObj<O extends Record<string, unknown>>(key: PropertyKey, obj: O): key is keyof O {\n\treturn key in obj;\n}\n","type TFunction = (key: 'competitive' | 'invalid_salary' | 'from' | 'up_to') => string;\n\ninterface SalaryParams {\n\tpay: string | null;\n\tpay_min: string | null;\n\tpay_mask: boolean;\n\tpay_max: string | null;\n\tpay_type: 'ANNUALLY' | 'HOURLY' | 'MONTHLY' | 'WEEKLY' | 'DAILY' | null;\n\tpay_currency: string;\n\tpay_display: boolean;\n}\n\nconst payPeriods: Record<NonNullable<SalaryParams['pay_type']>, string> = {\n\tANNUALLY: 'per year',\n\tDAILY: 'per day',\n\tHOURLY: 'per hour',\n\tMONTHLY: 'per month',\n\tWEEKLY: 'per week',\n};\n\nexport const getSalaryAsText = (params: {\n\tsalary: SalaryParams;\n\tconfig: { locales: string | string[] | undefined };\n\tt?: TFunction;\n}) => {\n\tconst { salary, config, t = s => s } = params;\n\tconst numberFormatter = new Intl.NumberFormat(config.locales, {\n\t\tstyle: 'currency',\n\t\tcurrency: salary.pay_currency,\n\t\t// @ts-expect-error - CI/CD is not happy with this, though locally it works\n\t\ttrailingZeroDisplay: 'stripIfInteger',\n\t});\n\tif (salary.pay_display === false) return undefined;\n\tif (salary.pay_mask) return t('competitive');\n\n\tif (salary.pay_max && Number.isNaN(+salary.pay_max)) return t('invalid_salary');\n\tif (salary.pay_min && Number.isNaN(+salary.pay_min)) return t('invalid_salary');\n\tif (salary.pay && Number.isNaN(+salary.pay)) return t('invalid_salary');\n\n\tconst period = salary.pay_type && salary.pay_type in payPeriods ? payPeriods[salary.pay_type] : undefined;\n\n\tif (salary.pay) return [numberFormatter.format(+salary.pay), period].filter(Boolean).join(' ');\n\n\tif (salary.pay_max && salary.pay_min)\n\t\treturn [numberFormatter.formatRange(+salary.pay_min, +salary.pay_max), period].filter(Boolean).join(' ') || '';\n\n\tif (salary.pay_max)\n\t\treturn `${t('up_to')} ${[numberFormatter.format(+salary.pay_max), period].filter(Boolean).join(' ')}`;\n\tif (salary.pay_min)\n\t\treturn `${t('from')} ${[numberFormatter.format(+salary.pay_min), period].filter(Boolean).join(' ')}`;\n\treturn t('invalid_salary');\n};\n","type TFunction = (key: 'today' | 'over_30_days_ago' | 'in_over_30_days') => string;\n\ntype Params = {\n\tfrom?: Date;\n\tto: string | number | Date;\n\tformatter?: Intl.RelativeTimeFormat;\n\tt?: TFunction;\n};\n\nconst DEFAULT_FORMATTER = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });\n/** From a date, calculates the relative time difference from now */\nexport const getRelativeTimeDifference = ({\n\tfrom = new Date(),\n\tto,\n\tformatter = DEFAULT_FORMATTER,\n\tt = s => s,\n}: Params) => {\n\tconst then = to instanceof Date ? to : new Date(to);\n\tconst diff = then.getTime() - from.getTime();\n\n\tconst diffIn = {\n\t\tdays: Math.round(diff / 1000 / 60 / 60 / 24),\n\t\tmonths: Math.round(diff / 1000 / 60 / 60 / 24 / 30),\n\t};\n\n\tif (diffIn.days === 0) return t('today');\n\tif (Math.abs(diffIn.days) < 30) return formatter.format(diffIn.days, 'days');\n\tif (Math.abs(diffIn.days) < 3) return formatter.format(diffIn.months, 'months');\n\treturn diffIn.months < 0 ? t('over_30_days_ago') : t('in_over_30_days');\n};\n","{\n\t\"name\": \"@inploi/sdk\",\n\t\"version\": \"1.14.13\",\n\t\"main\": \"dist/index.js\",\n\t\"types\": \"dist/index.d.ts\",\n\t\"license\": \"MIT\",\n\t\"files\": [\n\t\t\"/dist\",\n\t\t\"/cdn\"\n\t],\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"require\": \"./dist/index.js\",\n\t\t\t\"import\": \"./dist/index.mjs\",\n\t\t\t\"types\": \"./dist/index.d.ts\"\n\t\t}\n\t},\n\t\"scripts\": {\n\t\t\"build:npm\": \"tsup --dts --dts-resolve\",\n\t\t\"build:cdn\": \"tsup --config tsup.cdn.config.ts\",\n\t\t\"build\": \"concurrently 'pnpm run build:npm' 'pnpm run build:cdn'\",\n\t\t\"dev\": \"tsup --watch --config tsup.cdn.config.ts\",\n\t\t\"check\": \"eslint src --fix --max-warnings 0 && tsc\",\n\t\t\"test\": \"bun test\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@happy-dom/global-registrator\": \"^13.6.2\",\n\t\t\"@inploi/core\": \"workspace:*\",\n\t\t\"@total-typescript/ts-reset\": \"^0.5.1\",\n\t\t\"@types/bun\": \"^1.2.5\",\n\t\t\"@types/react\": \"^18.2.33\",\n\t\t\"@types/react-dom\": \"^18.2.14\",\n\t\t\"autoprefixer\": \"^10.4.16\",\n\t\t\"eslint\": \"^7.32.0\",\n\t\t\"eslint-config-custom\": \"workspace:*\",\n\t\t\"happy-dom\": \"^12.6.0\",\n\t\t\"ts-toolbelt\": \"^9.6.0\",\n\t\t\"concurrently\": \"9.1.2\",\n\t\t\"tsconfig\": \"workspace:*\",\n\t\t\"tsup\": \"^7.2.0\"\n\t}\n}\n","import { version } from '../package.json';\n\n/**\n * The environment the SDK should run in.\n * - `production`: data will be stored and displayed on dashboards\n * - `sandbox`: data will be stored temporarily and purged periodically\n */\nexport type InploiSdkEnvironment = 'production' | 'sandbox';\n\nexport const ENV_TO_API_URL: Record<InploiSdkEnvironment, string> = {\n\tsandbox: 'https://api.staging.inploi.com',\n\tproduction: 'https://api.inploi.com',\n\t// @ts-expect-error - local test environment\n\t_internal_local: 'http://api.test',\n};\n\nexport const ANALYTICS_VERSION = version;\n\nexport const LOG_PATHNAME = '/log';\n\nexport const ANALYTICS_COOKIE_NAME = 'isdk_session';\n","import type { ResponseObj } from '@inploi/core/common';\nimport { invariant } from '@inploi/core/common';\n\nimport { ApiClient, Logger } from '.';\nimport { ANALYTICS_COOKIE_NAME, ANALYTICS_VERSION, LOG_PATHNAME } from './sdk.constants';\n\nconst formatCookie = (value: string) => {\n\tconst now = new Date();\n\tnow.setTime(now.getTime() + 7 * 24 * 60 * 60 * 1000); // 7 days expiration\n\n\treturn `${ANALYTICS_COOKIE_NAME}=${value};expires=${now.toUTCString()};path=/`;\n};\n\ntype FlowProperties = { flow_id: string; flow_version: number; flow_session_id: string; flow_build: number };\n\ntype JobProperties = {\n\tid: string;\n\tid_type: 'internal' | 'external';\n};\n\ntype AnalyticsLogParams =\n\t| {\n\t\t\tevent: 'VIEW_JOB';\n\t\t\tproperties: { job: JobProperties };\n\t }\n\t| {\n\t\t\tevent: 'FLOW_REDIRECT';\n\t\t\tproperties: { href: string; job: JobProperties | undefined } & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_START' | 'FLOW_END';\n\t\t\tproperties: { job: JobProperties | undefined } & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_NODE';\n\t\t\tproperties: {\n\t\t\t\t/** Increments by 1 per node interpreted */\n\t\t\t\tsequence: number;\n\t\t\t\tfrom_node_id: string;\n\t\t\t\tto_node_id: string;\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t} & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_SUBMIT';\n\t\t\tproperties: {\n\t\t\t\tservice: string;\n\t\t\t\tresponse: {\n\t\t\t\t\tstatus: number;\n\t\t\t\t\tpayload: unknown;\n\t\t\t\t};\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t} & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'SUBMIT_FORM' | 'VIEW_PAGE';\n\t\t\tproperties?: {\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'IDENTIFY';\n\t\t\tproperties: {\n\t\t\t\tidentifier: string;\n\t\t\t\tfirst_name?: string;\n\t\t\t\tlast_name?: string;\n\t\t\t\tphone_number?: string;\n\t\t\t\temail?: string;\n\t\t\t\tcustom_traits?: Record<string, unknown>;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_PAGINATE';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_SETTLE';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_JOB_CLICK';\n\t\t\tproperties: {\n\t\t\t\tjob_id: number;\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'VIEW_SEARCH';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'FEEDBACK';\n\t\t\tproperties: {\n\t\t\t\tkey: string;\n\t\t\t\tscore?: -1 | 0 | 1;\n\t\t\t\tcomment?: string;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'LINK_CLICK';\n\t\t\tproperties: {\n\t\t\t\ttarget_href: string;\n\t\t\t\tjob_id: string | undefined;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'INTERACTION';\n\t\t\tproperties: {\n\t\t\t\ttag: string;\n\t\t\t};\n\t };\n\nexport type AnalyticsLogEvent = AnalyticsLogParams['event'];\n\ntype EventPropertyMap = {\n\t[Param in AnalyticsLogParams as Param['event']]: Omit<Param, 'event'>;\n};\n\ntype AnalyticsContext = {\n\tlibrary: {\n\t\tname: 'inploi-sdk';\n\t\tversion: string;\n\t};\n\tpage: {\n\t\thref: string;\n\t\treferrer: string;\n\t\ttitle: string;\n\t};\n};\n\ntype TrackPayload<P = EventPropertyMap[keyof EventPropertyMap]['properties']> = {\n\tanonymous_id: string | null;\n\tsession_id: string | null;\n\tevent: AnalyticsLogEvent;\n\tsent_at: string;\n\tcontext: AnalyticsContext;\n\tproperties: P;\n\tcustom_properties?: Record<string, unknown>;\n};\n\ntype LogFnParams<T extends keyof EventPropertyMap> = {\n\tevent: T;\n\tcustomProperties?: Record<string, unknown>;\n\t/** Passing a request will make logging possible on a server environment. */\n\trequest?: Request;\n} & EventPropertyMap[T];\n\ntype LogFn = <TEvent extends keyof EventPropertyMap>(\n\tparams: LogFnParams<TEvent>,\n) => Promise<ResponseObj<TrackPayload<EventPropertyMap[TEvent]['properties']>>>;\n\nexport type AnalyticsService = {\n\tlog: LogFn;\n\t/** From a log payload data, generate headers to use in server environments to update the anonymous_id */\n\tgetHeaders: (payload?: TrackPayload) => Headers;\n\tgetSessionInfo: typeof getSessionInfo;\n};\n\nconst getSessionId = (searchParams: URLSearchParams, isServer: boolean) => {\n\tconst fromSearchParams = searchParams.get('session_id');\n\tif (isServer) return fromSearchParams;\n\tif (fromSearchParams) return fromSearchParams;\n\tconst fromSessionStorage = sessionStorage.getItem(`${ANALYTICS_COOKIE_NAME}-session_id`);\n\tif (typeof fromSessionStorage === 'string') return fromSessionStorage;\n\treturn null;\n};\n\nconst cookieRegex = new RegExp(`${ANALYTICS_COOKIE_NAME}=([^;]+)`);\nconst getSessionInfo = (request?: Request) => {\n\tconst href = request ? request.url : location.href;\n\tconst { searchParams } = new URL(href);\n\tconst anonymous_id = searchParams.get('anonymous_id');\n\tconst session_id = getSessionId(searchParams, typeof window === 'undefined');\n\n\t// If there’s an anonymous_id in the search params, use it\n\tif (anonymous_id)\n\t\treturn {\n\t\t\tanonymous_id,\n\t\t\tsession_id,\n\t\t};\n\n\t// If there’s a cookie, use it\n\tconst cookie = request ? request.headers.get('cookie') : document.cookie;\n\tif (cookie) {\n\t\tconst match = cookieRegex.exec(cookie);\n\t\tconst anonymous_id = match?.[1];\n\t\treturn {\n\t\t\tanonymous_id: anonymous_id ?? null,\n\t\t\tsession_id,\n\t\t};\n\t}\n\n\t// Otherwise, return what we have\n\treturn {\n\t\tanonymous_id,\n\t\tsession_id,\n\t};\n};\n\nconst getSessionInfoFromResponse = (response: unknown) => {\n\tif (typeof response !== 'object' || response === null) return null;\n\treturn {\n\t\tanonymous_id:\n\t\t\t'anonymous_id' in response && typeof response.anonymous_id === 'string' ? response.anonymous_id : null,\n\t\tsession_id: 'session_id' in response && typeof response.session_id === 'string' ? response.session_id : null,\n\t};\n};\n\nconst serverReferrer = (referrer: typeof Request.prototype.referrer) => {\n\tif (referrer === 'about:client') return '';\n\treturn referrer;\n};\n\nexport const createAnalyticsService = ({\n\tapiClient,\n\tlogger,\n}: {\n\tlogger: Logger;\n\tapiClient: ApiClient;\n}): AnalyticsService => {\n\tconst logFn: LogFn = async params => {\n\t\tinvariant(\n\t\t\tparams.request || typeof window !== 'undefined',\n\t\t\t'Cannot log on the server without a request. Please pass a request to `log`.',\n\t\t);\n\n\t\t// if there’s a request, use it instead of browser APIs\n\t\tconst page =\n\t\t\t'request' in params && params.request ?\n\t\t\t\t{\n\t\t\t\t\thref: params.request.url,\n\t\t\t\t\treferrer: serverReferrer(params.request.referrer),\n\t\t\t\t\ttitle: '',\n\t\t\t\t}\n\t\t\t:\t{\n\t\t\t\t\thref: location.href,\n\t\t\t\t\treferrer: document.referrer,\n\t\t\t\t\ttitle: document.title,\n\t\t\t\t};\n\n\t\ttry {\n\t\t\tconst context: AnalyticsContext = {\n\t\t\t\tlibrary: {\n\t\t\t\t\tname: 'inploi-sdk',\n\t\t\t\t\tversion: ANALYTICS_VERSION,\n\t\t\t\t},\n\t\t\t\tpage,\n\t\t\t};\n\n\t\t\tconst sessionInfo = getSessionInfo(params.request);\n\t\t\tconst payload: TrackPayload = {\n\t\t\t\tanonymous_id: sessionInfo.anonymous_id,\n\t\t\t\tsession_id: sessionInfo.session_id,\n\t\t\t\tevent: params.event,\n\t\t\t\tsent_at: new Date().toISOString(),\n\t\t\t\tcontext,\n\t\t\t\tproperties: params.properties,\n\t\t\t\tcustom_properties: params.customProperties,\n\t\t\t};\n\n\t\t\tconst responseJson = await apiClient.fetch(LOG_PATHNAME, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t});\n\n\t\t\tconst newSession = getSessionInfoFromResponse(responseJson);\n\t\t\tif (newSession?.anonymous_id) {\n\t\t\t\tpayload.anonymous_id = newSession.anonymous_id;\n\t\t\t}\n\t\t\tif (newSession?.session_id) {\n\t\t\t\tpayload.session_id = newSession.session_id;\n\t\t\t}\n\n\t\t\tif (typeof window !== 'undefined' && payload.anonymous_id) {\n\t\t\t\tif (payload.session_id) {\n\t\t\t\t\tsessionStorage.setItem(`${ANALYTICS_COOKIE_NAME}-session_id`, payload.session_id.toString());\n\t\t\t\t}\n\t\t\t\tdocument.cookie = formatCookie(payload.anonymous_id);\n\t\t\t}\n\n\t\t\treturn { success: true, data: payload };\n\t\t} catch (e) {\n\t\t\t/** We dont’t log any PII on the console */\n\t\t\tlogger.error('Failed to send log to API. Inspect error response of `log` for more information.');\n\t\t\treturn { success: false, error: e };\n\t\t}\n\t};\n\n\treturn {\n\t\tlog: logFn,\n\t\tgetHeaders: payload => {\n\t\t\tconst headers = new Headers();\n\t\t\tif (!payload?.anonymous_id) return headers;\n\n\t\t\theaders.append('Set-Cookie', formatCookie(payload.anonymous_id));\n\t\t\treturn headers;\n\t\t},\n\t\tgetSessionInfo,\n\t};\n};\n","import { createAnalyticsService } from './sdk.analytics';\nimport { createApiClient } from './sdk.api';\nimport { ENV_TO_API_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger, inploiBrandedLogger, noLogging } from './sdk.logger';\nimport { InploiSdkPlugin } from './sdk.plugins';\n\nexport type InitialiseInploiSdkParams = {\n\t/** Your public API key for the inploi SDK. */\n\tpublishableKey: string;\n\t/** Which app environment to run. This ultimately affects which inploi endpoints to gather data are going to be used.\n\t * Anything other than `production` should be considered a development environment and the data periodicaly purged. */\n\tenv: InploiSdkEnvironment;\n\t/** Logger object that handles logging of different levels.\n\t * You can override this to use your own logger, or to disable logging altogether by passing`false`.\n\t * @default inploiBrandedLogger\n\t * */\n\tlogger?: Logger | false;\n};\n\nexport function initialiseSdk({ publishableKey, env, logger = inploiBrandedLogger }: InitialiseInploiSdkParams) {\n\tconst apiClient = createApiClient({ baseUrl: ENV_TO_API_URL[env], publishableKey });\n\tconst loggerService = logger === false ? noLogging : logger;\n\tconst analytics = createAnalyticsService({ apiClient, logger: loggerService });\n\n\tconst register = <P extends InploiSdkPlugin>(plugin: P): ReturnType<P> => {\n\t\treturn plugin({ logger: loggerService, apiClient, analytics });\n\t};\n\n\treturn { register, analytics, apiClient };\n}\n\nexport type Inplo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AAa+B,EAAQ,YAAY,CAAC,EACxDK,CACR,EACA,eAAA1B,CACD,GCjTM,SAAS2B,EAAc,CAAE,eAAAC,EAAgB,IAAAC,EAAK,OAAAC,EAASC,CAAoB,EAA8B,CAC/G,IAAMC,EAAYC,EAAgB,CAAE,QAASC,EAAeL,CAAG,EAAG,eAAAD,CAAe,CAAC,EAC5EO,EAAgBL,IAAW,GAAQM,EAAYN,EAC/CO,EAAYC,EAAuB,CAAE,UAAAN,EAAW,OAAQG,CAAc,CAAC,EAM7E,MAAO,CAAE,SAJoCI,GACrCA,EAAO,CAAE,OAAQJ,EAAe,UAAAH,EAAW,UAAAK,CAAU,CAAC,EAG3C,UAAAA,EAAW,UAAAL,CAAU,CACzC","names":["src_exports","__export","ApiError","NotFoundError","ParsingError","UnauthorisedError","createPlugin","initialiseSdk","inploiBrandedLogger","noLogging","__toCommonJS","CONSOLE_PREFIX","CONSOLE_STYLE","inploiBrandedLogger","args","noLogging","createPlugin","pluginFn","unauthenticatedMessage","unauthorisedMessage","NotFoundError","UnauthorisedError","message","ApiError","errors","ParsingError","response","createApiClient","params","defaultHeaders","_0","_1","__async","pathname","options","init","__spreadProps","__spreadValues","json","invariant","condition","message","DEFAULT_FORMATTER","version","ENV_TO_API_URL","ANALYTICS_VERSION","version","LOG_PATHNAME","ANALYTICS_COOKIE_NAME","formatCookie","value","now","ANALYTICS_COOKIE_NAME","getSessionId","searchParams","isServer","fromSearchParams","fromSessionStorage","cookieRegex","getSessionInfo","request","href","anonymous_id","session_id","cookie","match","getSessionInfoFromResponse","response","serverReferrer","referrer","createAnalyticsService","apiClient","logger","params","__async","invariant","page","context","ANALYTICS_VERSION","sessionInfo","payload","responseJson","LOG_PATHNAME","newSession","e","headers","initialiseSdk","publishableKey","env","logger","inploiBrandedLogger","apiClient","createApiClient","ENV_TO_API_URL","loggerService","noLogging","analytics","createAnalyticsService","plugin"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/sdk.logger.ts","../src/sdk.plugins.ts","../src/sdk.api.ts","../../core/src/common/common.utils.ts","../../core/src/common/common.currency.ts","../../core/src/common/common.datetime.ts","../package.json","../src/sdk.constants.ts","../src/sdk.analytics.ts","../src/sdk.rpc.ts","../src/sdk.ts"],"sourcesContent":["export { inploiBrandedLogger, noLogging } from './sdk.logger';\nexport type { Logger } from './sdk.logger';\n\nexport type { PluginParams, InploiSdkPlugin } from './sdk.plugins';\nexport { createPlugin } from './sdk.plugins';\n\nexport type { InploiSdkEnvironment } from './sdk.constants';\n\nexport type { ApiClient } from './sdk.api';\nexport { ApiError, NotFoundError, JsonParsingError as ParsingError, UnauthorisedError } from './sdk.api';\n\nexport { initialiseSdk } from './sdk';\nexport type { InitialiseInploiSdkParams, InploiSdk } from './sdk';\n\nexport type { AnalyticsService, AnalyticsLogEvent } from './sdk.analytics';\n\nexport { InploiRpcClient, endpoint, typed } from './sdk.rpc';\nexport type { RpcEndpoint } from './sdk.rpc';\n","export const CONSOLE_PREFIX = '%c[inploi SDK]';\nexport const CONSOLE_STYLE = 'color: #65BC67; font-weight: bold;';\n\ntype LogMessage = (...data: any[]) => void;\nexport type Logger = {\n\twarn: LogMessage;\n\terror: LogMessage;\n\tinfo: LogMessage;\n\tlog: LogMessage;\n};\n\nexport const inploiBrandedLogger: Logger = {\n\twarn: (...args) => console.warn(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\terror: (...args) => console.error(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\tinfo: (...args) => console.info(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\tlog: (...args) => console.log(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n};\n\nexport const noLogging: Logger = { info: () => void 0, error: () => void 0, log: () => void 0, warn: () => void 0 };\n","import { AnalyticsService } from './sdk.analytics';\nimport { ApiClient } from './sdk.api';\nimport { Logger } from './sdk.logger';\nimport { InploiRpcClient } from './sdk.rpc';\n\nexport type PluginParams = {\n\tapiClient: ApiClient;\n\tlogger: Logger;\n};\n\nexport type Plugin<T extends string, P extends Record<string, unknown>> = {\n\tpluginName: T;\n\tpure_createActions: (params: PluginParams) => P;\n};\n\ntype PluginDependencies = {\n\tapiClient: ApiClient;\n\trpcClient: InploiRpcClient;\n\tlogger: Logger;\n\tanalytics: AnalyticsService;\n};\n\nexport type InploiSdkPlugin = (dependencies: PluginDependencies) => any;\n\nexport const createPlugin = <T extends InploiSdkPlugin>(pluginFn: T) => pluginFn;\n","import { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport const unauthenticatedMessage = 'Unauthenticated';\nexport const unauthorisedMessage = 'This action is unauthorized.';\n\nexport class NotFoundError extends Error {\n\tconstructor() {\n\t\tsuper('Not found');\n\t\tthis.name = 'NotFoundError';\n\t}\n}\n\nexport class UnauthorisedError extends Error {\n\tconstructor(message?: string) {\n\t\tsuper(message ?? 'You are not authorised to perform this action.');\n\t\tthis.name = 'UnauthorisedError';\n\t}\n}\n\nexport class SchemaValidationError extends Error {\n\tconstructor(public issues: readonly StandardSchemaV1.Issue[]) {\n\t\tsuper('Schema validation failed');\n\t\tthis.name = 'SchemaValidationError';\n\t}\n}\n\nexport class ApiError extends Error {\n\terrors: unknown[];\n\tconstructor(message: string, errors: unknown[]) {\n\t\tsuper(message);\n\t\tthis.name = 'ApiError';\n\t\tthis.errors = errors;\n\t}\n}\n\nexport class JsonParsingError extends Error {\n\tconstructor(public response?: Response) {\n\t\tsuper('Error parsing response into JSON.');\n\t\tthis.name = 'ParsingError';\n\t}\n}\n\n/** @deprecated - use `JsonParsingError` instead */\nexport class ParsingError extends JsonParsingError {}\n\nexport type ApiClient = {\n\tfetch: (pathname: string, options?: RequestInit) => Promise<unknown>;\n};\n\n/** Throws branded errors when API returns a known error. */\nexport function handleApiExceptions(json: unknown) {\n\tif (typeof json === 'object' && json !== null && 'message' in json && typeof json.message === 'string') {\n\t\tif (json.message === unauthenticatedMessage) {\n\t\t\tthrow new UnauthorisedError('You are not authenticated.');\n\t\t}\n\t\tif (json.message === unauthorisedMessage) {\n\t\t\tthrow new UnauthorisedError();\n\t\t}\n\t\tif ('exception' in json) {\n\t\t\tthrow new ApiError(json.message, [json.exception]);\n\t\t}\n\t\tif ('errors' in json) {\n\t\t\tthrow new ApiError(json.message, Array.isArray(json.errors) ? json.errors : [json.errors]);\n\t\t}\n\t}\n}\n\nexport const createApiClient = (params: { baseUrl: string; publishableKey: string }): ApiClient => {\n\tconst defaultHeaders: HeadersInit = {\n\t\tAccept: 'application/json',\n\t\t'Content-Type': 'application/json',\n\t\t'x-publishable-key': params.publishableKey,\n\t};\n\n\treturn {\n\t\t/** Fetches from a pathname with a pre-established base path.\n\t\t * Parses received output as JSON, and throw if one of the common error messages is received.\n\t\t */\n\t\tfetch: async (pathname, options = {}) => {\n\t\t\tconst init = { ...options, headers: { ...options.headers, ...defaultHeaders } };\n\t\t\tconst response = await fetch(`${params.baseUrl}${pathname}`, init);\n\t\t\tif (response.status === 404) throw new NotFoundError();\n\n\t\t\tconst json = await response.json().catch(async () => {\n\t\t\t\tthrow new JsonParsingError(response);\n\t\t\t});\n\n\t\t\thandleApiExceptions(json);\n\n\t\t\t// We’re assuming no other exceptions have happened.\n\t\t\treturn json;\n\t\t},\n\t};\n};\n","export const exhaustive = (value: never) => {\n\tthrow new Error(`Unhandled discriminated union member: ${JSON.stringify(value)}`);\n};\n\nexport function invariant(condition: any, message?: string): asserts condition {\n\tif (condition) {\n\t\treturn;\n\t}\n\n\tthrow new Error(message);\n}\n\nexport const uniqueOrThrow = <T>(array: T[]) => {\n\tconst uniqueValues = new Set(array);\n\n\tif (array.length !== uniqueValues.size) {\n\t\tthrow new Error('Duplicate values found');\n\t}\n\treturn true;\n};\n\nexport const uniqueByPropertyOrThrow =\n\t<T extends PropertyKey>(propertyKey: T) =>\n\t(array: { [K in T]: any }[]) => {\n\t\tconst values = array.map(item => item[propertyKey]);\n\t\tconst uniqueValues = new Set(values);\n\n\t\tif (values.length !== uniqueValues.size) {\n\t\t\tthrow new Error(`Duplicate values found for property: ${propertyKey.toString()}`);\n\t\t}\n\t\treturn true;\n\t};\n\n/**\n * A destructive way to ensure an object has a property.\n * This is useful when working with unknowns.\n */\nexport function hasProp<K extends PropertyKey>(data: object, prop: K): data is Record<K, unknown> {\n\treturn prop in data;\n}\n\n/**\n * A sort of type-safe way to check whether a key exists in an object.\n */\nexport function isKeyInObj<O extends Record<string, unknown>>(key: PropertyKey, obj: O): key is keyof O {\n\treturn key in obj;\n}\n","type TFunction = (key: 'competitive' | 'invalid_salary' | 'from' | 'up_to') => string;\n\ninterface SalaryParams {\n\tpay: string | null;\n\tpay_min: string | null;\n\tpay_mask: boolean;\n\tpay_max: string | null;\n\tpay_type: 'ANNUALLY' | 'HOURLY' | 'MONTHLY' | 'WEEKLY' | 'DAILY' | null;\n\tpay_currency: string;\n\tpay_display: boolean;\n}\n\nconst payPeriods: Record<NonNullable<SalaryParams['pay_type']>, string> = {\n\tANNUALLY: 'per year',\n\tDAILY: 'per day',\n\tHOURLY: 'per hour',\n\tMONTHLY: 'per month',\n\tWEEKLY: 'per week',\n};\n\nexport const getSalaryAsText = (params: {\n\tsalary: SalaryParams;\n\tconfig: { locales: string | string[] | undefined };\n\tt?: TFunction;\n}) => {\n\tconst { salary, config, t = s => s } = params;\n\tconst numberFormatter = new Intl.NumberFormat(config.locales, {\n\t\tstyle: 'currency',\n\t\tcurrency: salary.pay_currency,\n\t\t// @ts-expect-error - CI/CD is not happy with this, though locally it works\n\t\ttrailingZeroDisplay: 'stripIfInteger',\n\t});\n\tif (salary.pay_display === false) return undefined;\n\tif (salary.pay_mask) return t('competitive');\n\n\tif (salary.pay_max && Number.isNaN(+salary.pay_max)) return t('invalid_salary');\n\tif (salary.pay_min && Number.isNaN(+salary.pay_min)) return t('invalid_salary');\n\tif (salary.pay && Number.isNaN(+salary.pay)) return t('invalid_salary');\n\n\tconst period = salary.pay_type && salary.pay_type in payPeriods ? payPeriods[salary.pay_type] : undefined;\n\n\tif (salary.pay) return [numberFormatter.format(+salary.pay), period].filter(Boolean).join(' ');\n\n\tif (salary.pay_max && salary.pay_min)\n\t\treturn [numberFormatter.formatRange(+salary.pay_min, +salary.pay_max), period].filter(Boolean).join(' ') || '';\n\n\tif (salary.pay_max)\n\t\treturn `${t('up_to')} ${[numberFormatter.format(+salary.pay_max), period].filter(Boolean).join(' ')}`;\n\tif (salary.pay_min)\n\t\treturn `${t('from')} ${[numberFormatter.format(+salary.pay_min), period].filter(Boolean).join(' ')}`;\n\treturn t('invalid_salary');\n};\n","type TFunction = (key: 'today' | 'over_30_days_ago' | 'in_over_30_days') => string;\n\ntype Params = {\n\tfrom?: Date;\n\tto: string | number | Date;\n\tformatter?: Intl.RelativeTimeFormat;\n\tt?: TFunction;\n};\n\nconst DEFAULT_FORMATTER = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });\n/** From a date, calculates the relative time difference from now */\nexport const getRelativeTimeDifference = ({\n\tfrom = new Date(),\n\tto,\n\tformatter = DEFAULT_FORMATTER,\n\tt = s => s,\n}: Params) => {\n\tconst then = to instanceof Date ? to : new Date(to);\n\tconst diff = then.getTime() - from.getTime();\n\n\tconst diffIn = {\n\t\tdays: Math.round(diff / 1000 / 60 / 60 / 24),\n\t\tmonths: Math.round(diff / 1000 / 60 / 60 / 24 / 30),\n\t};\n\n\tif (diffIn.days === 0) return t('today');\n\tif (Math.abs(diffIn.days) < 30) return formatter.format(diffIn.days, 'days');\n\tif (Math.abs(diffIn.days) < 3) return formatter.format(diffIn.months, 'months');\n\treturn diffIn.months < 0 ? t('over_30_days_ago') : t('in_over_30_days');\n};\n","{\n\t\"name\": \"@inploi/sdk\",\n\t\"version\": \"1.15.0\",\n\t\"main\": \"dist/index.js\",\n\t\"types\": \"dist/index.d.ts\",\n\t\"license\": \"MIT\",\n\t\"files\": [\n\t\t\"/dist\",\n\t\t\"/cdn\"\n\t],\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"require\": \"./dist/index.js\",\n\t\t\t\"import\": \"./dist/index.mjs\",\n\t\t\t\"types\": \"./dist/index.d.ts\"\n\t\t}\n\t},\n\t\"scripts\": {\n\t\t\"build:npm\": \"tsup --dts --dts-resolve\",\n\t\t\"build:cdn\": \"tsup --config tsup.cdn.config.ts\",\n\t\t\"build\": \"concurrently 'pnpm run build:npm' 'pnpm run build:cdn'\",\n\t\t\"dev\": \"tsup --watch --config tsup.cdn.config.ts\",\n\t\t\"check\": \"eslint src --fix --max-warnings 0 && tsc\",\n\t\t\"test\": \"bun test\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@happy-dom/global-registrator\": \"^13.6.2\",\n\t\t\"@inploi/core\": \"workspace:*\",\n\t\t\"@total-typescript/ts-reset\": \"^0.5.1\",\n\t\t\"@types/bun\": \"^1.2.5\",\n\t\t\"@types/react\": \"^18.2.33\",\n\t\t\"@types/react-dom\": \"^18.2.14\",\n\t\t\"autoprefixer\": \"^10.4.16\",\n\t\t\"concurrently\": \"9.1.2\",\n\t\t\"eslint\": \"^7.32.0\",\n\t\t\"eslint-config-custom\": \"workspace:*\",\n\t\t\"happy-dom\": \"^12.6.0\",\n\t\t\"ts-toolbelt\": \"^9.6.0\",\n\t\t\"tsconfig\": \"workspace:*\",\n\t\t\"tsup\": \"^7.2.0\"\n\t},\n\t\"dependencies\": {\n\t\t\"@standard-schema/spec\": \"^1.0.0\",\n\t\t\"neoqs\": \"^6.13.0\"\n\t}\n}\n","import { version } from '../package.json';\n\n/**\n * The environment the SDK should run in.\n * - `production`: data will be stored and displayed on dashboards\n * - `sandbox`: data will be stored temporarily and purged periodically\n */\nexport type InploiSdkEnvironment = 'production' | 'sandbox';\n\nexport const ENV_TO_API_URL: Record<InploiSdkEnvironment, string> = {\n\tsandbox: 'https://api.staging.inploi.com',\n\tproduction: 'https://api.inploi.com',\n\t// @ts-expect-error - local test environment\n\t_internal_local: 'http://api.test',\n};\n\nexport const ANALYTICS_VERSION = version;\n\nexport const LOG_PATHNAME = '/log';\n\nexport const ANALYTICS_COOKIE_NAME = 'isdk_session';\n","import type { ResponseObj } from '@inploi/core/common';\nimport { invariant } from '@inploi/core/common';\n\nimport { InploiRpcClient, Logger, endpoint, typed } from '.';\nimport { ANALYTICS_COOKIE_NAME, ANALYTICS_VERSION } from './sdk.constants';\n\nconst formatCookie = (value: string) => {\n\tconst now = new Date();\n\tnow.setTime(now.getTime() + 7 * 24 * 60 * 60 * 1000); // 7 days expiration\n\n\treturn `${ANALYTICS_COOKIE_NAME}=${value};expires=${now.toUTCString()};path=/`;\n};\n\ntype FlowProperties = { flow_id: string; flow_version: number; flow_session_id: string; flow_build: number };\n\ntype JobProperties = {\n\tid: string;\n\tid_type: 'internal' | 'external';\n};\n\ntype AnalyticsLogParams =\n\t| {\n\t\t\tevent: 'VIEW_JOB';\n\t\t\tproperties: { job: JobProperties };\n\t }\n\t| {\n\t\t\tevent: 'FLOW_REDIRECT';\n\t\t\tproperties: { href: string; job: JobProperties | undefined } & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_START' | 'FLOW_END';\n\t\t\tproperties: { job: JobProperties | undefined } & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_NODE';\n\t\t\tproperties: {\n\t\t\t\t/** Increments by 1 per node interpreted */\n\t\t\t\tsequence: number;\n\t\t\t\tfrom_node_id: string;\n\t\t\t\tto_node_id: string;\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t} & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_SUBMIT';\n\t\t\tproperties: {\n\t\t\t\tservice: string;\n\t\t\t\tresponse: {\n\t\t\t\t\tstatus: number;\n\t\t\t\t\tpayload: unknown;\n\t\t\t\t};\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t} & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'SUBMIT_FORM' | 'VIEW_PAGE';\n\t\t\tproperties?: {\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'IDENTIFY';\n\t\t\tproperties: {\n\t\t\t\tidentifier: string;\n\t\t\t\tfirst_name?: string;\n\t\t\t\tlast_name?: string;\n\t\t\t\tphone_number?: string;\n\t\t\t\temail?: string;\n\t\t\t\tcustom_traits?: Record<string, unknown>;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_PAGINATE';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_SETTLE';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_JOB_CLICK';\n\t\t\tproperties: {\n\t\t\t\tjob_id: number;\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'VIEW_SEARCH';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'FEEDBACK';\n\t\t\tproperties: {\n\t\t\t\tkey: string;\n\t\t\t\tscore?: -1 | 0 | 1;\n\t\t\t\tcomment?: string;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'LINK_CLICK';\n\t\t\tproperties: {\n\t\t\t\ttarget_href: string;\n\t\t\t\tjob_id: string | undefined;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'INTERACTION';\n\t\t\tproperties: {\n\t\t\t\ttag: string;\n\t\t\t};\n\t };\n\nexport type AnalyticsLogEvent = AnalyticsLogParams['event'];\n\ntype EventPropertyMap = {\n\t[Param in AnalyticsLogParams as Param['event']]: Omit<Param, 'event'>;\n};\n\ntype AnalyticsContext = {\n\tlibrary: {\n\t\tname: 'inploi-sdk';\n\t\tversion: string;\n\t};\n\tpage: {\n\t\thref: string;\n\t\treferrer: string;\n\t\ttitle: string;\n\t};\n};\n\ntype TrackPayload<P = EventPropertyMap[keyof EventPropertyMap]['properties']> = {\n\tanonymous_id: string | null;\n\tsession_id: string | null;\n\tevent: AnalyticsLogEvent;\n\tsent_at: string;\n\tcontext: AnalyticsContext;\n\tproperties: P;\n\tcustom_properties?: Record<string, unknown>;\n};\n\ntype LogFnParams<T extends keyof EventPropertyMap> = {\n\tevent: T;\n\tcustomProperties?: Record<string, unknown>;\n\t/** Passing a request will make logging possible on a server environment. */\n\trequest?: Request;\n} & EventPropertyMap[T];\n\ntype LogFn = <TEvent extends keyof EventPropertyMap>(\n\tparams: LogFnParams<TEvent>,\n) => Promise<ResponseObj<TrackPayload<EventPropertyMap[TEvent]['properties']>>>;\n\nexport type AnalyticsService = {\n\tlog: LogFn;\n\t/** From a log payload data, generate headers to use in server environments to update the anonymous_id */\n\tgetHeaders: (payload?: TrackPayload) => Headers;\n\tgetSessionInfo: typeof getSessionInfo;\n};\n\nconst getSessionId = (searchParams: URLSearchParams, isServer: boolean) => {\n\tconst fromSearchParams = searchParams.get('session_id');\n\tif (isServer) return fromSearchParams;\n\tif (fromSearchParams) return fromSearchParams;\n\tconst fromSessionStorage = sessionStorage.getItem(`${ANALYTICS_COOKIE_NAME}-session_id`);\n\tif (typeof fromSessionStorage === 'string') return fromSessionStorage;\n\treturn null;\n};\n\nconst cookieRegex = new RegExp(`${ANALYTICS_COOKIE_NAME}=([^;]+)`);\nconst getSessionInfo = (request?: Request) => {\n\tconst href = request ? request.url : location.href;\n\tconst { searchParams } = new URL(href);\n\tconst anonymous_id = searchParams.get('anonymous_id');\n\tconst session_id = getSessionId(searchParams, typeof window === 'undefined');\n\n\t// If there’s an anonymous_id in the search params, use it\n\tif (anonymous_id)\n\t\treturn {\n\t\t\tanonymous_id,\n\t\t\tsession_id,\n\t\t};\n\n\t// If there’s a cookie, use it\n\tconst cookie = request ? request.headers.get('cookie') : document.cookie;\n\tif (cookie) {\n\t\tconst match = cookieRegex.exec(cookie);\n\t\tconst anonymous_id = match?.[1];\n\t\treturn {\n\t\t\tanonymous_id: anonymous_id ?? null,\n\t\t\tsession_id,\n\t\t};\n\t}\n\n\t// Otherwise, return what we have\n\treturn {\n\t\tanonymous_id,\n\t\tsession_id,\n\t};\n};\n\nconst getSessionInfoFromResponse = (response: unknown) => {\n\tif (typeof response !== 'object' || response === null) return null;\n\treturn {\n\t\tanonymous_id:\n\t\t\t'anonymous_id' in response && typeof response.anonymous_id === 'string' ? response.anonymous_id : null,\n\t\tsession_id: 'session_id' in response && typeof response.session_id === 'string' ? response.session_id : null,\n\t};\n};\n\nconst serverReferrer = (referrer: typeof Request.prototype.referrer) => {\n\tif (referrer === 'about:client') return '';\n\treturn referrer;\n};\n\nconst analyticsLogEndpoint = endpoint({\n\tpathname: '/log',\n\tmethod: 'POST',\n\tschema: {\n\t\tresponse: typed<unknown>(),\n\t\tsearchParams: typed<TrackPayload>(),\n\t},\n});\n\nexport const createAnalyticsService = ({\n\trpcClient,\n\tlogger,\n}: {\n\tlogger: Logger;\n\trpcClient: InploiRpcClient;\n}): AnalyticsService => {\n\tconst logFn: LogFn = async params => {\n\t\tinvariant(\n\t\t\tparams.request || typeof window !== 'undefined',\n\t\t\t'Cannot log on the server without a request. Please pass a request to `log`.',\n\t\t);\n\n\t\t// if there’s a request, use it instead of browser APIs\n\t\tconst page =\n\t\t\t'request' in params && params.request ?\n\t\t\t\t{\n\t\t\t\t\thref: params.request.url,\n\t\t\t\t\treferrer: serverReferrer(params.request.referrer),\n\t\t\t\t\ttitle: '',\n\t\t\t\t}\n\t\t\t:\t{\n\t\t\t\t\thref: location.href,\n\t\t\t\t\treferrer: document.referrer,\n\t\t\t\t\ttitle: document.title,\n\t\t\t\t};\n\n\t\ttry {\n\t\t\tconst context: AnalyticsContext = {\n\t\t\t\tlibrary: {\n\t\t\t\t\tname: 'inploi-sdk',\n\t\t\t\t\tversion: ANALYTICS_VERSION,\n\t\t\t\t},\n\t\t\t\tpage,\n\t\t\t};\n\n\t\t\tconst sessionInfo = getSessionInfo(params.request);\n\t\t\tconst payload: TrackPayload = {\n\t\t\t\tanonymous_id: sessionInfo.anonymous_id,\n\t\t\t\tsession_id: sessionInfo.session_id,\n\t\t\t\tevent: params.event,\n\t\t\t\tsent_at: new Date().toISOString(),\n\t\t\t\tcontext,\n\t\t\t\tproperties: params.properties,\n\t\t\t\tcustom_properties: params.customProperties,\n\t\t\t};\n\n\t\t\tconst responseJson = await rpcClient.request(analyticsLogEndpoint, {\n\t\t\t\tsearchParams: payload,\n\t\t\t});\n\n\t\t\tconst newSession = getSessionInfoFromResponse(responseJson);\n\t\t\tif (newSession?.anonymous_id) {\n\t\t\t\tpayload.anonymous_id = newSession.anonymous_id;\n\t\t\t}\n\t\t\tif (newSession?.session_id) {\n\t\t\t\tpayload.session_id = newSession.session_id;\n\t\t\t}\n\n\t\t\tif (typeof window !== 'undefined' && payload.anonymous_id) {\n\t\t\t\tif (payload.session_id) {\n\t\t\t\t\tsessionStorage.setItem(`${ANALYTICS_COOKIE_NAME}-session_id`, payload.session_id.toString());\n\t\t\t\t}\n\t\t\t\tdocument.cookie = formatCookie(payload.anonymous_id);\n\t\t\t}\n\n\t\t\treturn { success: true, data: payload };\n\t\t} catch (e) {\n\t\t\t/** We dont’t log any PII on the console */\n\t\t\tlogger.error('Failed to send log to API. Inspect error response of `log` for more information.');\n\t\t\treturn { success: false, error: e };\n\t\t}\n\t};\n\n\treturn {\n\t\tlog: logFn,\n\t\tgetHeaders: payload => {\n\t\t\tconst headers = new Headers();\n\t\t\tif (!payload?.anonymous_id) return headers;\n\n\t\t\theaders.append('Set-Cookie', formatCookie(payload.anonymous_id));\n\t\t\treturn headers;\n\t\t},\n\t\tgetSessionInfo,\n\t};\n};\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { stringify } from 'neoqs';\n\nimport { JsonParsingError, SchemaValidationError, handleApiExceptions } from './sdk.api';\nimport { ENV_TO_API_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger } from './sdk.logger';\n\ntype RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\n/** Extract parameter names from a pathname string */\ntype ExtractParamNames<T extends string> =\n\tT extends `${infer _Before}:${infer Param}/${infer After}` ? Param | ExtractParamNames<`/${After}`>\n\t: T extends `${infer _Before}:${infer Param}` ? Param\n\t: never;\n\n/** Create params object from parameter names */\ntype ExtractPathParams<T extends string> =\n\tstring extends T ? Record<string, string | number>\n\t: ExtractParamNames<T> extends never ? Record<string, never>\n\t: { [K in ExtractParamNames<T>]: string | number };\n\n/** Parses a StandardSchemaV1 schema and input into an output. */\nexport function parse<T extends StandardSchemaV1>(\n\tschema: T,\n\tinput: StandardSchemaV1.InferInput<T>,\n): StandardSchemaV1.InferOutput<T> {\n\tconst result = schema['~standard'].validate(input);\n\tif (result instanceof Promise) {\n\t\tthrow new TypeError('Async schema');\n\t}\n\n\tif (result.issues) {\n\t\tthrow new SchemaValidationError(result.issues);\n\t}\n\n\treturn result.value;\n}\n\n/** Parses a StandardSchemaV1 schema and input into an output, returning a success flag and issues if the parse fails. */\nexport function safeParse<T extends StandardSchemaV1>(\n\tschema: T,\n\tinput: StandardSchemaV1.InferInput<T>,\n):\n\t| {\n\t\t\tsuccess: true;\n\t\t\toutput: StandardSchemaV1.InferOutput<T>;\n\t }\n\t| {\n\t\t\tsuccess: false;\n\t\t\tissues: readonly StandardSchemaV1.Issue[];\n\t } {\n\ttry {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\toutput: parse(schema, input),\n\t\t};\n\t} catch (e) {\n\t\tif (e instanceof SchemaValidationError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tissues: e.issues,\n\t\t\t};\n\t\t}\n\t\tthrow e;\n\t}\n}\n\nexport interface InploiRpcClientParams {\n\tenvironment: InploiSdkEnvironment;\n\tlogger: Logger;\n\tapiKey:\n\t\t| {\n\t\t\t\t/** Makes the API call with an x-secret-key header\n\t\t\t\t * This will error if used in a browser environment.\n\t\t\t\t */\n\t\t\t\ttype: 'secret';\n\t\t\t\tkey: string;\n\t\t }\n\t\t| {\n\t\t\t\t/** Makes the API call with an x-publishable-key header\n\t\t\t\t * This can be called in a browser or server environment.\n\t\t\t\t */\n\t\t\t\ttype: 'publishable';\n\t\t\t\tkey: string;\n\t\t };\n}\n\n/** RPC client for making API calls to the Inploi API. */\nexport class InploiRpcClient {\n\tprivate baseUrl: string;\n\tprivate headers: Headers;\n\tprivate logger: Logger;\n\n\tconstructor(params: InploiRpcClientParams) {\n\t\tthis.baseUrl = ENV_TO_API_URL[params.environment];\n\t\tthis.headers = new Headers({\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAccept: 'application/json',\n\t\t});\n\t\tif (params.apiKey.type === 'secret') {\n\t\t\tif (typeof window !== 'undefined') {\n\t\t\t\tthrow new Error('Secret key cannot be used in a browser environment');\n\t\t\t}\n\t\t\tthis.headers.set('x-secret-key', params.apiKey.key);\n\t\t} else {\n\t\t\tthis.headers.set('x-publishable-key', params.apiKey.key);\n\t\t}\n\t\tthis.logger = params.logger;\n\t}\n\n\t/** Fetches, parses and validates an API endpoint.\n\t * Logs errors and throws them again so that the caller can handle them.\n\t *\n\t * @throws {JsonParsingError} - If the response is not valid JSON.\n\t * @throws {SchemaValidationError} - If the searchParams, body or response does not match the schema.\n\t * @throws {ApiError} - If the API responded with an error message.\n\t * @throws {UnauthorisedError} - If the request is unauthorised either by missing key or unmet permissions.\n\t * @throws {NotFoundError} - If the endpoint is not found.\n\t * @throws {Error} - Another unhandled error.\n\t */\n\tasync request<T extends RpcEndpoint>(\n\t\tendpoint: T,\n\t\toptions: T extends RpcEndpoint<infer _, infer _TPathname, infer TPathParams, infer TSearch, infer TBody> ?\n\t\t\tGetSchemaValues<{\n\t\t\t\tbody: TBody;\n\t\t\t\tsearchParams: TSearch;\n\t\t\t\tparams: TPathParams;\n\t\t\t}> & { signal?: AbortSignal }\n\t\t:\tnever,\n\t) {\n\t\ttry {\n\t\t\tconst url = new URL(this.baseUrl);\n\n\t\t\t// Replace path parameters in pathname\n\t\t\tlet pathname = endpoint.pathname;\n\t\t\tif ('params' in options && options.params) {\n\t\t\t\tfor (const [key, value] of Object.entries(options.params)) {\n\t\t\t\t\tpathname = pathname.replace(`:${key}`, String(value));\n\t\t\t\t}\n\t\t\t}\n\t\t\turl.pathname = pathname;\n\n\t\t\tif (endpoint.schema.searchParams) {\n\t\t\t\turl.search = stringify(\n\t\t\t\t\tparse(endpoint.schema.searchParams, 'searchParams' in options ? options.searchParams : {}),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst body =\n\t\t\t\tendpoint.schema.body ? parse(endpoint.schema.body, 'body' in options ? options.body : {}) : undefined;\n\n\t\t\tconst response = await fetch(url.toString(), {\n\t\t\t\tmethod: endpoint.method,\n\t\t\t\tbody: body ? JSON.stringify(body) : undefined,\n\t\t\t\theaders: this.headers,\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\n\t\t\tconst json = await response.json().catch(e => {\n\t\t\t\tthis.logger.error(e);\n\t\t\t\tthrow new JsonParsingError(response);\n\t\t\t});\n\n\t\t\tconst result = safeParse(endpoint.schema.response, json);\n\t\t\tif (!result.success) {\n\t\t\t\thandleApiExceptions(json);\n\t\t\t\tthrow new SchemaValidationError(result.issues);\n\t\t\t}\n\n\t\t\treturn result.output as StandardSchemaV1.InferOutput<T['schema']['response']>;\n\t\t} catch (e) {\n\t\t\tif (e instanceof SchemaValidationError) {\n\t\t\t\tthis.logger.error(e.message, e.issues);\n\t\t\t} else {\n\t\t\t\tthis.logger.error(e);\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n}\n\ntype GetSchemaValues<T extends { searchParams: any; body: any; params?: any }> = {\n\t[K in keyof T as T[K] extends never ? never\n\t: T[K] extends Record<string, never> ? never\n\t: K]: T[K] extends never ? never : T[K];\n};\n\n/**\n * Typed but *not runtime validated* schema\n * useful for type-checking the schema without bundling validation schemas\n */\nexport function typed<T>(): StandardSchemaV1<T, T> {\n\treturn {\n\t\t'~standard': {\n\t\t\tvendor: 'inploi',\n\t\t\tversion: 1,\n\t\t\tvalidate: input => {\n\t\t\t\treturn {\n\t\t\t\t\tvalue: input as T,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t};\n}\n\nexport interface RpcEndpoint<\n\tTMethod extends RequestMethod = RequestMethod,\n\tTPathname extends string = string,\n\tTPathParams = any,\n\tTSearch = any,\n\tTBody = any,\n\tTResponse = any,\n> {\n\tpathname: TPathname;\n\tmethod: TMethod;\n\theaders?: Headers;\n\tschema: {\n\t\tsearchParams?: StandardSchemaV1<TSearch, TSearch>;\n\t\tbody?: StandardSchemaV1<TBody, TBody>;\n\t\tresponse: StandardSchemaV1<TResponse, TResponse>;\n\t};\n\t/** Type-only property to store path parameter types */\n\treadonly __pathParams?: TPathParams;\n}\n\nexport function endpoint<\n\tTMethod extends RequestMethod,\n\tTPathname extends string,\n\tTSearch extends StandardSchemaV1 | never = never,\n\tTBody extends StandardSchemaV1 | never = never,\n\tTResponse extends StandardSchemaV1 | never = never,\n>(endpoint: {\n\tpathname: TPathname;\n\tmethod: TMethod;\n\theaders?: Headers;\n\tschema: {\n\t\tsearchParams?: TSearch;\n\t\tbody?: TBody;\n\t\tresponse: TResponse;\n\t};\n}) {\n\ttype PathParams = ExtractPathParams<TPathname>;\n\treturn endpoint as RpcEndpoint<\n\t\tTMethod,\n\t\tTPathname,\n\t\tPathParams,\n\t\tStandardSchemaV1.InferInput<TSearch>,\n\t\tStandardSchemaV1.InferInput<TBody>,\n\t\tStandardSchemaV1.InferOutput<TResponse>\n\t>;\n}\n","import { createAnalyticsService } from './sdk.analytics';\nimport { createApiClient } from './sdk.api';\nimport { ENV_TO_API_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger, inploiBrandedLogger, noLogging } from './sdk.logger';\nimport { InploiSdkPlugin } from './sdk.plugins';\nimport { InploiRpcClient } from './sdk.rpc';\n\nexport type InitialiseInploiSdkParams = {\n\t/** Your public API key for the inploi SDK. */\n\tpublishableKey: string;\n\t/** Which app environment to run. This ultimately affects which inploi endpoints to gather data are going to be used.\n\t * Anything other than `production` should be considered a development environment and the data periodicaly purged. */\n\tenv: InploiSdkEnvironment;\n\t/** Logger object that handles logging of different levels.\n\t * You can override this to use your own logger, or to disable logging altogether by passing`false`.\n\t * @default inploiBrandedLogger\n\t * */\n\tlogger?: Logger | false;\n};\n\nexport function initialiseSdk({ publishableKey, env, logger = inploiBrandedLogger }: InitialiseInploiSdkParams) {\n\t/** @deprecated - use `rpcClient` instead */\n\tconst apiClient = createApiClient({ baseUrl: ENV_TO_API_URL[env], publishableKey });\n\tconst loggerService = logger === false ? noLogging : logger;\n\tconst rpcClient = new InploiRpcClient({\n\t\tenvironment: env,\n\t\tapiKey: { type: 'publishable', key: publishableKey },\n\t\tlogger: loggerService,\n\t});\n\tconst analytics = createAnalyticsService({ rpcClient, logger: loggerService });\n\n\tconst register = <P extends InploiSdkPlugin>(plugin: P): ReturnType<P> => {\n\t\treturn plugin({ logger: loggerService, apiClient, analytics, rpcClient });\n\t};\n\n\treturn { register, analytics, apiClient };\n}\n\nexport type InploiSdk = ReturnType<typeof initialiseSdk>;\n"],"mappings":"i9BAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,cAAAE,EAAA,oBAAAC,EAAA,kBAAAC,EAAA,iBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,kBAAAC,EAA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T,EACb,OAAQ,CAAE,KAAM,cAAe,IAAKD,CAAe,EACnD,OAAQO,CACT,CAAC,EACKI,EAAYC,EAAuB,CAAE,UAAAH,EAAW,OAAQF,CAAc,CAAC,EAM7E,MAAO,CAAE,SAJoCM,GACrCA,EAAO,CAAE,OAAQN,EAAe,UAAAH,EAAW,UAAAO,EAAW,UAAAF,CAAU,CAAC,EAGtD,UAAAE,EAAW,UAAAP,CAAU,CACzC","names":["src_exports","__export","ApiError","InploiRpcClient","NotFoundError","JsonParsingError","UnauthorisedError","createPlugin","endpoint","initialiseSdk","inploiBrandedLogger","noLogging","typed","__toCommonJS","CONSOLE_PREFIX","CONSOLE_STYLE","inploiBrandedLogger","args","noLogging","createPlugin","pluginFn","unauthenticatedMessage","unauthorisedMessage","NotFoundError","UnauthorisedError","message","SchemaValidationError","issues","ApiError","errors","JsonParsingError","response","handleApiExceptions","json","unauthenticatedMessage","UnauthorisedError","unauthorisedMessage","ApiError","createApiClient","params","defaultHeaders","_0","_1","__async","pathname","options","init","__spreadProps","__spreadValues","response","NotFoundError","JsonParsingError","invariant","condition","message","DEFAULT_FORMATTER","version","ENV_TO_API_URL","ANALYTICS_VERSION","version","ANALYTICS_COOKIE_NAME","formatCookie","value","now","ANALYTICS_COOKIE_NAME","getSessionId","searchParams","isServer","fromSearchParams","fromSessionStorage","cookieRegex","getSessionInfo","request","href","anonymous_id","session_id","cookie","match","getSessionInfoFromResponse","response","serverReferrer","referrer","analyticsLogEndpoint","typed","createAnalyticsService","rpcClient","logger","params","__async","invariant","page","context","ANALYTICS_VERSION","sessionInfo","payload","responseJson","newSession","e","headers","import_neoqs","parse","schema","input","result","SchemaValidationError","safeParse","e","InploiRpcClient","params","ENV_TO_API_URL","endpoint","options","__async","url","pathname","key","value","body","response","json","JsonParsingError","handleApiExceptions","typed","initialiseSdk","publishableKey","env","logger","inploiBrandedLogger","apiClient","createApiClient","ENV_TO_API_URL","loggerService","noLogging","rpcClient","InploiRpcClient","analytics","createAnalyticsService","plugin"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var B=Object.defineProperty,K=Object.defineProperties;var U=Object.getOwnPropertyDescriptors;var k=Object.getOwnPropertySymbols;var D=Object.prototype.hasOwnProperty,$=Object.prototype.propertyIsEnumerable;var R=(e,r,t)=>r in e?B(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t,h=(e,r)=>{for(var t in r||(r={}))D.call(r,t)&&R(e,t,r[t]);if(k)for(var t of k(r))$.call(r,t)&&R(e,t,r[t]);return e},A=(e,r)=>K(e,U(r));var d=(e,r,t)=>new Promise((n,s)=>{var c=i=>{try{o(t.next(i))}catch(p){s(p)}},a=i=>{try{o(t.throw(i))}catch(p){s(p)}},o=i=>i.done?n(i.value):Promise.resolve(i.value).then(c,a);o((t=t.apply(e,r)).next())});var _="%c[inploi SDK]",P="color: #65BC67; font-weight: bold;",v={warn:(...e)=>console.warn(_,P,...e),error:(...e)=>console.error(_,P,...e),info:(...e)=>console.info(_,P,...e),log:(...e)=>console.log(_,P,...e)},b={info:()=>{},error:()=>{},log:()=>{},warn:()=>{}};var j=e=>e;var H="Unauthenticated",J="This action is unauthorized.",T=class extends Error{constructor(){super("Not found"),this.name="NotFoundError"}},m=class extends Error{constructor(r){super(r!=null?r:"You are not authorised to perform this action."),this.name="UnauthorisedError"}},u=class extends Error{constructor(t){super("Schema validation failed");this.issues=t;this.name="SchemaValidationError"}},g=class extends Error{constructor(t,n){super(t);this.name="ApiError",this.errors=n}},l=class extends Error{constructor(t){super("Error parsing response into JSON.");this.response=t;this.name="ParsingError"}};function w(e){if(typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"){if(e.message===H)throw new m("You are not authenticated.");if(e.message===J)throw new m;if("exception"in e)throw new g(e.message,[e.exception]);if("errors"in e)throw new g(e.message,Array.isArray(e.errors)?e.errors:[e.errors])}}var L=e=>{let r={Accept:"application/json","Content-Type":"application/json","x-publishable-key":e.publishableKey};return{fetch:(s,...c)=>d(void 0,[s,...c],function*(t,n={}){let a=A(h({},n),{headers:h(h({},n.headers),r)}),o=yield fetch(`${e.baseUrl}${t}`,a);if(o.status===404)throw new T;let i=yield o.json().catch(()=>d(void 0,null,function*(){throw new l(o)}));return w(i),i})}};function E(e,r){if(!e)throw new Error(r)}var ge=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});var C="1.15.0";var x={sandbox:"https://api.staging.inploi.com",production:"https://api.inploi.com",_internal_local:"http://api.test"},O=C;var f="isdk_session";var N=e=>{let r=new Date;return r.setTime(r.getTime()+7*24*60*60*1e3),`${f}=${e};expires=${r.toUTCString()};path=/`},W=(e,r)=>{let t=e.get("session_id");if(r||t)return t;let n=sessionStorage.getItem(`${f}-session_id`);return typeof n=="string"?n:null},z=new RegExp(`${f}=([^;]+)`),M=e=>{let r=e?e.url:location.href,{searchParams:t}=new URL(r),n=t.get("anonymous_id"),s=W(t,typeof window=="undefined");if(n)return{anonymous_id:n,session_id:s};let c=e?e.headers.get("cookie"):document.cookie;if(c){let a=z.exec(c),o=a==null?void 0:a[1];return{anonymous_id:o!=null?o:null,session_id:s}}return{anonymous_id:n,session_id:s}},G=e=>typeof e!="object"||e===null?null:{anonymous_id:"anonymous_id"in e&&typeof e.anonymous_id=="string"?e.anonymous_id:null,session_id:"session_id"in e&&typeof e.session_id=="string"?e.session_id:null},X=e=>e==="about:client"?"":e,Z={pathname:"/log",method:"POST",schema:{response:S(),searchParams:S()}},V=({rpcClient:e,logger:r})=>({log:n=>d(void 0,null,function*(){E(n.request||typeof window!="undefined","Cannot log on the server without a request. Please pass a request to `log`.");let s="request"in n&&n.request?{href:n.request.url,referrer:X(n.request.referrer),title:""}:{href:location.href,referrer:document.referrer,title:document.title};try{let c={library:{name:"inploi-sdk",version:O},page:s},a=M(n.request),o={anonymous_id:a.anonymous_id,session_id:a.session_id,event:n.event,sent_at:new Date().toISOString(),context:c,properties:n.properties,custom_properties:n.customProperties},i=yield e.request(Z,{searchParams:o}),p=G(i);return p!=null&&p.anonymous_id&&(o.anonymous_id=p.anonymous_id),p!=null&&p.session_id&&(o.session_id=p.session_id),typeof window!="undefined"&&o.anonymous_id&&(o.session_id&&sessionStorage.setItem(`${f}-session_id`,o.session_id.toString()),document.cookie=N(o.anonymous_id)),{success:!0,data:o}}catch(c){return r.error("Failed to send log to API. Inspect error response of `log` for more information."),{success:!1,error:c}}}),getHeaders:n=>{let s=new Headers;return n!=null&&n.anonymous_id&&s.append("Set-Cookie",N(n.anonymous_id)),s},getSessionInfo:M});import{stringify as Q}from"neoqs";function I(e,r){let t=e["~standard"].validate(r);if(t instanceof Promise)throw new TypeError("Async schema");if(t.issues)throw new u(t.issues);return t.value}function ee(e,r){try{return{success:!0,output:I(e,r)}}catch(t){if(t instanceof u)return{success:!1,issues:t.issues};throw t}}var y=class{constructor(r){if(this.baseUrl=x[r.environment],this.headers=new Headers({"Content-Type":"application/json",Accept:"application/json"}),r.apiKey.type==="secret"){if(typeof window!="undefined")throw new Error("Secret key cannot be used in a browser environment");this.headers.set("x-secret-key",r.apiKey.key)}else this.headers.set("x-publishable-key",r.apiKey.key);this.logger=r.logger}request(r,t){return d(this,null,function*(){try{let n=new URL(this.baseUrl),s=r.pathname;if("params"in t&&t.params)for(let[p,F]of Object.entries(t.params))s=s.replace(`:${p}`,String(F));n.pathname=s,r.schema.searchParams&&(n.search=Q(I(r.schema.searchParams,"searchParams"in t?t.searchParams:{})));let c=r.schema.body?I(r.schema.body,"body"in t?t.body:{}):void 0,a=yield fetch(n.toString(),{method:r.method,body:c?JSON.stringify(c):void 0,headers:this.headers,signal:t.signal}),o=yield a.json().catch(p=>{throw this.logger.error(p),new l(a)}),i=ee(r.schema.response,o);if(!i.success)throw w(o),new u(i.issues);return i.output}catch(n){throw n instanceof u?this.logger.error(n.message,n.issues):this.logger.error(n),n}})}};function S(){return{"~standard":{vendor:"inploi",version:1,validate:e=>({value:e})}}}function q(e){return e}function re({publishableKey:e,env:r,logger:t=v}){let n=L({baseUrl:x[r],publishableKey:e}),s=t===!1?b:t,c=new y({environment:r,apiKey:{type:"publishable",key:e},logger:s}),a=V({rpcClient:c,logger:s});return{register:i=>i({logger:s,apiClient:n,analytics:a,rpcClient:c}),analytics:a,apiClient:n}}export{g as ApiError,y as InploiRpcClient,T as NotFoundError,l as ParsingError,m as UnauthorisedError,j as createPlugin,q as endpoint,re as initialiseSdk,v as inploiBrandedLogger,b as noLogging,S as typed};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sdk.logger.ts","../src/sdk.plugins.ts","../src/sdk.api.ts","../../core/src/common/common.utils.ts","../../core/src/common/common.currency.ts","../../core/src/common/common.datetime.ts","../package.json","../src/sdk.constants.ts","../src/sdk.analytics.ts","../src/sdk.ts"],"sourcesContent":["export const CONSOLE_PREFIX = '%c[inploi SDK]';\nexport const CONSOLE_STYLE = 'color: #65BC67; font-weight: bold;';\n\ntype LogMessage = (...data: any[]) => void;\nexport type Logger = {\n\twarn: LogMessage;\n\terror: LogMessage;\n\tinfo: LogMessage;\n\tlog: LogMessage;\n};\n\nexport const inploiBrandedLogger: Logger = {\n\twarn: (...args) => console.warn(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\terror: (...args) => console.error(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\tinfo: (...args) => console.info(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\tlog: (...args) => console.log(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n};\n\nexport const noLogging: Logger = { info: () => void 0, error: () => void 0, log: () => void 0, warn: () => void 0 };\n","import { AnalyticsService } from './sdk.analytics';\nimport { ApiClient } from './sdk.api';\nimport { Logger } from './sdk.logger';\n\nexport type PluginParams = {\n\tapiClient: ApiClient;\n\tlogger: Logger;\n};\n\nexport type Plugin<T extends string, P extends Record<string, unknown>> = {\n\tpluginName: T;\n\tpure_createActions: (params: PluginParams) => P;\n};\n\ntype PluginDependencies = {\n\tapiClient: ApiClient;\n\tlogger: Logger;\n\tanalytics: AnalyticsService;\n};\n\nexport type InploiSdkPlugin = (dependencies: PluginDependencies) => any;\n\nexport const createPlugin = <T extends InploiSdkPlugin>(pluginFn: T) => pluginFn;\n","export const unauthenticatedMessage = 'Unauthenticated';\nexport const unauthorisedMessage = 'This action is unauthorized.';\n\nexport class NotFoundError extends Error {\n\tconstructor() {\n\t\tsuper('Not found');\n\t\tthis.name = 'NotFoundError';\n\t}\n}\n\nexport class UnauthorisedError extends Error {\n\tconstructor(message?: string) {\n\t\tsuper(message ?? 'You are not authorised to perform this action.');\n\t\tthis.name = 'UnauthorisedError';\n\t}\n}\n\nexport class ApiError extends Error {\n\terrors: unknown[];\n\tconstructor(message: string, errors: unknown[]) {\n\t\tsuper(`API error: “${message}”`);\n\t\tthis.name = 'ApiError';\n\t\tthis.errors = errors;\n\t}\n}\n\nexport class ParsingError extends Error {\n\tconstructor(public response?: Response) {\n\t\tsuper('Error parsing response into JSON.');\n\t\tthis.name = 'ParsingError';\n\t}\n}\n\nexport type ApiClient = {\n\tfetch: (pathname: string, options?: RequestInit) => Promise<unknown>;\n};\n\nexport const createApiClient = (params: { baseUrl: string; publishableKey: string }): ApiClient => {\n\tconst defaultHeaders: HeadersInit = {\n\t\tAccept: 'application/json',\n\t\t'Content-Type': 'application/json',\n\t\t'x-publishable-key': params.publishableKey,\n\t};\n\n\treturn {\n\t\t/** Fetches from a pathname with a pre-established base path.\n\t\t * Parses received output as JSON, and throw if one of the common error messages is received.\n\t\t */\n\t\tfetch: async (pathname, options = {}) => {\n\t\t\tconst init = { ...options, headers: { ...options.headers, ...defaultHeaders } };\n\t\t\tconst response = await fetch(`${params.baseUrl}${pathname}`, init);\n\t\t\tif (response.status === 404) throw new NotFoundError();\n\n\t\t\tconst json = await response.json().catch(async () => {\n\t\t\t\tthrow new ParsingError(response);\n\t\t\t});\n\n\t\t\tif (typeof json === 'object' && json !== null && 'message' in json && typeof json.message === 'string') {\n\t\t\t\tif (json.message === unauthenticatedMessage) {\n\t\t\t\t\tthrow new UnauthorisedError('You are not authenticated.');\n\t\t\t\t}\n\t\t\t\tif (json.message === unauthorisedMessage) {\n\t\t\t\t\tthrow new UnauthorisedError();\n\t\t\t\t}\n\t\t\t\tif ('exception' in json) {\n\t\t\t\t\tthrow new ApiError(json.message, [json.exception]);\n\t\t\t\t}\n\t\t\t\tif ('errors' in json) {\n\t\t\t\t\tthrow new ApiError(json.message, Array.isArray(json.errors) ? json.errors : [json.errors]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// We’re assuming no other exceptions have happened.\n\t\t\treturn json;\n\t\t},\n\t};\n};\n","export const exhaustive = (value: never) => {\n\tthrow new Error(`Unhandled discriminated union member: ${JSON.stringify(value)}`);\n};\n\nexport function invariant(condition: any, message?: string): asserts condition {\n\tif (condition) {\n\t\treturn;\n\t}\n\n\tthrow new Error(message);\n}\n\nexport const uniqueOrThrow = <T>(array: T[]) => {\n\tconst uniqueValues = new Set(array);\n\n\tif (array.length !== uniqueValues.size) {\n\t\tthrow new Error('Duplicate values found');\n\t}\n\treturn true;\n};\n\nexport const uniqueByPropertyOrThrow =\n\t<T extends PropertyKey>(propertyKey: T) =>\n\t(array: { [K in T]: any }[]) => {\n\t\tconst values = array.map(item => item[propertyKey]);\n\t\tconst uniqueValues = new Set(values);\n\n\t\tif (values.length !== uniqueValues.size) {\n\t\t\tthrow new Error(`Duplicate values found for property: ${propertyKey.toString()}`);\n\t\t}\n\t\treturn true;\n\t};\n\n/**\n * A destructive way to ensure an object has a property.\n * This is useful when working with unknowns.\n */\nexport function hasProp<K extends PropertyKey>(data: object, prop: K): data is Record<K, unknown> {\n\treturn prop in data;\n}\n\n/**\n * A sort of type-safe way to check whether a key exists in an object.\n */\nexport function isKeyInObj<O extends Record<string, unknown>>(key: PropertyKey, obj: O): key is keyof O {\n\treturn key in obj;\n}\n","type TFunction = (key: 'competitive' | 'invalid_salary' | 'from' | 'up_to') => string;\n\ninterface SalaryParams {\n\tpay: string | null;\n\tpay_min: string | null;\n\tpay_mask: boolean;\n\tpay_max: string | null;\n\tpay_type: 'ANNUALLY' | 'HOURLY' | 'MONTHLY' | 'WEEKLY' | 'DAILY' | null;\n\tpay_currency: string;\n\tpay_display: boolean;\n}\n\nconst payPeriods: Record<NonNullable<SalaryParams['pay_type']>, string> = {\n\tANNUALLY: 'per year',\n\tDAILY: 'per day',\n\tHOURLY: 'per hour',\n\tMONTHLY: 'per month',\n\tWEEKLY: 'per week',\n};\n\nexport const getSalaryAsText = (params: {\n\tsalary: SalaryParams;\n\tconfig: { locales: string | string[] | undefined };\n\tt?: TFunction;\n}) => {\n\tconst { salary, config, t = s => s } = params;\n\tconst numberFormatter = new Intl.NumberFormat(config.locales, {\n\t\tstyle: 'currency',\n\t\tcurrency: salary.pay_currency,\n\t\t// @ts-expect-error - CI/CD is not happy with this, though locally it works\n\t\ttrailingZeroDisplay: 'stripIfInteger',\n\t});\n\tif (salary.pay_display === false) return undefined;\n\tif (salary.pay_mask) return t('competitive');\n\n\tif (salary.pay_max && Number.isNaN(+salary.pay_max)) return t('invalid_salary');\n\tif (salary.pay_min && Number.isNaN(+salary.pay_min)) return t('invalid_salary');\n\tif (salary.pay && Number.isNaN(+salary.pay)) return t('invalid_salary');\n\n\tconst period = salary.pay_type && salary.pay_type in payPeriods ? payPeriods[salary.pay_type] : undefined;\n\n\tif (salary.pay) return [numberFormatter.format(+salary.pay), period].filter(Boolean).join(' ');\n\n\tif (salary.pay_max && salary.pay_min)\n\t\treturn [numberFormatter.formatRange(+salary.pay_min, +salary.pay_max), period].filter(Boolean).join(' ') || '';\n\n\tif (salary.pay_max)\n\t\treturn `${t('up_to')} ${[numberFormatter.format(+salary.pay_max), period].filter(Boolean).join(' ')}`;\n\tif (salary.pay_min)\n\t\treturn `${t('from')} ${[numberFormatter.format(+salary.pay_min), period].filter(Boolean).join(' ')}`;\n\treturn t('invalid_salary');\n};\n","type TFunction = (key: 'today' | 'over_30_days_ago' | 'in_over_30_days') => string;\n\ntype Params = {\n\tfrom?: Date;\n\tto: string | number | Date;\n\tformatter?: Intl.RelativeTimeFormat;\n\tt?: TFunction;\n};\n\nconst DEFAULT_FORMATTER = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });\n/** From a date, calculates the relative time difference from now */\nexport const getRelativeTimeDifference = ({\n\tfrom = new Date(),\n\tto,\n\tformatter = DEFAULT_FORMATTER,\n\tt = s => s,\n}: Params) => {\n\tconst then = to instanceof Date ? to : new Date(to);\n\tconst diff = then.getTime() - from.getTime();\n\n\tconst diffIn = {\n\t\tdays: Math.round(diff / 1000 / 60 / 60 / 24),\n\t\tmonths: Math.round(diff / 1000 / 60 / 60 / 24 / 30),\n\t};\n\n\tif (diffIn.days === 0) return t('today');\n\tif (Math.abs(diffIn.days) < 30) return formatter.format(diffIn.days, 'days');\n\tif (Math.abs(diffIn.days) < 3) return formatter.format(diffIn.months, 'months');\n\treturn diffIn.months < 0 ? t('over_30_days_ago') : t('in_over_30_days');\n};\n","{\n\t\"name\": \"@inploi/sdk\",\n\t\"version\": \"1.14.13\",\n\t\"main\": \"dist/index.js\",\n\t\"types\": \"dist/index.d.ts\",\n\t\"license\": \"MIT\",\n\t\"files\": [\n\t\t\"/dist\",\n\t\t\"/cdn\"\n\t],\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"require\": \"./dist/index.js\",\n\t\t\t\"import\": \"./dist/index.mjs\",\n\t\t\t\"types\": \"./dist/index.d.ts\"\n\t\t}\n\t},\n\t\"scripts\": {\n\t\t\"build:npm\": \"tsup --dts --dts-resolve\",\n\t\t\"build:cdn\": \"tsup --config tsup.cdn.config.ts\",\n\t\t\"build\": \"concurrently 'pnpm run build:npm' 'pnpm run build:cdn'\",\n\t\t\"dev\": \"tsup --watch --config tsup.cdn.config.ts\",\n\t\t\"check\": \"eslint src --fix --max-warnings 0 && tsc\",\n\t\t\"test\": \"bun test\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@happy-dom/global-registrator\": \"^13.6.2\",\n\t\t\"@inploi/core\": \"workspace:*\",\n\t\t\"@total-typescript/ts-reset\": \"^0.5.1\",\n\t\t\"@types/bun\": \"^1.2.5\",\n\t\t\"@types/react\": \"^18.2.33\",\n\t\t\"@types/react-dom\": \"^18.2.14\",\n\t\t\"autoprefixer\": \"^10.4.16\",\n\t\t\"eslint\": \"^7.32.0\",\n\t\t\"eslint-config-custom\": \"workspace:*\",\n\t\t\"happy-dom\": \"^12.6.0\",\n\t\t\"ts-toolbelt\": \"^9.6.0\",\n\t\t\"concurrently\": \"9.1.2\",\n\t\t\"tsconfig\": \"workspace:*\",\n\t\t\"tsup\": \"^7.2.0\"\n\t}\n}\n","import { version } from '../package.json';\n\n/**\n * The environment the SDK should run in.\n * - `production`: data will be stored and displayed on dashboards\n * - `sandbox`: data will be stored temporarily and purged periodically\n */\nexport type InploiSdkEnvironment = 'production' | 'sandbox';\n\nexport const ENV_TO_API_URL: Record<InploiSdkEnvironment, string> = {\n\tsandbox: 'https://api.staging.inploi.com',\n\tproduction: 'https://api.inploi.com',\n\t// @ts-expect-error - local test environment\n\t_internal_local: 'http://api.test',\n};\n\nexport const ANALYTICS_VERSION = version;\n\nexport const LOG_PATHNAME = '/log';\n\nexport const ANALYTICS_COOKIE_NAME = 'isdk_session';\n","import type { ResponseObj } from '@inploi/core/common';\nimport { invariant } from '@inploi/core/common';\n\nimport { ApiClient, Logger } from '.';\nimport { ANALYTICS_COOKIE_NAME, ANALYTICS_VERSION, LOG_PATHNAME } from './sdk.constants';\n\nconst formatCookie = (value: string) => {\n\tconst now = new Date();\n\tnow.setTime(now.getTime() + 7 * 24 * 60 * 60 * 1000); // 7 days expiration\n\n\treturn `${ANALYTICS_COOKIE_NAME}=${value};expires=${now.toUTCString()};path=/`;\n};\n\ntype FlowProperties = { flow_id: string; flow_version: number; flow_session_id: string; flow_build: number };\n\ntype JobProperties = {\n\tid: string;\n\tid_type: 'internal' | 'external';\n};\n\ntype AnalyticsLogParams =\n\t| {\n\t\t\tevent: 'VIEW_JOB';\n\t\t\tproperties: { job: JobProperties };\n\t }\n\t| {\n\t\t\tevent: 'FLOW_REDIRECT';\n\t\t\tproperties: { href: string; job: JobProperties | undefined } & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_START' | 'FLOW_END';\n\t\t\tproperties: { job: JobProperties | undefined } & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_NODE';\n\t\t\tproperties: {\n\t\t\t\t/** Increments by 1 per node interpreted */\n\t\t\t\tsequence: number;\n\t\t\t\tfrom_node_id: string;\n\t\t\t\tto_node_id: string;\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t} & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_SUBMIT';\n\t\t\tproperties: {\n\t\t\t\tservice: string;\n\t\t\t\tresponse: {\n\t\t\t\t\tstatus: number;\n\t\t\t\t\tpayload: unknown;\n\t\t\t\t};\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t} & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'SUBMIT_FORM' | 'VIEW_PAGE';\n\t\t\tproperties?: {\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'IDENTIFY';\n\t\t\tproperties: {\n\t\t\t\tidentifier: string;\n\t\t\t\tfirst_name?: string;\n\t\t\t\tlast_name?: string;\n\t\t\t\tphone_number?: string;\n\t\t\t\temail?: string;\n\t\t\t\tcustom_traits?: Record<string, unknown>;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_PAGINATE';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_SETTLE';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_JOB_CLICK';\n\t\t\tproperties: {\n\t\t\t\tjob_id: number;\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'VIEW_SEARCH';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'FEEDBACK';\n\t\t\tproperties: {\n\t\t\t\tkey: string;\n\t\t\t\tscore?: -1 | 0 | 1;\n\t\t\t\tcomment?: string;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'LINK_CLICK';\n\t\t\tproperties: {\n\t\t\t\ttarget_href: string;\n\t\t\t\tjob_id: string | undefined;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'INTERACTION';\n\t\t\tproperties: {\n\t\t\t\ttag: string;\n\t\t\t};\n\t };\n\nexport type AnalyticsLogEvent = AnalyticsLogParams['event'];\n\ntype EventPropertyMap = {\n\t[Param in AnalyticsLogParams as Param['event']]: Omit<Param, 'event'>;\n};\n\ntype AnalyticsContext = {\n\tlibrary: {\n\t\tname: 'inploi-sdk';\n\t\tversion: string;\n\t};\n\tpage: {\n\t\thref: string;\n\t\treferrer: string;\n\t\ttitle: string;\n\t};\n};\n\ntype TrackPayload<P = EventPropertyMap[keyof EventPropertyMap]['properties']> = {\n\tanonymous_id: string | null;\n\tsession_id: string | null;\n\tevent: AnalyticsLogEvent;\n\tsent_at: string;\n\tcontext: AnalyticsContext;\n\tproperties: P;\n\tcustom_properties?: Record<string, unknown>;\n};\n\ntype LogFnParams<T extends keyof EventPropertyMap> = {\n\tevent: T;\n\tcustomProperties?: Record<string, unknown>;\n\t/** Passing a request will make logging possible on a server environment. */\n\trequest?: Request;\n} & EventPropertyMap[T];\n\ntype LogFn = <TEvent extends keyof EventPropertyMap>(\n\tparams: LogFnParams<TEvent>,\n) => Promise<ResponseObj<TrackPayload<EventPropertyMap[TEvent]['properties']>>>;\n\nexport type AnalyticsService = {\n\tlog: LogFn;\n\t/** From a log payload data, generate headers to use in server environments to update the anonymous_id */\n\tgetHeaders: (payload?: TrackPayload) => Headers;\n\tgetSessionInfo: typeof getSessionInfo;\n};\n\nconst getSessionId = (searchParams: URLSearchParams, isServer: boolean) => {\n\tconst fromSearchParams = searchParams.get('session_id');\n\tif (isServer) return fromSearchParams;\n\tif (fromSearchParams) return fromSearchParams;\n\tconst fromSessionStorage = sessionStorage.getItem(`${ANALYTICS_COOKIE_NAME}-session_id`);\n\tif (typeof fromSessionStorage === 'string') return fromSessionStorage;\n\treturn null;\n};\n\nconst cookieRegex = new RegExp(`${ANALYTICS_COOKIE_NAME}=([^;]+)`);\nconst getSessionInfo = (request?: Request) => {\n\tconst href = request ? request.url : location.href;\n\tconst { searchParams } = new URL(href);\n\tconst anonymous_id = searchParams.get('anonymous_id');\n\tconst session_id = getSessionId(searchParams, typeof window === 'undefined');\n\n\t// If there’s an anonymous_id in the search params, use it\n\tif (anonymous_id)\n\t\treturn {\n\t\t\tanonymous_id,\n\t\t\tsession_id,\n\t\t};\n\n\t// If there’s a cookie, use it\n\tconst cookie = request ? request.headers.get('cookie') : document.cookie;\n\tif (cookie) {\n\t\tconst match = cookieRegex.exec(cookie);\n\t\tconst anonymous_id = match?.[1];\n\t\treturn {\n\t\t\tanonymous_id: anonymous_id ?? null,\n\t\t\tsession_id,\n\t\t};\n\t}\n\n\t// Otherwise, return what we have\n\treturn {\n\t\tanonymous_id,\n\t\tsession_id,\n\t};\n};\n\nconst getSessionInfoFromResponse = (response: unknown) => {\n\tif (typeof response !== 'object' || response === null) return null;\n\treturn {\n\t\tanonymous_id:\n\t\t\t'anonymous_id' in response && typeof response.anonymous_id === 'string' ? response.anonymous_id : null,\n\t\tsession_id: 'session_id' in response && typeof response.session_id === 'string' ? response.session_id : null,\n\t};\n};\n\nconst serverReferrer = (referrer: typeof Request.prototype.referrer) => {\n\tif (referrer === 'about:client') return '';\n\treturn referrer;\n};\n\nexport const createAnalyticsService = ({\n\tapiClient,\n\tlogger,\n}: {\n\tlogger: Logger;\n\tapiClient: ApiClient;\n}): AnalyticsService => {\n\tconst logFn: LogFn = async params => {\n\t\tinvariant(\n\t\t\tparams.request || typeof window !== 'undefined',\n\t\t\t'Cannot log on the server without a request. Please pass a request to `log`.',\n\t\t);\n\n\t\t// if there’s a request, use it instead of browser APIs\n\t\tconst page =\n\t\t\t'request' in params && params.request ?\n\t\t\t\t{\n\t\t\t\t\thref: params.request.url,\n\t\t\t\t\treferrer: serverReferrer(params.request.referrer),\n\t\t\t\t\ttitle: '',\n\t\t\t\t}\n\t\t\t:\t{\n\t\t\t\t\thref: location.href,\n\t\t\t\t\treferrer: document.referrer,\n\t\t\t\t\ttitle: document.title,\n\t\t\t\t};\n\n\t\ttry {\n\t\t\tconst context: AnalyticsContext = {\n\t\t\t\tlibrary: {\n\t\t\t\t\tname: 'inploi-sdk',\n\t\t\t\t\tversion: ANALYTICS_VERSION,\n\t\t\t\t},\n\t\t\t\tpage,\n\t\t\t};\n\n\t\t\tconst sessionInfo = getSessionInfo(params.request);\n\t\t\tconst payload: TrackPayload = {\n\t\t\t\tanonymous_id: sessionInfo.anonymous_id,\n\t\t\t\tsession_id: sessionInfo.session_id,\n\t\t\t\tevent: params.event,\n\t\t\t\tsent_at: new Date().toISOString(),\n\t\t\t\tcontext,\n\t\t\t\tproperties: params.properties,\n\t\t\t\tcustom_properties: params.customProperties,\n\t\t\t};\n\n\t\t\tconst responseJson = await apiClient.fetch(LOG_PATHNAME, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t});\n\n\t\t\tconst newSession = getSessionInfoFromResponse(responseJson);\n\t\t\tif (newSession?.anonymous_id) {\n\t\t\t\tpayload.anonymous_id = newSession.anonymous_id;\n\t\t\t}\n\t\t\tif (newSession?.session_id) {\n\t\t\t\tpayload.session_id = newSession.session_id;\n\t\t\t}\n\n\t\t\tif (typeof window !== 'undefined' && payload.anonymous_id) {\n\t\t\t\tif (payload.session_id) {\n\t\t\t\t\tsessionStorage.setItem(`${ANALYTICS_COOKIE_NAME}-session_id`, payload.session_id.toString());\n\t\t\t\t}\n\t\t\t\tdocument.cookie = formatCookie(payload.anonymous_id);\n\t\t\t}\n\n\t\t\treturn { success: true, data: payload };\n\t\t} catch (e) {\n\t\t\t/** We dont’t log any PII on the console */\n\t\t\tlogger.error('Failed to send log to API. Inspect error response of `log` for more information.');\n\t\t\treturn { success: false, error: e };\n\t\t}\n\t};\n\n\treturn {\n\t\tlog: logFn,\n\t\tgetHeaders: payload => {\n\t\t\tconst headers = new Headers();\n\t\t\tif (!payload?.anonymous_id) return headers;\n\n\t\t\theaders.append('Set-Cookie', formatCookie(payload.anonymous_id));\n\t\t\treturn headers;\n\t\t},\n\t\tgetSessionInfo,\n\t};\n};\n","import { createAnalyticsService } from './sdk.analytics';\nimport { createApiClient } from './sdk.api';\nimport { ENV_TO_API_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger, inploiBrandedLogger, noLogging } from './sdk.logger';\nimport { InploiSdkPlugin } from './sdk.plugins';\n\nexport type InitialiseInploiSdkParams = {\n\t/** Your public API key for the inploi SDK. */\n\tpublishableKey: string;\n\t/** Which app environment to run. This ultimately affects which inploi endpoints to gather data are going to be used.\n\t * Anything other than `production` should be considered a development environment and the data periodicaly purged. */\n\tenv: InploiSdkEnvironment;\n\t/** Logger object that handles logging of different levels.\n\t * You can override this to use your own logger, or to disable logging altogether by passing`false`.\n\t * @default inploiBrandedLogger\n\t * */\n\tlogger?: Logger | false;\n};\n\nexport function initialiseSdk({ publishableKey, env, logger = inploiBrandedLogger }: InitialiseInploiSdkParams) {\n\tconst apiClient = createApiClient({ baseUrl: ENV_TO_API_URL[env], publishableKey });\n\tconst loggerService = logger === false ? noLogging : logger;\n\tconst analytics = createAnalyticsService({ apiClient, logger: loggerService });\n\n\tconst register = <P extends InploiSdkPlugin>(plugin: P): ReturnType<P> => {\n\t\treturn plugin({ logger: loggerService, apiClient, analytics });\n\t};\n\n\treturn { register, analytics, apiClient };\n}\n\nexport type InploiSdk = ReturnType<typeof initialiseSdk>;\n"],"mappings":"0nBAAO,IAAMA,EAAiB,iBACjBC,EAAgB,qCAUhBC,EAA8B,CAC1C,KAAM,IAAIC,IAAS,QAAQ,KAAKH,EAAgBC,EAAe,GAAGE,CAAI,EACtE,MAAO,IAAIA,IAAS,QAAQ,MAAMH,EAAgBC,EAAe,GAAGE,CAAI,EACxE,KAAM,IAAIA,IAAS,QAAQ,KAAKH,EAAgBC,EAAe,GAAGE,CAAI,EACtE,IAAK,IAAIA,IAAS,QAAQ,IAAIH,EAAgBC,EAAe,GAAGE,CAAI,CACrE,EAEaC,EAAoB,CAAE,KAAM,IAAG,GAAW,MAAO,IAAG,GAAW,IAAK,IAAG,GAAW,KAAM,IAAG,EAAU,ECI3G,IAAMC,EAA2CC,GAAgBA,ECtBjE,IAAMC,EAAyB,kBACzBC,EAAsB,+BAEtBC,EAAN,cAA4B,KAAM,CACxC,aAAc,CACb,MAAM,WAAW,EACjB,KAAK,KAAO,eACb,CACD,EAEaC,EAAN,cAAgC,KAAM,CAC5C,YAAYC,EAAkB,CAC7B,MAAMA,GAAA,KAAAA,EAAW,gDAAgD,EACjE,KAAK,KAAO,mBACb,CACD,EAEaC,EAAN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Q,WAAW,SAAS,CAAC,EAE5F,SAAS,OAAS/B,EAAa+B,EAAQ,YAAY,GAG7C,CAAE,QAAS,GAAM,KAAMA,CAAQ,CACvC,OAASI,EAAG,CAEX,OAAAZ,EAAO,MAAM,kFAAkF,EACxF,CAAE,QAAS,GAAO,MAAOY,CAAE,CACnC,CACD,GAIC,WAAYJ,GAAW,CACtB,IAAMK,EAAU,IAAI,QACpB,OAAKL,GAAA,MAAAA,EAAS,cAEdK,EAAQ,OAAO,aAAcpC,EAAa+B,EAAQ,YAAY,CAAC,EACxDK,CACR,EACA,eAAA1B,CACD,GCjTM,SAAS2B,EAAc,CAAE,eAAAC,EAAgB,IAAAC,EAAK,OAAAC,EAASC,CAAoB,EAA8B,CAC/G,IAAMC,EAAYC,EAAgB,CAAE,QAASC,EAAeL,CAAG,EAAG,eAAAD,CAAe,CAAC,EAC5EO,EAAgBL,IAAW,GAAQM,EAAYN,EAC/CO,EAAYC,EAAuB,CAAE,UAAAN,EAAW,OAAQG,CAAc,CAAC,EAM7E,MAAO,CAAE,SAJoCI,GACrCA,EAAO,CAAE,OAAQJ,EAAe,UAAAH,EAAW,UAAAK,CAAU,CAAC,EAG3C,UAAAA,EAAW,UAAAL,CAAU,CACzC","names":["CONSOLE_PREFIX","CONSOLE_STYLE","inploiBrandedLogger","args","noLogging","createPlugin","pluginFn","unauthenticatedMessage","unauthorisedMessage","NotFoundError","UnauthorisedError","message","ApiError","errors","ParsingError","response","createApiClient","params","defaultHeaders","_0","_1","__async","pathname","options","init","__spreadProps","__spreadValues","json","invariant","condition","message","DEFAULT_FORMATTER","version","ENV_TO_API_URL","ANALYTICS_VERSION","version","LOG_PATHNAME","ANALYTICS_COOKIE_NAME","formatCookie","value","now","ANALYTICS_COOKIE_NAME","getSessionId","searchParams","isServer","fromSearchParams","fromSessionStorage","cookieRegex","getSessionInfo","request","href","anonymous_id","session_id","cookie","match","getSessionInfoFromResponse","response","serverReferrer","referrer","createAnalyticsService","apiClient","logger","params","__async","invariant","page","context","ANALYTICS_VERSION","sessionInfo","payload","responseJson","LOG_PATHNAME","newSession","e","headers","initialiseSdk","publishableKey","env","logger","inploiBrandedLogger","apiClient","createApiClient","ENV_TO_API_URL","loggerService","noLogging","analytics","createAnalyticsService","plugin"]}
|
|
1
|
+
{"version":3,"sources":["../src/sdk.logger.ts","../src/sdk.plugins.ts","../src/sdk.api.ts","../../core/src/common/common.utils.ts","../../core/src/common/common.currency.ts","../../core/src/common/common.datetime.ts","../package.json","../src/sdk.constants.ts","../src/sdk.analytics.ts","../src/sdk.rpc.ts","../src/sdk.ts"],"sourcesContent":["export const CONSOLE_PREFIX = '%c[inploi SDK]';\nexport const CONSOLE_STYLE = 'color: #65BC67; font-weight: bold;';\n\ntype LogMessage = (...data: any[]) => void;\nexport type Logger = {\n\twarn: LogMessage;\n\terror: LogMessage;\n\tinfo: LogMessage;\n\tlog: LogMessage;\n};\n\nexport const inploiBrandedLogger: Logger = {\n\twarn: (...args) => console.warn(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\terror: (...args) => console.error(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\tinfo: (...args) => console.info(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\tlog: (...args) => console.log(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n};\n\nexport const noLogging: Logger = { info: () => void 0, error: () => void 0, log: () => void 0, warn: () => void 0 };\n","import { AnalyticsService } from './sdk.analytics';\nimport { ApiClient } from './sdk.api';\nimport { Logger } from './sdk.logger';\nimport { InploiRpcClient } from './sdk.rpc';\n\nexport type PluginParams = {\n\tapiClient: ApiClient;\n\tlogger: Logger;\n};\n\nexport type Plugin<T extends string, P extends Record<string, unknown>> = {\n\tpluginName: T;\n\tpure_createActions: (params: PluginParams) => P;\n};\n\ntype PluginDependencies = {\n\tapiClient: ApiClient;\n\trpcClient: InploiRpcClient;\n\tlogger: Logger;\n\tanalytics: AnalyticsService;\n};\n\nexport type InploiSdkPlugin = (dependencies: PluginDependencies) => any;\n\nexport const createPlugin = <T extends InploiSdkPlugin>(pluginFn: T) => pluginFn;\n","import { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport const unauthenticatedMessage = 'Unauthenticated';\nexport const unauthorisedMessage = 'This action is unauthorized.';\n\nexport class NotFoundError extends Error {\n\tconstructor() {\n\t\tsuper('Not found');\n\t\tthis.name = 'NotFoundError';\n\t}\n}\n\nexport class UnauthorisedError extends Error {\n\tconstructor(message?: string) {\n\t\tsuper(message ?? 'You are not authorised to perform this action.');\n\t\tthis.name = 'UnauthorisedError';\n\t}\n}\n\nexport class SchemaValidationError extends Error {\n\tconstructor(public issues: readonly StandardSchemaV1.Issue[]) {\n\t\tsuper('Schema validation failed');\n\t\tthis.name = 'SchemaValidationError';\n\t}\n}\n\nexport class ApiError extends Error {\n\terrors: unknown[];\n\tconstructor(message: string, errors: unknown[]) {\n\t\tsuper(message);\n\t\tthis.name = 'ApiError';\n\t\tthis.errors = errors;\n\t}\n}\n\nexport class JsonParsingError extends Error {\n\tconstructor(public response?: Response) {\n\t\tsuper('Error parsing response into JSON.');\n\t\tthis.name = 'ParsingError';\n\t}\n}\n\n/** @deprecated - use `JsonParsingError` instead */\nexport class ParsingError extends JsonParsingError {}\n\nexport type ApiClient = {\n\tfetch: (pathname: string, options?: RequestInit) => Promise<unknown>;\n};\n\n/** Throws branded errors when API returns a known error. */\nexport function handleApiExceptions(json: unknown) {\n\tif (typeof json === 'object' && json !== null && 'message' in json && typeof json.message === 'string') {\n\t\tif (json.message === unauthenticatedMessage) {\n\t\t\tthrow new UnauthorisedError('You are not authenticated.');\n\t\t}\n\t\tif (json.message === unauthorisedMessage) {\n\t\t\tthrow new UnauthorisedError();\n\t\t}\n\t\tif ('exception' in json) {\n\t\t\tthrow new ApiError(json.message, [json.exception]);\n\t\t}\n\t\tif ('errors' in json) {\n\t\t\tthrow new ApiError(json.message, Array.isArray(json.errors) ? json.errors : [json.errors]);\n\t\t}\n\t}\n}\n\nexport const createApiClient = (params: { baseUrl: string; publishableKey: string }): ApiClient => {\n\tconst defaultHeaders: HeadersInit = {\n\t\tAccept: 'application/json',\n\t\t'Content-Type': 'application/json',\n\t\t'x-publishable-key': params.publishableKey,\n\t};\n\n\treturn {\n\t\t/** Fetches from a pathname with a pre-established base path.\n\t\t * Parses received output as JSON, and throw if one of the common error messages is received.\n\t\t */\n\t\tfetch: async (pathname, options = {}) => {\n\t\t\tconst init = { ...options, headers: { ...options.headers, ...defaultHeaders } };\n\t\t\tconst response = await fetch(`${params.baseUrl}${pathname}`, init);\n\t\t\tif (response.status === 404) throw new NotFoundError();\n\n\t\t\tconst json = await response.json().catch(async () => {\n\t\t\t\tthrow new JsonParsingError(response);\n\t\t\t});\n\n\t\t\thandleApiExceptions(json);\n\n\t\t\t// We’re assuming no other exceptions have happened.\n\t\t\treturn json;\n\t\t},\n\t};\n};\n","export const exhaustive = (value: never) => {\n\tthrow new Error(`Unhandled discriminated union member: ${JSON.stringify(value)}`);\n};\n\nexport function invariant(condition: any, message?: string): asserts condition {\n\tif (condition) {\n\t\treturn;\n\t}\n\n\tthrow new Error(message);\n}\n\nexport const uniqueOrThrow = <T>(array: T[]) => {\n\tconst uniqueValues = new Set(array);\n\n\tif (array.length !== uniqueValues.size) {\n\t\tthrow new Error('Duplicate values found');\n\t}\n\treturn true;\n};\n\nexport const uniqueByPropertyOrThrow =\n\t<T extends PropertyKey>(propertyKey: T) =>\n\t(array: { [K in T]: any }[]) => {\n\t\tconst values = array.map(item => item[propertyKey]);\n\t\tconst uniqueValues = new Set(values);\n\n\t\tif (values.length !== uniqueValues.size) {\n\t\t\tthrow new Error(`Duplicate values found for property: ${propertyKey.toString()}`);\n\t\t}\n\t\treturn true;\n\t};\n\n/**\n * A destructive way to ensure an object has a property.\n * This is useful when working with unknowns.\n */\nexport function hasProp<K extends PropertyKey>(data: object, prop: K): data is Record<K, unknown> {\n\treturn prop in data;\n}\n\n/**\n * A sort of type-safe way to check whether a key exists in an object.\n */\nexport function isKeyInObj<O extends Record<string, unknown>>(key: PropertyKey, obj: O): key is keyof O {\n\treturn key in obj;\n}\n","type TFunction = (key: 'competitive' | 'invalid_salary' | 'from' | 'up_to') => string;\n\ninterface SalaryParams {\n\tpay: string | null;\n\tpay_min: string | null;\n\tpay_mask: boolean;\n\tpay_max: string | null;\n\tpay_type: 'ANNUALLY' | 'HOURLY' | 'MONTHLY' | 'WEEKLY' | 'DAILY' | null;\n\tpay_currency: string;\n\tpay_display: boolean;\n}\n\nconst payPeriods: Record<NonNullable<SalaryParams['pay_type']>, string> = {\n\tANNUALLY: 'per year',\n\tDAILY: 'per day',\n\tHOURLY: 'per hour',\n\tMONTHLY: 'per month',\n\tWEEKLY: 'per week',\n};\n\nexport const getSalaryAsText = (params: {\n\tsalary: SalaryParams;\n\tconfig: { locales: string | string[] | undefined };\n\tt?: TFunction;\n}) => {\n\tconst { salary, config, t = s => s } = params;\n\tconst numberFormatter = new Intl.NumberFormat(config.locales, {\n\t\tstyle: 'currency',\n\t\tcurrency: salary.pay_currency,\n\t\t// @ts-expect-error - CI/CD is not happy with this, though locally it works\n\t\ttrailingZeroDisplay: 'stripIfInteger',\n\t});\n\tif (salary.pay_display === false) return undefined;\n\tif (salary.pay_mask) return t('competitive');\n\n\tif (salary.pay_max && Number.isNaN(+salary.pay_max)) return t('invalid_salary');\n\tif (salary.pay_min && Number.isNaN(+salary.pay_min)) return t('invalid_salary');\n\tif (salary.pay && Number.isNaN(+salary.pay)) return t('invalid_salary');\n\n\tconst period = salary.pay_type && salary.pay_type in payPeriods ? payPeriods[salary.pay_type] : undefined;\n\n\tif (salary.pay) return [numberFormatter.format(+salary.pay), period].filter(Boolean).join(' ');\n\n\tif (salary.pay_max && salary.pay_min)\n\t\treturn [numberFormatter.formatRange(+salary.pay_min, +salary.pay_max), period].filter(Boolean).join(' ') || '';\n\n\tif (salary.pay_max)\n\t\treturn `${t('up_to')} ${[numberFormatter.format(+salary.pay_max), period].filter(Boolean).join(' ')}`;\n\tif (salary.pay_min)\n\t\treturn `${t('from')} ${[numberFormatter.format(+salary.pay_min), period].filter(Boolean).join(' ')}`;\n\treturn t('invalid_salary');\n};\n","type TFunction = (key: 'today' | 'over_30_days_ago' | 'in_over_30_days') => string;\n\ntype Params = {\n\tfrom?: Date;\n\tto: string | number | Date;\n\tformatter?: Intl.RelativeTimeFormat;\n\tt?: TFunction;\n};\n\nconst DEFAULT_FORMATTER = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });\n/** From a date, calculates the relative time difference from now */\nexport const getRelativeTimeDifference = ({\n\tfrom = new Date(),\n\tto,\n\tformatter = DEFAULT_FORMATTER,\n\tt = s => s,\n}: Params) => {\n\tconst then = to instanceof Date ? to : new Date(to);\n\tconst diff = then.getTime() - from.getTime();\n\n\tconst diffIn = {\n\t\tdays: Math.round(diff / 1000 / 60 / 60 / 24),\n\t\tmonths: Math.round(diff / 1000 / 60 / 60 / 24 / 30),\n\t};\n\n\tif (diffIn.days === 0) return t('today');\n\tif (Math.abs(diffIn.days) < 30) return formatter.format(diffIn.days, 'days');\n\tif (Math.abs(diffIn.days) < 3) return formatter.format(diffIn.months, 'months');\n\treturn diffIn.months < 0 ? t('over_30_days_ago') : t('in_over_30_days');\n};\n","{\n\t\"name\": \"@inploi/sdk\",\n\t\"version\": \"1.15.0\",\n\t\"main\": \"dist/index.js\",\n\t\"types\": \"dist/index.d.ts\",\n\t\"license\": \"MIT\",\n\t\"files\": [\n\t\t\"/dist\",\n\t\t\"/cdn\"\n\t],\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"require\": \"./dist/index.js\",\n\t\t\t\"import\": \"./dist/index.mjs\",\n\t\t\t\"types\": \"./dist/index.d.ts\"\n\t\t}\n\t},\n\t\"scripts\": {\n\t\t\"build:npm\": \"tsup --dts --dts-resolve\",\n\t\t\"build:cdn\": \"tsup --config tsup.cdn.config.ts\",\n\t\t\"build\": \"concurrently 'pnpm run build:npm' 'pnpm run build:cdn'\",\n\t\t\"dev\": \"tsup --watch --config tsup.cdn.config.ts\",\n\t\t\"check\": \"eslint src --fix --max-warnings 0 && tsc\",\n\t\t\"test\": \"bun test\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@happy-dom/global-registrator\": \"^13.6.2\",\n\t\t\"@inploi/core\": \"workspace:*\",\n\t\t\"@total-typescript/ts-reset\": \"^0.5.1\",\n\t\t\"@types/bun\": \"^1.2.5\",\n\t\t\"@types/react\": \"^18.2.33\",\n\t\t\"@types/react-dom\": \"^18.2.14\",\n\t\t\"autoprefixer\": \"^10.4.16\",\n\t\t\"concurrently\": \"9.1.2\",\n\t\t\"eslint\": \"^7.32.0\",\n\t\t\"eslint-config-custom\": \"workspace:*\",\n\t\t\"happy-dom\": \"^12.6.0\",\n\t\t\"ts-toolbelt\": \"^9.6.0\",\n\t\t\"tsconfig\": \"workspace:*\",\n\t\t\"tsup\": \"^7.2.0\"\n\t},\n\t\"dependencies\": {\n\t\t\"@standard-schema/spec\": \"^1.0.0\",\n\t\t\"neoqs\": \"^6.13.0\"\n\t}\n}\n","import { version } from '../package.json';\n\n/**\n * The environment the SDK should run in.\n * - `production`: data will be stored and displayed on dashboards\n * - `sandbox`: data will be stored temporarily and purged periodically\n */\nexport type InploiSdkEnvironment = 'production' | 'sandbox';\n\nexport const ENV_TO_API_URL: Record<InploiSdkEnvironment, string> = {\n\tsandbox: 'https://api.staging.inploi.com',\n\tproduction: 'https://api.inploi.com',\n\t// @ts-expect-error - local test environment\n\t_internal_local: 'http://api.test',\n};\n\nexport const ANALYTICS_VERSION = version;\n\nexport const LOG_PATHNAME = '/log';\n\nexport const ANALYTICS_COOKIE_NAME = 'isdk_session';\n","import type { ResponseObj } from '@inploi/core/common';\nimport { invariant } from '@inploi/core/common';\n\nimport { InploiRpcClient, Logger, endpoint, typed } from '.';\nimport { ANALYTICS_COOKIE_NAME, ANALYTICS_VERSION } from './sdk.constants';\n\nconst formatCookie = (value: string) => {\n\tconst now = new Date();\n\tnow.setTime(now.getTime() + 7 * 24 * 60 * 60 * 1000); // 7 days expiration\n\n\treturn `${ANALYTICS_COOKIE_NAME}=${value};expires=${now.toUTCString()};path=/`;\n};\n\ntype FlowProperties = { flow_id: string; flow_version: number; flow_session_id: string; flow_build: number };\n\ntype JobProperties = {\n\tid: string;\n\tid_type: 'internal' | 'external';\n};\n\ntype AnalyticsLogParams =\n\t| {\n\t\t\tevent: 'VIEW_JOB';\n\t\t\tproperties: { job: JobProperties };\n\t }\n\t| {\n\t\t\tevent: 'FLOW_REDIRECT';\n\t\t\tproperties: { href: string; job: JobProperties | undefined } & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_START' | 'FLOW_END';\n\t\t\tproperties: { job: JobProperties | undefined } & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_NODE';\n\t\t\tproperties: {\n\t\t\t\t/** Increments by 1 per node interpreted */\n\t\t\t\tsequence: number;\n\t\t\t\tfrom_node_id: string;\n\t\t\t\tto_node_id: string;\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t} & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_SUBMIT';\n\t\t\tproperties: {\n\t\t\t\tservice: string;\n\t\t\t\tresponse: {\n\t\t\t\t\tstatus: number;\n\t\t\t\t\tpayload: unknown;\n\t\t\t\t};\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t} & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'SUBMIT_FORM' | 'VIEW_PAGE';\n\t\t\tproperties?: {\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'IDENTIFY';\n\t\t\tproperties: {\n\t\t\t\tidentifier: string;\n\t\t\t\tfirst_name?: string;\n\t\t\t\tlast_name?: string;\n\t\t\t\tphone_number?: string;\n\t\t\t\temail?: string;\n\t\t\t\tcustom_traits?: Record<string, unknown>;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_PAGINATE';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_SETTLE';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_JOB_CLICK';\n\t\t\tproperties: {\n\t\t\t\tjob_id: number;\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'VIEW_SEARCH';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'FEEDBACK';\n\t\t\tproperties: {\n\t\t\t\tkey: string;\n\t\t\t\tscore?: -1 | 0 | 1;\n\t\t\t\tcomment?: string;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'LINK_CLICK';\n\t\t\tproperties: {\n\t\t\t\ttarget_href: string;\n\t\t\t\tjob_id: string | undefined;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'INTERACTION';\n\t\t\tproperties: {\n\t\t\t\ttag: string;\n\t\t\t};\n\t };\n\nexport type AnalyticsLogEvent = AnalyticsLogParams['event'];\n\ntype EventPropertyMap = {\n\t[Param in AnalyticsLogParams as Param['event']]: Omit<Param, 'event'>;\n};\n\ntype AnalyticsContext = {\n\tlibrary: {\n\t\tname: 'inploi-sdk';\n\t\tversion: string;\n\t};\n\tpage: {\n\t\thref: string;\n\t\treferrer: string;\n\t\ttitle: string;\n\t};\n};\n\ntype TrackPayload<P = EventPropertyMap[keyof EventPropertyMap]['properties']> = {\n\tanonymous_id: string | null;\n\tsession_id: string | null;\n\tevent: AnalyticsLogEvent;\n\tsent_at: string;\n\tcontext: AnalyticsContext;\n\tproperties: P;\n\tcustom_properties?: Record<string, unknown>;\n};\n\ntype LogFnParams<T extends keyof EventPropertyMap> = {\n\tevent: T;\n\tcustomProperties?: Record<string, unknown>;\n\t/** Passing a request will make logging possible on a server environment. */\n\trequest?: Request;\n} & EventPropertyMap[T];\n\ntype LogFn = <TEvent extends keyof EventPropertyMap>(\n\tparams: LogFnParams<TEvent>,\n) => Promise<ResponseObj<TrackPayload<EventPropertyMap[TEvent]['properties']>>>;\n\nexport type AnalyticsService = {\n\tlog: LogFn;\n\t/** From a log payload data, generate headers to use in server environments to update the anonymous_id */\n\tgetHeaders: (payload?: TrackPayload) => Headers;\n\tgetSessionInfo: typeof getSessionInfo;\n};\n\nconst getSessionId = (searchParams: URLSearchParams, isServer: boolean) => {\n\tconst fromSearchParams = searchParams.get('session_id');\n\tif (isServer) return fromSearchParams;\n\tif (fromSearchParams) return fromSearchParams;\n\tconst fromSessionStorage = sessionStorage.getItem(`${ANALYTICS_COOKIE_NAME}-session_id`);\n\tif (typeof fromSessionStorage === 'string') return fromSessionStorage;\n\treturn null;\n};\n\nconst cookieRegex = new RegExp(`${ANALYTICS_COOKIE_NAME}=([^;]+)`);\nconst getSessionInfo = (request?: Request) => {\n\tconst href = request ? request.url : location.href;\n\tconst { searchParams } = new URL(href);\n\tconst anonymous_id = searchParams.get('anonymous_id');\n\tconst session_id = getSessionId(searchParams, typeof window === 'undefined');\n\n\t// If there’s an anonymous_id in the search params, use it\n\tif (anonymous_id)\n\t\treturn {\n\t\t\tanonymous_id,\n\t\t\tsession_id,\n\t\t};\n\n\t// If there’s a cookie, use it\n\tconst cookie = request ? request.headers.get('cookie') : document.cookie;\n\tif (cookie) {\n\t\tconst match = cookieRegex.exec(cookie);\n\t\tconst anonymous_id = match?.[1];\n\t\treturn {\n\t\t\tanonymous_id: anonymous_id ?? null,\n\t\t\tsession_id,\n\t\t};\n\t}\n\n\t// Otherwise, return what we have\n\treturn {\n\t\tanonymous_id,\n\t\tsession_id,\n\t};\n};\n\nconst getSessionInfoFromResponse = (response: unknown) => {\n\tif (typeof response !== 'object' || response === null) return null;\n\treturn {\n\t\tanonymous_id:\n\t\t\t'anonymous_id' in response && typeof response.anonymous_id === 'string' ? response.anonymous_id : null,\n\t\tsession_id: 'session_id' in response && typeof response.session_id === 'string' ? response.session_id : null,\n\t};\n};\n\nconst serverReferrer = (referrer: typeof Request.prototype.referrer) => {\n\tif (referrer === 'about:client') return '';\n\treturn referrer;\n};\n\nconst analyticsLogEndpoint = endpoint({\n\tpathname: '/log',\n\tmethod: 'POST',\n\tschema: {\n\t\tresponse: typed<unknown>(),\n\t\tsearchParams: typed<TrackPayload>(),\n\t},\n});\n\nexport const createAnalyticsService = ({\n\trpcClient,\n\tlogger,\n}: {\n\tlogger: Logger;\n\trpcClient: InploiRpcClient;\n}): AnalyticsService => {\n\tconst logFn: LogFn = async params => {\n\t\tinvariant(\n\t\t\tparams.request || typeof window !== 'undefined',\n\t\t\t'Cannot log on the server without a request. Please pass a request to `log`.',\n\t\t);\n\n\t\t// if there’s a request, use it instead of browser APIs\n\t\tconst page =\n\t\t\t'request' in params && params.request ?\n\t\t\t\t{\n\t\t\t\t\thref: params.request.url,\n\t\t\t\t\treferrer: serverReferrer(params.request.referrer),\n\t\t\t\t\ttitle: '',\n\t\t\t\t}\n\t\t\t:\t{\n\t\t\t\t\thref: location.href,\n\t\t\t\t\treferrer: document.referrer,\n\t\t\t\t\ttitle: document.title,\n\t\t\t\t};\n\n\t\ttry {\n\t\t\tconst context: AnalyticsContext = {\n\t\t\t\tlibrary: {\n\t\t\t\t\tname: 'inploi-sdk',\n\t\t\t\t\tversion: ANALYTICS_VERSION,\n\t\t\t\t},\n\t\t\t\tpage,\n\t\t\t};\n\n\t\t\tconst sessionInfo = getSessionInfo(params.request);\n\t\t\tconst payload: TrackPayload = {\n\t\t\t\tanonymous_id: sessionInfo.anonymous_id,\n\t\t\t\tsession_id: sessionInfo.session_id,\n\t\t\t\tevent: params.event,\n\t\t\t\tsent_at: new Date().toISOString(),\n\t\t\t\tcontext,\n\t\t\t\tproperties: params.properties,\n\t\t\t\tcustom_properties: params.customProperties,\n\t\t\t};\n\n\t\t\tconst responseJson = await rpcClient.request(analyticsLogEndpoint, {\n\t\t\t\tsearchParams: payload,\n\t\t\t});\n\n\t\t\tconst newSession = getSessionInfoFromResponse(responseJson);\n\t\t\tif (newSession?.anonymous_id) {\n\t\t\t\tpayload.anonymous_id = newSession.anonymous_id;\n\t\t\t}\n\t\t\tif (newSession?.session_id) {\n\t\t\t\tpayload.session_id = newSession.session_id;\n\t\t\t}\n\n\t\t\tif (typeof window !== 'undefined' && payload.anonymous_id) {\n\t\t\t\tif (payload.session_id) {\n\t\t\t\t\tsessionStorage.setItem(`${ANALYTICS_COOKIE_NAME}-session_id`, payload.session_id.toString());\n\t\t\t\t}\n\t\t\t\tdocument.cookie = formatCookie(payload.anonymous_id);\n\t\t\t}\n\n\t\t\treturn { success: true, data: payload };\n\t\t} catch (e) {\n\t\t\t/** We dont’t log any PII on the console */\n\t\t\tlogger.error('Failed to send log to API. Inspect error response of `log` for more information.');\n\t\t\treturn { success: false, error: e };\n\t\t}\n\t};\n\n\treturn {\n\t\tlog: logFn,\n\t\tgetHeaders: payload => {\n\t\t\tconst headers = new Headers();\n\t\t\tif (!payload?.anonymous_id) return headers;\n\n\t\t\theaders.append('Set-Cookie', formatCookie(payload.anonymous_id));\n\t\t\treturn headers;\n\t\t},\n\t\tgetSessionInfo,\n\t};\n};\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { stringify } from 'neoqs';\n\nimport { JsonParsingError, SchemaValidationError, handleApiExceptions } from './sdk.api';\nimport { ENV_TO_API_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger } from './sdk.logger';\n\ntype RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\n/** Extract parameter names from a pathname string */\ntype ExtractParamNames<T extends string> =\n\tT extends `${infer _Before}:${infer Param}/${infer After}` ? Param | ExtractParamNames<`/${After}`>\n\t: T extends `${infer _Before}:${infer Param}` ? Param\n\t: never;\n\n/** Create params object from parameter names */\ntype ExtractPathParams<T extends string> =\n\tstring extends T ? Record<string, string | number>\n\t: ExtractParamNames<T> extends never ? Record<string, never>\n\t: { [K in ExtractParamNames<T>]: string | number };\n\n/** Parses a StandardSchemaV1 schema and input into an output. */\nexport function parse<T extends StandardSchemaV1>(\n\tschema: T,\n\tinput: StandardSchemaV1.InferInput<T>,\n): StandardSchemaV1.InferOutput<T> {\n\tconst result = schema['~standard'].validate(input);\n\tif (result instanceof Promise) {\n\t\tthrow new TypeError('Async schema');\n\t}\n\n\tif (result.issues) {\n\t\tthrow new SchemaValidationError(result.issues);\n\t}\n\n\treturn result.value;\n}\n\n/** Parses a StandardSchemaV1 schema and input into an output, returning a success flag and issues if the parse fails. */\nexport function safeParse<T extends StandardSchemaV1>(\n\tschema: T,\n\tinput: StandardSchemaV1.InferInput<T>,\n):\n\t| {\n\t\t\tsuccess: true;\n\t\t\toutput: StandardSchemaV1.InferOutput<T>;\n\t }\n\t| {\n\t\t\tsuccess: false;\n\t\t\tissues: readonly StandardSchemaV1.Issue[];\n\t } {\n\ttry {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\toutput: parse(schema, input),\n\t\t};\n\t} catch (e) {\n\t\tif (e instanceof SchemaValidationError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tissues: e.issues,\n\t\t\t};\n\t\t}\n\t\tthrow e;\n\t}\n}\n\nexport interface InploiRpcClientParams {\n\tenvironment: InploiSdkEnvironment;\n\tlogger: Logger;\n\tapiKey:\n\t\t| {\n\t\t\t\t/** Makes the API call with an x-secret-key header\n\t\t\t\t * This will error if used in a browser environment.\n\t\t\t\t */\n\t\t\t\ttype: 'secret';\n\t\t\t\tkey: string;\n\t\t }\n\t\t| {\n\t\t\t\t/** Makes the API call with an x-publishable-key header\n\t\t\t\t * This can be called in a browser or server environment.\n\t\t\t\t */\n\t\t\t\ttype: 'publishable';\n\t\t\t\tkey: string;\n\t\t };\n}\n\n/** RPC client for making API calls to the Inploi API. */\nexport class InploiRpcClient {\n\tprivate baseUrl: string;\n\tprivate headers: Headers;\n\tprivate logger: Logger;\n\n\tconstructor(params: InploiRpcClientParams) {\n\t\tthis.baseUrl = ENV_TO_API_URL[params.environment];\n\t\tthis.headers = new Headers({\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAccept: 'application/json',\n\t\t});\n\t\tif (params.apiKey.type === 'secret') {\n\t\t\tif (typeof window !== 'undefined') {\n\t\t\t\tthrow new Error('Secret key cannot be used in a browser environment');\n\t\t\t}\n\t\t\tthis.headers.set('x-secret-key', params.apiKey.key);\n\t\t} else {\n\t\t\tthis.headers.set('x-publishable-key', params.apiKey.key);\n\t\t}\n\t\tthis.logger = params.logger;\n\t}\n\n\t/** Fetches, parses and validates an API endpoint.\n\t * Logs errors and throws them again so that the caller can handle them.\n\t *\n\t * @throws {JsonParsingError} - If the response is not valid JSON.\n\t * @throws {SchemaValidationError} - If the searchParams, body or response does not match the schema.\n\t * @throws {ApiError} - If the API responded with an error message.\n\t * @throws {UnauthorisedError} - If the request is unauthorised either by missing key or unmet permissions.\n\t * @throws {NotFoundError} - If the endpoint is not found.\n\t * @throws {Error} - Another unhandled error.\n\t */\n\tasync request<T extends RpcEndpoint>(\n\t\tendpoint: T,\n\t\toptions: T extends RpcEndpoint<infer _, infer _TPathname, infer TPathParams, infer TSearch, infer TBody> ?\n\t\t\tGetSchemaValues<{\n\t\t\t\tbody: TBody;\n\t\t\t\tsearchParams: TSearch;\n\t\t\t\tparams: TPathParams;\n\t\t\t}> & { signal?: AbortSignal }\n\t\t:\tnever,\n\t) {\n\t\ttry {\n\t\t\tconst url = new URL(this.baseUrl);\n\n\t\t\t// Replace path parameters in pathname\n\t\t\tlet pathname = endpoint.pathname;\n\t\t\tif ('params' in options && options.params) {\n\t\t\t\tfor (const [key, value] of Object.entries(options.params)) {\n\t\t\t\t\tpathname = pathname.replace(`:${key}`, String(value));\n\t\t\t\t}\n\t\t\t}\n\t\t\turl.pathname = pathname;\n\n\t\t\tif (endpoint.schema.searchParams) {\n\t\t\t\turl.search = stringify(\n\t\t\t\t\tparse(endpoint.schema.searchParams, 'searchParams' in options ? options.searchParams : {}),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst body =\n\t\t\t\tendpoint.schema.body ? parse(endpoint.schema.body, 'body' in options ? options.body : {}) : undefined;\n\n\t\t\tconst response = await fetch(url.toString(), {\n\t\t\t\tmethod: endpoint.method,\n\t\t\t\tbody: body ? JSON.stringify(body) : undefined,\n\t\t\t\theaders: this.headers,\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\n\t\t\tconst json = await response.json().catch(e => {\n\t\t\t\tthis.logger.error(e);\n\t\t\t\tthrow new JsonParsingError(response);\n\t\t\t});\n\n\t\t\tconst result = safeParse(endpoint.schema.response, json);\n\t\t\tif (!result.success) {\n\t\t\t\thandleApiExceptions(json);\n\t\t\t\tthrow new SchemaValidationError(result.issues);\n\t\t\t}\n\n\t\t\treturn result.output as StandardSchemaV1.InferOutput<T['schema']['response']>;\n\t\t} catch (e) {\n\t\t\tif (e instanceof SchemaValidationError) {\n\t\t\t\tthis.logger.error(e.message, e.issues);\n\t\t\t} else {\n\t\t\t\tthis.logger.error(e);\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n}\n\ntype GetSchemaValues<T extends { searchParams: any; body: any; params?: any }> = {\n\t[K in keyof T as T[K] extends never ? never\n\t: T[K] extends Record<string, never> ? never\n\t: K]: T[K] extends never ? never : T[K];\n};\n\n/**\n * Typed but *not runtime validated* schema\n * useful for type-checking the schema without bundling validation schemas\n */\nexport function typed<T>(): StandardSchemaV1<T, T> {\n\treturn {\n\t\t'~standard': {\n\t\t\tvendor: 'inploi',\n\t\t\tversion: 1,\n\t\t\tvalidate: input => {\n\t\t\t\treturn {\n\t\t\t\t\tvalue: input as T,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t};\n}\n\nexport interface RpcEndpoint<\n\tTMethod extends RequestMethod = RequestMethod,\n\tTPathname extends string = string,\n\tTPathParams = any,\n\tTSearch = any,\n\tTBody = any,\n\tTResponse = any,\n> {\n\tpathname: TPathname;\n\tmethod: TMethod;\n\theaders?: Headers;\n\tschema: {\n\t\tsearchParams?: StandardSchemaV1<TSearch, TSearch>;\n\t\tbody?: StandardSchemaV1<TBody, TBody>;\n\t\tresponse: StandardSchemaV1<TResponse, TResponse>;\n\t};\n\t/** Type-only property to store path parameter types */\n\treadonly __pathParams?: TPathParams;\n}\n\nexport function endpoint<\n\tTMethod extends RequestMethod,\n\tTPathname extends string,\n\tTSearch extends StandardSchemaV1 | never = never,\n\tTBody extends StandardSchemaV1 | never = never,\n\tTResponse extends StandardSchemaV1 | never = never,\n>(endpoint: {\n\tpathname: TPathname;\n\tmethod: TMethod;\n\theaders?: Headers;\n\tschema: {\n\t\tsearchParams?: TSearch;\n\t\tbody?: TBody;\n\t\tresponse: TResponse;\n\t};\n}) {\n\ttype PathParams = ExtractPathParams<TPathname>;\n\treturn endpoint as RpcEndpoint<\n\t\tTMethod,\n\t\tTPathname,\n\t\tPathParams,\n\t\tStandardSchemaV1.InferInput<TSearch>,\n\t\tStandardSchemaV1.InferInput<TBody>,\n\t\tStandardSchemaV1.InferOutput<TResponse>\n\t>;\n}\n","import { createAnalyticsService } from './sdk.analytics';\nimport { createApiClient } from './sdk.api';\nimport { ENV_TO_API_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger, inploiBrandedLogger, noLogging } from './sdk.logger';\nimport { InploiSdkPlugin } from './sdk.plugins';\nimport { InploiRpcClient } from './sdk.rpc';\n\nexport type InitialiseInploiSdkParams = {\n\t/** Your public API key for the inploi SDK. */\n\tpublishableKey: string;\n\t/** Which app environment to run. This ultimately affects which inploi endpoints to gather data are going to be used.\n\t * Anything other than `production` should be considered a development environment and the data periodicaly purged. */\n\tenv: InploiSdkEnvironment;\n\t/** Logger object that handles logging of different levels.\n\t * You can override this to use your own logger, or to disable logging altogether by passing`false`.\n\t * @default inploiBrandedLogger\n\t * */\n\tlogger?: Logger | false;\n};\n\nexport function initialiseSdk({ publishableKey, env, logger = inploiBrandedLogger }: InitialiseInploiSdkParams) {\n\t/** @deprecated - use `rpcClient` instead */\n\tconst apiClient = createApiClient({ baseUrl: ENV_TO_API_URL[env], publishableKey });\n\tconst loggerService = logger === false ? noLogging : logger;\n\tconst rpcClient = new InploiRpcClient({\n\t\tenvironment: env,\n\t\tapiKey: { type: 'publishable', key: publishableKey },\n\t\tlogger: loggerService,\n\t});\n\tconst analytics = createAnalyticsService({ rpcClient, logger: loggerService });\n\n\tconst register = <P extends InploiSdkPlugin>(plugin: P): ReturnType<P> => {\n\t\treturn plugin({ logger: loggerService, apiClient, analytics, rpcClient });\n\t};\n\n\treturn { register, analytics, apiClient };\n}\n\nexport type InploiSdk = ReturnType<typeof initialiseSdk>;\n"],"mappings":"0nBAAO,IAAMA,EAAiB,iBACjBC,EAAgB,qCAUhBC,EAA8B,CAC1C,KAAM,IAAIC,IAAS,QAAQ,KAAKH,EAAgBC,EAAe,GAAGE,CAAI,EACtE,MAAO,IAAIA,IAAS,QAAQ,MAAMH,EAAgBC,EAAe,GAAGE,CAAI,EACxE,KAAM,IAAIA,IAAS,QAAQ,KAAKH,EAAgBC,EAAe,GAAGE,CAAI,EACtE,IAAK,IAAIA,IAAS,QAAQ,IAAIH,EAAgBC,EAAe,GAAGE,CAAI,CACrE,EAEaC,EAAoB,CAAE,KAAM,IAAG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CAAC,EAEKS,EAAO,MAAMD,EAAS,KAAK,EAAE,MAAMb,GAAK,CAC7C,WAAK,OAAO,MAAMA,CAAC,EACb,IAAIe,EAAiBF,CAAQ,CACpC,CAAC,EAEKhB,EAASE,GAAUK,EAAS,OAAO,SAAUU,CAAI,EACvD,GAAI,CAACjB,EAAO,QACX,MAAAmB,EAAoBF,CAAI,EAClB,IAAIhB,EAAsBD,EAAO,MAAM,EAG9C,OAAOA,EAAO,MACf,OAASG,EAAG,CACX,MAAIA,aAAaF,EAChB,KAAK,OAAO,MAAME,EAAE,QAASA,EAAE,MAAM,EAErC,KAAK,OAAO,MAAMA,CAAC,EAEdA,CACP,CACD,GACD,EAYO,SAASiB,GAAmC,CAClD,MAAO,CACN,YAAa,CACZ,OAAQ,SACR,QAAS,EACT,SAAUrB,IACF,CACN,MAAOA,CACR,EAEF,CACD,CACD,CAsBO,SAASQ,EAMdA,EASC,CAEF,OAAOA,CAQR,CCtOO,SAASc,GAAc,CAAE,eAAAC,EAAgB,IAAAC,EAAK,OAAAC,EAASC,CAAoB,EAA8B,CAE/G,IAAMC,EAAYC,EAAgB,CAAE,QAASC,EAAeL,CAAG,EAAG,eAAAD,CAAe,CAAC,EAC5EO,EAAgBL,IAAW,GAAQM,EAAYN,EAC/CO,EAAY,IAAIC,EAAgB,CACrC,YAAaT,EACb,OAAQ,CAAE,KAAM,cAAe,IAAKD,CAAe,EACnD,OAAQO,CACT,CAAC,EACKI,EAAYC,EAAuB,CAAE,UAAAH,EAAW,OAAQF,CAAc,CAAC,EAM7E,MAAO,CAAE,SAJoCM,GACrCA,EAAO,CAAE,OAAQN,EAAe,UAAAH,EAAW,UAAAO,EAAW,UAAAF,CAAU,CAAC,EAGtD,UAAAE,EAAW,UAAAP,CAAU,CACzC","names":["CONSOLE_PREFIX","CONSOLE_STYLE","inploiBrandedLogger","args","noLogging","createPlugin","pluginFn","unauthenticatedMessage","unauthorisedMessage","NotFoundError","UnauthorisedError","message","SchemaValidationError","issues","ApiError","errors","JsonParsingError","response","handleApiExceptions","json","unauthenticatedMessage","UnauthorisedError","unauthorisedMessage","ApiError","createApiClient","params","defaultHeaders","_0","_1","__async","pathname","options","init","__spreadProps","__spreadValues","response","NotFoundError","JsonParsingError","invariant","condition","message","DEFAULT_FORMATTER","version","ENV_TO_API_URL","ANALYTICS_VERSION","version","ANALYTICS_COOKIE_NAME","formatCookie","value","now","ANALYTICS_COOKIE_NAME","getSessionId","searchParams","isServer","fromSearchParams","fromSessionStorage","cookieRegex","getSessionInfo","request","href","anonymous_id","session_id","cookie","match","getSessionInfoFromResponse","response","serverReferrer","referrer","analyticsLogEndpoint","typed","createAnalyticsService","rpcClient","logger","params","__async","invariant","page","context","ANALYTICS_VERSION","sessionInfo","payload","responseJson","newSession","e","headers","stringify","parse","schema","input","result","SchemaValidationError","safeParse","e","InploiRpcClient","params","ENV_TO_API_URL","endpoint","options","__async","url","pathname","key","value","stringify","body","response","json","JsonParsingError","handleApiExceptions","typed","initialiseSdk","publishableKey","env","logger","inploiBrandedLogger","apiClient","createApiClient","ENV_TO_API_URL","loggerService","noLogging","rpcClient","InploiRpcClient","analytics","createAnalyticsService","plugin"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inploi/sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.15.0",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"license": "MIT",
|
|
@@ -22,15 +22,19 @@
|
|
|
22
22
|
"@types/react": "^18.2.33",
|
|
23
23
|
"@types/react-dom": "^18.2.14",
|
|
24
24
|
"autoprefixer": "^10.4.16",
|
|
25
|
+
"concurrently": "9.1.2",
|
|
25
26
|
"eslint": "^7.32.0",
|
|
26
27
|
"happy-dom": "^12.6.0",
|
|
27
28
|
"ts-toolbelt": "^9.6.0",
|
|
28
|
-
"concurrently": "9.1.2",
|
|
29
29
|
"tsup": "^7.2.0",
|
|
30
|
-
"eslint-config-custom": "0.1.0",
|
|
31
30
|
"@inploi/core": "1.16.0",
|
|
31
|
+
"eslint-config-custom": "0.1.0",
|
|
32
32
|
"tsconfig": "0.1.0"
|
|
33
33
|
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@standard-schema/spec": "^1.0.0",
|
|
36
|
+
"neoqs": "^6.13.0"
|
|
37
|
+
},
|
|
34
38
|
"scripts": {
|
|
35
39
|
"build:npm": "tsup --dts --dts-resolve",
|
|
36
40
|
"build:cdn": "tsup --config tsup.cdn.config.ts",
|