@inploi/sdk 2.0.1 → 2.0.2
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.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 +4 -4
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 En=Object.defineProperty,wn=Object.defineProperties;var Sn=Object.getOwnPropertyDescriptors;var Xe=Object.getOwnPropertySymbols;var In=Object.prototype.hasOwnProperty,An=Object.prototype.propertyIsEnumerable;var He=(e,r,n)=>r in e?En(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n,P=(e,r)=>{for(var n in r||(r={}))In.call(r,n)&&He(e,n,r[n]);if(Xe)for(var n of Xe(r))An.call(r,n)&&He(e,n,r[n]);return e},R=(e,r)=>wn(e,Sn(r));var A=(e,r,n)=>new Promise((t,s)=>{var i=o=>{try{l(n.next(o))}catch(p){s(p)}},u=o=>{try{l(n.throw(o))}catch(p){s(p)}},l=o=>o.done?t(o.value):Promise.resolve(o.value).then(i,u);l((n=n.apply(e,r)).next())});function ve(e,r){if(!e)throw new Error(r)}function ge(e,r){return r in e}var br=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});var te="%c[inploi SDK]",ie="color: #65BC67; font-weight: bold;",be={warn:(...e)=>console.warn(te,ie,...e),error:(...e)=>console.error(te,ie,...e),info:(...e)=>console.info(te,ie,...e),log:(...e)=>console.log(te,ie,...e)},ke={info:()=>{},error:()=>{},log:()=>{},warn:()=>{}};var Tn="Unauthenticated",Pn="This action is unauthorized.",F=class extends Error{constructor(n,t){super(n);this.status=t,this.name="ErrorWithStatus"}},X=class extends F{constructor(r){super(r!=null?r:"Not found"),this.name="NotFoundError",this.status=404}},H=class extends F{constructor(r,n){super(r!=null?r:"You are not authorised to perform this action."),this.name="UnauthorisedError",this.status=n!=null?n:401}},N=class extends F{constructor(n,t){let s=t?` in ${t}`:"";super(`Schema validation failed${s}`);this.issues=n;this.source=t;this.name="SchemaValidationError",this.status=400}},se=class extends F{constructor(r,n){super(r),this.name="ApiError",this.status=n!=null?n:500}},G=class extends F{constructor(n){super("Error parsing response into JSON.");this.response=n;this.name="ParsingError",this.status=500}};var Dn=["message","error","errors","exception","exceptions"];function jn(e){console.log("json",e);let r=[];if(typeof e=="object"&&e!==null){for(let n of Dn)if(ge(e,n)){console.log("hasProp",n,e[n]);let t=e[n];typeof t=="string"&&r.push(t),Array.isArray(t)&&t.every(s=>typeof s=="string")&&r.push(...t)}}return r.length===0&&r.push("Unknown error"),r.join(", ")}function xe(e,r){if(r>=300&&r<=500){let n=jn(e);throw r===404?new X(n):n===Tn?new H("You are not authenticated.",r):n===Pn?new H(n,r):new se(n,r)}}var We=e=>{let r={Accept:"application/json","Content-Type":"application/json","x-publishable-key":e.publishableKey};return{fetch:(s,...i)=>A(void 0,[s,...i],function*(n,t={}){let u=R(P({},t),{headers:P(P({},t.headers),r)}),l=yield fetch(`${e.baseUrl}${n}`,u);if(l.status===404)throw new X;let o=yield l.json().catch(()=>A(void 0,null,function*(){throw new G(l)}));return xe(o,l.status),o})}};var we="RFC3986",Se={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},On="RFC1738";var Rn=Array.isArray,D=(()=>{let e=[];for(let r=0;r<256;++r)e.push("%"+((r<16?"0":"")+r.toString(16)).toUpperCase());return e})();var _e=1024,Cn=(e,r,n,t,s)=>{if(e.length===0)return e;let i=e;if(typeof e=="symbol"?i=Symbol.prototype.toString.call(e):typeof e!="string"&&(i=String(e)),n==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let u="";for(let l=0;l<i.length;l+=_e){let o=i.length>=_e?i.slice(l,l+_e):i,p=[];for(let f=0;f<o.length;++f){let c=o.charCodeAt(f);if(c===45||c===46||c===95||c===126||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===On&&(c===40||c===41)){p[p.length]=o.charAt(f);continue}if(c<128){p[p.length]=D[c];continue}if(c<2048){p[p.length]=D[192|c>>6]+D[128|c&63];continue}if(c<55296||c>=57344){p[p.length]=D[224|c>>12]+D[128|c>>6&63]+D[128|c&63];continue}f+=1,c=65536+((c&1023)<<10|o.charCodeAt(f)&1023),p[p.length]=D[240|c>>18]+D[128|c>>12&63]+D[128|c>>6&63]+D[128|c&63]}u+=p.join("")}return u};function Nn(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function $e(e,r){if(Rn(e)){let n=[];for(let t=0;t<e.length;t+=1)n.push(r(e[t]));return n}return r(e)}var Ir=Array.isArray;var Ln=Object.prototype.hasOwnProperty,Ye={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,r){return String(e)+"["+r+"]"},repeat(e){return String(e)}},j=Array.isArray,qn=Array.prototype.push,Ze=function(e,r){qn.apply(e,j(r)?r:[r])},Fn=Date.prototype.toISOString,k={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Cn,encodeValuesOnly:!1,format:we,formatter:Se[we],indices:!1,serializeDate(e){return Fn.call(e)},skipNulls:!1,strictNullHandling:!1};function Mn(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}var Ee={};function Qe(e,r,n,t,s,i,u,l,o,p,f,c,b,m,g,E,q,B){let y=e,ee=B,ne=0,Ue=!1;for(;(ee=ee.get(Ee))!==void 0&&!Ue;){let _=ee.get(e);if(ne+=1,typeof _!="undefined"){if(_===ne)throw new RangeError("Cyclic object value");Ue=!0}typeof ee.get(Ee)=="undefined"&&(ne=0)}if(typeof p=="function"?y=p(r,y):y instanceof Date?y=b==null?void 0:b(y):n==="comma"&&j(y)&&(y=$e(y,function(_){return _ instanceof Date?b==null?void 0:b(_):_})),y===null){if(i)return o&&!E?o(r,k.encoder,q,"key",m):r;y=""}if(Mn(y)||Nn(y)){if(o){let _=E?r:o(r,k.encoder,q,"key",m);return[(g==null?void 0:g(_))+"="+(g==null?void 0:g(o(y,k.encoder,q,"value",m)))]}return[(g==null?void 0:g(r))+"="+(g==null?void 0:g(String(y)))]}let me=[];if(typeof y=="undefined")return me;let J;if(n==="comma"&&j(y))E&&o&&(y=$e(y,o)),J=[{value:y.length>0?y.join(",")||null:void 0}];else if(j(p))J=p;else{let _=Object.keys(y);J=f?_.sort(f):_}let ze=l?String(r).replace(/\./g,"%2E"):String(r),re=t&&j(y)&&y.length===1?ze+"[]":ze;if(s&&j(y)&&y.length===0)return re+"[]";for(let _=0;_<J.length;++_){let V=J[_],Ke=typeof V=="object"&&typeof V.value!="undefined"?V.value:y[V];if(u&&Ke===null)continue;let de=c&&l?V.replace(/\./g,"%2E"):V,_n=j(y)?typeof n=="function"?n(re,de):re:re+(c?"."+de:"["+de+"]");B.set(e,ne);let Je=new WeakMap;Je.set(Ee,B),Ze(me,Qe(Ke,_n,n,t,s,i,u,l,n==="comma"&&E&&j(y)?null:o,p,f,c,b,m,g,E,q,Je))}return me}function Bn(e=k){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||k.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=we;if(typeof e.format!="undefined"){if(!Ln.call(Se,e.format))throw new TypeError("Unknown format option provided.");n=e.format}let t=Se[n],s=k.filter;(typeof e.filter=="function"||j(e.filter))&&(s=e.filter);let i;if(e.arrayFormat&&e.arrayFormat in Ye?i=e.arrayFormat:"indices"in e?i=e.indices?"indices":"repeat":i=k.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let u=typeof e.allowDots=="undefined"?e.encodeDotInKeys?!0:k.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:k.addQueryPrefix,allowDots:u,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:k.allowEmptyArrays,arrayFormat:i,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:k.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter=="undefined"?k.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:k.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:k.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:k.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:k.encodeValuesOnly,filter:s,format:n,formatter:t,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:k.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:k.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:k.strictNullHandling}}function en(e,r={}){let n=e,t=Bn(r),s,i;typeof t.filter=="function"?(i=t.filter,n=i("",n)):j(t.filter)&&(i=t.filter,s=i);let u=[];if(typeof n!="object"||n===null)return"";let l=Ye[t.arrayFormat],o=l==="comma"&&t.commaRoundTrip;s||(s=Object.keys(n)),t.sort&&s.sort(t.sort);let p=new WeakMap;for(let b=0;b<s.length;++b){let m=s[b];t.skipNulls&&n[m]===null||Ze(u,Qe(n[m],m,l,o,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,p))}let f=u.join(t.delimiter),c=t.addQueryPrefix===!0?"?":"";return t.charsetSentinel&&(t.charset==="iso-8859-1"?c+="utf8=%26%2310003%3B&":c+="utf8=%E2%9C%93&"),f.length>0?c+f:""}var nn="2.0.1";var ue={sandbox:"https://api.staging.inploi.com",production:"https://api.inploi.com",_internal_local:"http://api.test"},rn={sandbox:"https://talent-bank.staging.inploi.com",production:"https://talent-bank.inploi.com",_internal_local:"http://localhost:8787"},tn=nn;var U="isdk_session",oe=`${U}-candidate_id`;function Ie(e,r,n){let t=e["~standard"].validate(r);if(t instanceof Promise)throw new TypeError("Async schema");if(t.issues)throw new N(t.issues,n);return t.value}function Gn(e,r,n){try{return{success:!0,output:Ie(e,r,n)}}catch(t){if(t instanceof N)return{success:!1,issues:t.issues,source:t.source};throw t}}var W=class{constructor(r){if(this.baseUrl=ue[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,this._environment=r.environment}get environment(){return this._environment}getFetchParams(r,n){var o;let t=(o=n.validateIn)!=null?o:!0,{searchParams:s,body:i}=t?sn(r,n):n,u=new URL(this.baseUrl),l=r.pathname;if("params"in n&&n.params)for(let[p,f]of Object.entries(n.params))l=l.replace(`:${p}`,String(f));return u.pathname=l,r.schema.searchParams&&(u.search=en(s)),[u.toString(),{method:r.method,body:i?JSON.stringify(i):void 0,headers:this.headers,signal:n.signal}]}parseResponse(r,n){return A(this,null,function*(){var u;let t=yield n.response.json().catch(l=>{throw this.logger.error(l),new G(n.response)});if(!((u=n.validateOut)!=null?u:!0))return t;let i=Gn(r.schema.response,t,"response");if(!i.success)throw xe(t,n.response.status),new N(i.issues,i.source);return i.output})}request(r,n){return A(this,null,function*(){try{let t=this.getFetchParams(r,n),s=yield fetch(...t);return this.parseResponse(r,{response:s,validateOut:n.validateOut})}catch(t){throw t instanceof N?this.logger.error(t.message,t.issues):this.logger.error(t),t}})}};function le(){return{"~standard":{vendor:"inploi",version:1,validate:e=>({value:e})}}}function sn(e,r){let n={searchParams:void 0,body:void 0,validateIn:!1};return e.schema.searchParams&&(n.searchParams=Ie(e.schema.searchParams,"searchParams"in r?r.searchParams:{})),e.schema.body&&(n.body=Ie(e.schema.body,"body"in r?r.body:{})),n}var C;function on(e){var r,n,t;return{lang:(r=e==null?void 0:e.lang)!=null?r:C==null?void 0:C.lang,message:e==null?void 0:e.message,abortEarly:(n=e==null?void 0:e.abortEarly)!=null?n:C==null?void 0:C.abortEarly,abortPipeEarly:(t=e==null?void 0:e.abortPipeEarly)!=null?t:C==null?void 0:C.abortPipeEarly}}var Ae;function Un(e){return Ae==null?void 0:Ae.get(e)}var Te;function zn(e){return Te==null?void 0:Te.get(e)}var Pe;function Kn(e,r){var n;return(n=Pe==null?void 0:Pe.get(e))==null?void 0:n.get(r)}function $(e){var n,t,s;let r=typeof e;return r==="string"?`"${e}"`:r==="number"||r==="bigint"||r==="boolean"?`${e}`:r==="object"||r==="function"?(s=e&&((t=(n=Object.getPrototypeOf(e))==null?void 0:n.constructor)==null?void 0:t.name))!=null?s:"null":r}function w(e,r,n,t,s){var c,b,m,g,E,q,B,y;let i=s&&"input"in s?s.input:n.value,u=(b=(c=s==null?void 0:s.expected)!=null?c:e.expects)!=null?b:null,l=(m=s==null?void 0:s.received)!=null?m:$(i),o={kind:e.kind,type:e.type,input:i,expected:u,received:l,message:`Invalid ${r}: ${u?`Expected ${u} but r`:"R"}eceived ${l}`,requirement:e.requirement,path:s==null?void 0:s.path,issues:s==null?void 0:s.issues,lang:t.lang,abortEarly:t.abortEarly,abortPipeEarly:t.abortPipeEarly},p=e.kind==="schema",f=(y=(B=(q=(E=(g=s==null?void 0:s.message)!=null?g:e.message)!=null?E:Kn(e.reference,o.lang))!=null?q:p?zn(o.lang):null)!=null?B:t.message)!=null?y:Un(o.lang);f!==void 0&&(o.message=typeof f=="function"?f(o):f),p&&(n.typed=!1),n.issues?n.issues.push(o):n.issues=[o]}function S(e){return{version:1,vendor:"valibot",validate(r){return e["~run"]({value:r},on())}}}function Jn(e,r){return Object.hasOwn(e,r)&&r!=="__proto__"&&r!=="prototype"&&r!=="constructor"}function ln(e,r){var t;let n=[...new Set(e)];return n.length>1?`(${n.join(` ${r} `)})`:(t=n[0])!=null?t:"never"}var Mr=new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$","u");function De(e){return{kind:"validation",type:"integer",reference:De,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(r,n){return r.typed&&!this.requirement(r.value)&&w(this,"integer",r,n),r}}}function je(e,r){return{kind:"validation",type:"min_length",reference:je,async:!1,expects:`>=${e}`,requirement:e,message:r,"~run"(n,t){return n.typed&&n.value.length<this.requirement&&w(this,"length",n,t,{received:`${n.value.length}`}),n}}}function Oe(e,r){return{kind:"validation",type:"min_value",reference:Oe,async:!1,expects:`>=${e instanceof Date?e.toJSON():$(e)}`,requirement:e,message:r,"~run"(n,t){return n.typed&&!(n.value>=this.requirement)&&w(this,"value",n,t,{received:n.value instanceof Date?n.value.toJSON():$(n.value)}),n}}}function Xn(e,r,n){return typeof e.fallback=="function"?e.fallback(r,n):e.fallback}function ae(e,r,n){return typeof e.default=="function"?e.default(r,n):e.default}function Y(e,r){return{kind:"schema",type:"array",reference:Y,expects:"Array",async:!1,item:e,message:r,get"~standard"(){return S(this)},"~run"(n,t){var i;let s=n.value;if(Array.isArray(s)){n.typed=!0,n.value=[];for(let u=0;u<s.length;u++){let l=s[u],o=this.item["~run"]({value:l},t);if(o.issues){let p={type:"array",origin:"value",input:s,key:u,value:l};for(let f of o.issues)f.path?f.path.unshift(p):f.path=[p],(i=n.issues)==null||i.push(f);if(n.issues||(n.issues=o.issues),t.abortEarly){n.typed=!1;break}}o.typed||(n.typed=!1),n.value.push(o.value)}}else w(this,"type",n,t);return n}}}function Z(e){return{kind:"schema",type:"boolean",reference:Z,expects:"boolean",async:!1,message:e,get"~standard"(){return S(this)},"~run"(r,n){return typeof r.value=="boolean"?r.typed=!0:w(this,"type",r,n),r}}}function z(e,r){return{kind:"schema",type:"literal",reference:z,expects:$(e),async:!1,literal:e,message:r,get"~standard"(){return S(this)},"~run"(n,t){return n.value===this.literal?n.typed=!0:w(this,"type",n,t),n}}}function h(e,r){return{kind:"schema",type:"nullable",reference:h,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:r,get"~standard"(){return S(this)},"~run"(n,t){return n.value===null&&(this.default!==void 0&&(n.value=ae(this,n,t)),n.value===null)?(n.typed=!0,n):this.wrapped["~run"](n,t)}}}function I(e,r){return{kind:"schema",type:"nullish",reference:I,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:r,get"~standard"(){return S(this)},"~run"(n,t){return(n.value===null||n.value===void 0)&&(this.default!==void 0&&(n.value=ae(this,n,t)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,t)}}}function v(e){return{kind:"schema",type:"number",reference:v,expects:"number",async:!1,message:e,get"~standard"(){return S(this)},"~run"(r,n){return typeof r.value=="number"&&!isNaN(r.value)?r.typed=!0:w(this,"type",r,n),r}}}function d(e,r){return{kind:"schema",type:"object",reference:d,expects:"Object",async:!1,entries:e,message:r,get"~standard"(){return S(this)},"~run"(n,t){var i;let s=n.value;if(s&&typeof s=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in s||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let o=u in s?s[u]:ae(l),p=l["~run"]({value:o},t);if(p.issues){let f={type:"object",origin:"value",input:s,key:u,value:o};for(let c of p.issues)c.path?c.path.unshift(f):c.path=[f],(i=n.issues)==null||i.push(c);if(n.issues||(n.issues=p.issues),t.abortEarly){n.typed=!1;break}}p.typed||(n.typed=!1),n.value[u]=p.value}else if(l.fallback!==void 0)n.value[u]=Xn(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(w(this,"key",n,t,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:s,key:u,value:s[u]}]}),t.abortEarly))break}}else w(this,"type",n,t);return n}}}function x(e,r){return{kind:"schema",type:"optional",reference:x,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:r,get"~standard"(){return S(this)},"~run"(n,t){return n.value===void 0&&(this.default!==void 0&&(n.value=ae(this,n,t)),n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,t)}}}function T(e,r){return{kind:"schema",type:"picklist",reference:T,expects:ln(e.map($),"|"),async:!1,options:e,message:r,get"~standard"(){return S(this)},"~run"(n,t){return this.options.includes(n.value)?n.typed=!0:w(this,"type",n,t),n}}}function M(e,r,n){return{kind:"schema",type:"record",reference:M,expects:"Object",async:!1,key:e,value:r,message:n,get"~standard"(){return S(this)},"~run"(t,s){var u,l;let i=t.value;if(i&&typeof i=="object"){t.typed=!0,t.value={};for(let o in i)if(Jn(i,o)){let p=i[o],f=this.key["~run"]({value:o},s);if(f.issues){let b={type:"object",origin:"key",input:i,key:o,value:p};for(let m of f.issues)m.path=[b],(u=t.issues)==null||u.push(m);if(t.issues||(t.issues=f.issues),s.abortEarly){t.typed=!1;break}}let c=this.value["~run"]({value:p},s);if(c.issues){let b={type:"object",origin:"value",input:i,key:o,value:p};for(let m of c.issues)m.path?m.path.unshift(b):m.path=[b],(l=t.issues)==null||l.push(m);if(t.issues||(t.issues=c.issues),s.abortEarly){t.typed=!1;break}}(!f.typed||!c.typed)&&(t.typed=!1),f.typed&&(t.value[f.value]=c.value)}}else w(this,"type",t,s);return t}}}function a(e){return{kind:"schema",type:"string",reference:a,expects:"string",async:!1,message:e,get"~standard"(){return S(this)},"~run"(r,n){return typeof r.value=="string"?r.typed=!0:w(this,"type",r,n),r}}}function un(e){let r;if(e)for(let n of e)r?r.push(...n.issues):r=n.issues;return r}function Re(e,r){return{kind:"schema",type:"union",reference:Re,expects:ln(e.map(n=>n.expects),"|"),async:!1,options:e,message:r,get"~standard"(){return S(this)},"~run"(n,t){let s,i,u;for(let l of this.options){let o=l["~run"]({value:n.value},t);if(o.typed)if(o.issues)i?i.push(o):i=[o];else{s=o;break}else u?u.push(o):u=[o]}if(s)return s;if(i){if(i.length===1)return i[0];w(this,"type",n,t,{issues:un(i)}),n.typed=!0}else{if((u==null?void 0:u.length)===1)return u[0];w(this,"type",n,t,{issues:un(u)})}return n}}}function Ce(){return{kind:"schema",type:"unknown",reference:Ce,expects:"unknown",async:!1,get"~standard"(){return S(this)},"~run"(e){return e.typed=!0,e}}}function Ne(...e){return R(P({},e[0]),{pipe:e,get"~standard"(){return S(this)},"~run"(r,n){for(let t of e)if(t.kind!=="metadata"){if(r.issues&&(t.kind==="schema"||t.kind==="transformation")){r.typed=!1;break}(!r.issues||!n.abortEarly&&!n.abortPipeEarly)&&(r=t["~run"](r,n))}return r}})}function ce(e,r,n){let t=e["~run"]({value:r},on(n));return{typed:t.typed,success:!t.issues,output:t.value,issues:t.issues}}var Hn=["agent","sdk","form","integration","migration"],Wn=["PENDING","SUBMITTED","SCREENING","SHORTLISTED","INTERVIEW","OFFERED","HIRED","REJECTED","WITHDRAWN"],$n=["screening","cv_match","interview","overall"],Yn=["PENDING","SCHEDULED","IN_PROGRESS","COMPLETED","CANCELLED"],Zn=["job","company"],Qn=["created_at","updated_at"],er=["asc","desc"],pe=T(Hn),fe=T(Wn),ye=T($n),an=T(Yn),Vr=T(Zn),cn=T(Qn),pn=T(er);var nr=d({total:v(),page:v(),perPage:v(),lastPage:v()});function he(e){return d({data:Y(e),pagination:nr})}var Q=d({id:a(),email:h(a()),firstName:h(a()),lastName:h(a()),phone:h(a()),source:h(pe),identifiedAt:h(a()),createdAt:a(),updatedAt:a()});var K=Ne(a(),je(1)),fn=Ne(v(),De(),Oe(1)),L=M(a(),Ce());var yn=d({id:a(),applicationId:a(),status:an,scheduledAt:h(a()),completedAt:h(a()),meta:h(L),createdAt:a(),updatedAt:a()});var Le=d({score:v(),reason:a(),confidence:v()}),hn=d({id:a(),candidateId:a(),jobId:v(),status:fe,sessionId:h(v()),externalApplicationId:h(a()),meta:h(L),context:h(L),scoredAt:h(a()),shortlistedAt:h(a()),createdAt:a(),updatedAt:a()}),rr=d({id:a(),applicationId:a(),scoreType:ye,score:h(v()),reason:h(a()),categories:h(M(a(),Le)),scoredBy:h(a()),createdAt:a()}),mn=d(R(P({},hn.entries),{candidate:h(Q),score:h(rr),interview:h(yn)})),tr=d(R(P({},Q.entries),{applications:Y(hn)}));var dn=d({anonymousId:K,email:K,firstName:I(a()),lastName:I(a()),phone:I(a()),source:I(pe)}),vn=d({candidateId:a(),isNew:Z()});var at=d({status:x(fe),job_id:x(a()),candidate_id:x(a()),created_from:x(a()),created_to:x(a()),updated_from:x(a()),updated_to:x(a()),from:x(a()),to:x(a()),q:x(a()),scored:x(T(["true","false"])),shortlisted:x(T(["true","false"])),sort:x(cn),order:x(pn),page:x(a()),per_page:x(a())}),ct=d({candidateId:K,jobId:fn,meta:I(L),sessionId:I(v()),externalApplicationId:I(a()),context:I(L)}),gn=d({id:a(),status:a(),createdAt:a()}),pt=Re([d({ok:z(!0),duplicate:z(!1),applicationId:a(),candidateId:a()}),d({ok:z(!0),duplicate:z(!0),existingApplication:gn})]),bn=d({isDuplicate:Z(),existingApplication:x(gn)}),ft=d({applicationId:K,scoreType:ye,score:v(),reason:I(a()),categories:I(M(a(),Le)),scoredBy:I(a())}),yt=d({scoreId:a()}),ht=he(mn);var bt=he(Q);var xt=d({avg_score:h(v()),p90_score:h(v()),p85_score:h(v()),p80_score:h(v()),total_scores:v()});var qe=({environment:e,publishableKey:r,logger:n})=>{let t=rn[e];return{checkDuplicate(i){return A(this,null,function*(){try{let u=new URLSearchParams({email:i.email,scope:i.scope});i.scope==="job"&&i.jobId!=null&&u.set("job_id",String(i.jobId));let l=yield fetch(`${t}/applications/check-duplicate?${u}`,{method:"GET",headers:{Accept:"application/json","x-publishable-key":r}});if(!l.ok)return n.error(`[TalentBankClient] checkDuplicate failed with status ${l.status}`),{isDuplicate:!1};let o=ce(bn,yield l.json());return o.success?o.output:(n.error("[TalentBankClient] checkDuplicate returned an invalid response"),{isDuplicate:!1})}catch(u){return n.error("[TalentBankClient] checkDuplicate failed:",u),{isDuplicate:!1}}})},identify(i){return A(this,null,function*(){var u;try{if(!i.anonymousId)return n.error("[TalentBankClient] identify skipped because anonymousId is missing"),null;let l={email:i.email,firstName:i.firstName,lastName:i.lastName,phone:i.phone,anonymousId:i.anonymousId,source:(u=i.source)!=null?u:"sdk"},o=ce(dn,l);if(!o.success)return n.error("[TalentBankClient] identify received invalid input"),null;let p=yield fetch(`${t}/identify`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-publishable-key":r},body:JSON.stringify(o.output)});if(!p.ok)return n.error(`[TalentBankClient] identify failed with status ${p.status}`),null;let f=ce(vn,yield p.json());return f.success?f.output:(n.error("[TalentBankClient] identify returned an invalid response"),null)}catch(l){return n.error("[TalentBankClient] identify failed:",l),null}})}}};var Fe=()=>typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+e/4).toString(16));function Me(e){if(typeof document!="undefined"){if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",e,{once:!0});return}Promise.resolve().then(e)}}var Ve=e=>{let r=new Date;return r.setTime(r.getTime()+7*24*60*60*1e3),`${U}=${e};expires=${r.toUTCString()};path=/`},sr=(e,r)=>{let n=e.get("session_id");if(r||n)return n;let t=sessionStorage.getItem(`${U}-session_id`);return typeof t=="string"?t:null},ur=()=>{if(typeof window=="undefined")return null;try{let e=window.localStorage.getItem(oe);return typeof e=="string"&&e!==""?e:null}catch(e){return null}},or=e=>{if(typeof window!="undefined")try{e?window.localStorage.setItem(oe,e):window.localStorage.removeItem(oe)}catch(r){}},lr=new RegExp(`${U}=([^;]+)`),Ge=e=>{let r=e?e.url:location.href,{searchParams:n}=new URL(r),t=n.get("anonymous_id"),s=sr(n,typeof window=="undefined");if(t)return{anonymous_id:t,session_id:s};let i=e?e.headers.get("cookie"):document.cookie;if(i){let u=lr.exec(i),l=u==null?void 0:u[1];return{anonymous_id:l!=null?l:null,session_id:s}}return{anonymous_id:t,session_id:s}},kn=()=>{if(typeof window=="undefined")throw new Error("getOrCreateAnonymousId() can only be called in browser environment");let e=Ge().anonymous_id;if(e)return e;let r=Fe();return document.cookie=Ve(r),r},ar=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},cr=e=>e==="about:client"?"":e,pr={pathname:"/log",method:"POST",schema:{response:le(),body:le()}},xn=({rpcClient:e,logger:r,onEvent:n,talentBank:t})=>({log:i=>A(void 0,null,function*(){var l;ve(i.request||typeof window!="undefined","Cannot log on the server without a request. Please pass a request to `log`.");let u="request"in i&&i.request?{href:i.request.url,referrer:cr(i.request.referrer),title:""}:{href:location.href,referrer:document.referrer,title:document.title};try{let o={library:{name:"inploi-sdk",version:tn},page:u},p=Ge(i.request);i.event==="IDENTIFY"&&!p.anonymous_id&&!i.request&&typeof window!="undefined"&&(p=R(P({},p),{anonymous_id:kn()}));let f=ur();if(i.event==="IDENTIFY"&&t&&p.anonymous_id){let g=i.properties,E=yield t.identify({email:(l=g.email)!=null?l:g.identifier,firstName:g.first_name,lastName:g.last_name,phone:g.phone_number,anonymousId:p.anonymous_id,source:"sdk"});E!=null&&E.candidateId&&(f=E.candidateId,or(E.candidateId))}let c={anonymous_id:p.anonymous_id,session_id:p.session_id,candidate_id:f,event:i.event,sent_at:new Date().toISOString(),context:o,properties:i.properties,custom_properties:i.customProperties},b=yield e.request(pr,{body:c}),m=ar(b);return m!=null&&m.anonymous_id&&(c.anonymous_id=m.anonymous_id),m!=null&&m.session_id&&(c.session_id=m.session_id),typeof window!="undefined"&&c.anonymous_id&&(c.session_id&&sessionStorage.setItem(`${U}-session_id`,c.session_id.toString()),document.cookie=Ve(c.anonymous_id)),n==null||n(c),{success:!0,data:c}}catch(o){return r.error("Failed to send log to API. Inspect error response of `log` for more information."),{success:!1,error:o}}}),getHeaders:i=>{let u=new Headers;return i!=null&&i.anonymous_id&&u.append("Set-Cookie",Ve(i.anonymous_id)),u},getSessionInfo:Ge});function Be({publishableKey:e,env:r,logger:n=be,onEvent:t}){let s=We({baseUrl:ue[r],publishableKey:e}),i=n===!1?ke:n,u=new W({environment:r,apiKey:{type:"publishable",key:e},logger:i}),l=qe({environment:r,publishableKey:e,logger:i}),o=xn({rpcClient:u,logger:i,onEvent:t,talentBank:l});return{register:f=>f({logger:i,apiClient:s,analytics:o,rpcClient:u,publishableKey:e,env:r}),analytics:o,apiClient:s}}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=Be;window.inploi.ready=Me;})();
|
|
3
|
+
"use strict";(()=>{var En=Object.defineProperty,wn=Object.defineProperties;var Sn=Object.getOwnPropertyDescriptors;var Xe=Object.getOwnPropertySymbols;var In=Object.prototype.hasOwnProperty,An=Object.prototype.propertyIsEnumerable;var He=(e,r,n)=>r in e?En(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n,P=(e,r)=>{for(var n in r||(r={}))In.call(r,n)&&He(e,n,r[n]);if(Xe)for(var n of Xe(r))An.call(r,n)&&He(e,n,r[n]);return e},R=(e,r)=>wn(e,Sn(r));var A=(e,r,n)=>new Promise((t,s)=>{var i=o=>{try{l(n.next(o))}catch(p){s(p)}},u=o=>{try{l(n.throw(o))}catch(p){s(p)}},l=o=>o.done?t(o.value):Promise.resolve(o.value).then(i,u);l((n=n.apply(e,r)).next())});function ve(e,r){if(!e)throw new Error(r)}function ge(e,r){return r in e}var br=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});var te="%c[inploi SDK]",ie="color: #65BC67; font-weight: bold;",be={warn:(...e)=>console.warn(te,ie,...e),error:(...e)=>console.error(te,ie,...e),info:(...e)=>console.info(te,ie,...e),log:(...e)=>console.log(te,ie,...e)},ke={info:()=>{},error:()=>{},log:()=>{},warn:()=>{}};var Tn="Unauthenticated",Pn="This action is unauthorized.",F=class extends Error{constructor(n,t){super(n);this.status=t,this.name="ErrorWithStatus"}},X=class extends F{constructor(r){super(r!=null?r:"Not found"),this.name="NotFoundError",this.status=404}},H=class extends F{constructor(r,n){super(r!=null?r:"You are not authorised to perform this action."),this.name="UnauthorisedError",this.status=n!=null?n:401}},N=class extends F{constructor(n,t){let s=t?` in ${t}`:"";super(`Schema validation failed${s}`);this.issues=n;this.source=t;this.name="SchemaValidationError",this.status=400}},se=class extends F{constructor(r,n){super(r),this.name="ApiError",this.status=n!=null?n:500}},G=class extends F{constructor(n){super("Error parsing response into JSON.");this.response=n;this.name="ParsingError",this.status=500}};var Dn=["message","error","errors","exception","exceptions"];function jn(e){console.log("json",e);let r=[];if(typeof e=="object"&&e!==null){for(let n of Dn)if(ge(e,n)){console.log("hasProp",n,e[n]);let t=e[n];typeof t=="string"&&r.push(t),Array.isArray(t)&&t.every(s=>typeof s=="string")&&r.push(...t)}}return r.length===0&&r.push("Unknown error"),r.join(", ")}function xe(e,r){if(r>=300&&r<=500){let n=jn(e);throw r===404?new X(n):n===Tn?new H("You are not authenticated.",r):n===Pn?new H(n,r):new se(n,r)}}var We=e=>{let r={Accept:"application/json","Content-Type":"application/json","x-publishable-key":e.publishableKey};return{fetch:(s,...i)=>A(void 0,[s,...i],function*(n,t={}){let u=R(P({},t),{headers:P(P({},t.headers),r)}),l=yield fetch(`${e.baseUrl}${n}`,u);if(l.status===404)throw new X;let o=yield l.json().catch(()=>A(void 0,null,function*(){throw new G(l)}));return xe(o,l.status),o})}};var we="RFC3986",Se={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},On="RFC1738";var Rn=Array.isArray,D=(()=>{let e=[];for(let r=0;r<256;++r)e.push("%"+((r<16?"0":"")+r.toString(16)).toUpperCase());return e})();var _e=1024,Cn=(e,r,n,t,s)=>{if(e.length===0)return e;let i=e;if(typeof e=="symbol"?i=Symbol.prototype.toString.call(e):typeof e!="string"&&(i=String(e)),n==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let u="";for(let l=0;l<i.length;l+=_e){let o=i.length>=_e?i.slice(l,l+_e):i,p=[];for(let f=0;f<o.length;++f){let c=o.charCodeAt(f);if(c===45||c===46||c===95||c===126||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===On&&(c===40||c===41)){p[p.length]=o.charAt(f);continue}if(c<128){p[p.length]=D[c];continue}if(c<2048){p[p.length]=D[192|c>>6]+D[128|c&63];continue}if(c<55296||c>=57344){p[p.length]=D[224|c>>12]+D[128|c>>6&63]+D[128|c&63];continue}f+=1,c=65536+((c&1023)<<10|o.charCodeAt(f)&1023),p[p.length]=D[240|c>>18]+D[128|c>>12&63]+D[128|c>>6&63]+D[128|c&63]}u+=p.join("")}return u};function Nn(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function $e(e,r){if(Rn(e)){let n=[];for(let t=0;t<e.length;t+=1)n.push(r(e[t]));return n}return r(e)}var Ir=Array.isArray;var Ln=Object.prototype.hasOwnProperty,Ye={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,r){return String(e)+"["+r+"]"},repeat(e){return String(e)}},j=Array.isArray,qn=Array.prototype.push,Ze=function(e,r){qn.apply(e,j(r)?r:[r])},Fn=Date.prototype.toISOString,k={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Cn,encodeValuesOnly:!1,format:we,formatter:Se[we],indices:!1,serializeDate(e){return Fn.call(e)},skipNulls:!1,strictNullHandling:!1};function Mn(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}var Ee={};function Qe(e,r,n,t,s,i,u,l,o,p,f,c,b,m,g,E,q,B){let y=e,ee=B,ne=0,Ue=!1;for(;(ee=ee.get(Ee))!==void 0&&!Ue;){let _=ee.get(e);if(ne+=1,typeof _!="undefined"){if(_===ne)throw new RangeError("Cyclic object value");Ue=!0}typeof ee.get(Ee)=="undefined"&&(ne=0)}if(typeof p=="function"?y=p(r,y):y instanceof Date?y=b==null?void 0:b(y):n==="comma"&&j(y)&&(y=$e(y,function(_){return _ instanceof Date?b==null?void 0:b(_):_})),y===null){if(i)return o&&!E?o(r,k.encoder,q,"key",m):r;y=""}if(Mn(y)||Nn(y)){if(o){let _=E?r:o(r,k.encoder,q,"key",m);return[(g==null?void 0:g(_))+"="+(g==null?void 0:g(o(y,k.encoder,q,"value",m)))]}return[(g==null?void 0:g(r))+"="+(g==null?void 0:g(String(y)))]}let me=[];if(typeof y=="undefined")return me;let J;if(n==="comma"&&j(y))E&&o&&(y=$e(y,o)),J=[{value:y.length>0?y.join(",")||null:void 0}];else if(j(p))J=p;else{let _=Object.keys(y);J=f?_.sort(f):_}let ze=l?String(r).replace(/\./g,"%2E"):String(r),re=t&&j(y)&&y.length===1?ze+"[]":ze;if(s&&j(y)&&y.length===0)return re+"[]";for(let _=0;_<J.length;++_){let V=J[_],Ke=typeof V=="object"&&typeof V.value!="undefined"?V.value:y[V];if(u&&Ke===null)continue;let de=c&&l?V.replace(/\./g,"%2E"):V,_n=j(y)?typeof n=="function"?n(re,de):re:re+(c?"."+de:"["+de+"]");B.set(e,ne);let Je=new WeakMap;Je.set(Ee,B),Ze(me,Qe(Ke,_n,n,t,s,i,u,l,n==="comma"&&E&&j(y)?null:o,p,f,c,b,m,g,E,q,Je))}return me}function Bn(e=k){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||k.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=we;if(typeof e.format!="undefined"){if(!Ln.call(Se,e.format))throw new TypeError("Unknown format option provided.");n=e.format}let t=Se[n],s=k.filter;(typeof e.filter=="function"||j(e.filter))&&(s=e.filter);let i;if(e.arrayFormat&&e.arrayFormat in Ye?i=e.arrayFormat:"indices"in e?i=e.indices?"indices":"repeat":i=k.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let u=typeof e.allowDots=="undefined"?e.encodeDotInKeys?!0:k.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:k.addQueryPrefix,allowDots:u,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:k.allowEmptyArrays,arrayFormat:i,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:k.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter=="undefined"?k.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:k.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:k.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:k.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:k.encodeValuesOnly,filter:s,format:n,formatter:t,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:k.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:k.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:k.strictNullHandling}}function en(e,r={}){let n=e,t=Bn(r),s,i;typeof t.filter=="function"?(i=t.filter,n=i("",n)):j(t.filter)&&(i=t.filter,s=i);let u=[];if(typeof n!="object"||n===null)return"";let l=Ye[t.arrayFormat],o=l==="comma"&&t.commaRoundTrip;s||(s=Object.keys(n)),t.sort&&s.sort(t.sort);let p=new WeakMap;for(let b=0;b<s.length;++b){let m=s[b];t.skipNulls&&n[m]===null||Ze(u,Qe(n[m],m,l,o,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,p))}let f=u.join(t.delimiter),c=t.addQueryPrefix===!0?"?":"";return t.charsetSentinel&&(t.charset==="iso-8859-1"?c+="utf8=%26%2310003%3B&":c+="utf8=%E2%9C%93&"),f.length>0?c+f:""}var nn="2.0.2";var ue={sandbox:"https://api.staging.inploi.com",production:"https://api.inploi.com",_internal_local:"http://api.test"},rn={sandbox:"https://talent-bank.staging.inploi.com",production:"https://talent-bank.inploi.com",_internal_local:"http://localhost:8787"},tn=nn;var U="isdk_session",oe=`${U}-candidate_id`;function Ie(e,r,n){let t=e["~standard"].validate(r);if(t instanceof Promise)throw new TypeError("Async schema");if(t.issues)throw new N(t.issues,n);return t.value}function Gn(e,r,n){try{return{success:!0,output:Ie(e,r,n)}}catch(t){if(t instanceof N)return{success:!1,issues:t.issues,source:t.source};throw t}}var W=class{constructor(r){if(this.baseUrl=ue[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,this._environment=r.environment}get environment(){return this._environment}getFetchParams(r,n){var o;let t=(o=n.validateIn)!=null?o:!0,{searchParams:s,body:i}=t?sn(r,n):n,u=new URL(this.baseUrl),l=r.pathname;if("params"in n&&n.params)for(let[p,f]of Object.entries(n.params))l=l.replace(`:${p}`,String(f));return u.pathname=l,r.schema.searchParams&&(u.search=en(s)),[u.toString(),{method:r.method,body:i?JSON.stringify(i):void 0,headers:this.headers,signal:n.signal}]}parseResponse(r,n){return A(this,null,function*(){var u;let t=yield n.response.json().catch(l=>{throw this.logger.error(l),new G(n.response)});if(!((u=n.validateOut)!=null?u:!0))return t;let i=Gn(r.schema.response,t,"response");if(!i.success)throw xe(t,n.response.status),new N(i.issues,i.source);return i.output})}request(r,n){return A(this,null,function*(){try{let t=this.getFetchParams(r,n),s=yield fetch(...t);return this.parseResponse(r,{response:s,validateOut:n.validateOut})}catch(t){throw t instanceof N?this.logger.error(t.message,t.issues):this.logger.error(t),t}})}};function le(){return{"~standard":{vendor:"inploi",version:1,validate:e=>({value:e})}}}function sn(e,r){let n={searchParams:void 0,body:void 0,validateIn:!1};return e.schema.searchParams&&(n.searchParams=Ie(e.schema.searchParams,"searchParams"in r?r.searchParams:{})),e.schema.body&&(n.body=Ie(e.schema.body,"body"in r?r.body:{})),n}var C;function on(e){var r,n,t;return{lang:(r=e==null?void 0:e.lang)!=null?r:C==null?void 0:C.lang,message:e==null?void 0:e.message,abortEarly:(n=e==null?void 0:e.abortEarly)!=null?n:C==null?void 0:C.abortEarly,abortPipeEarly:(t=e==null?void 0:e.abortPipeEarly)!=null?t:C==null?void 0:C.abortPipeEarly}}var Ae;function Un(e){return Ae==null?void 0:Ae.get(e)}var Te;function zn(e){return Te==null?void 0:Te.get(e)}var Pe;function Kn(e,r){var n;return(n=Pe==null?void 0:Pe.get(e))==null?void 0:n.get(r)}function $(e){var n,t,s;let r=typeof e;return r==="string"?`"${e}"`:r==="number"||r==="bigint"||r==="boolean"?`${e}`:r==="object"||r==="function"?(s=e&&((t=(n=Object.getPrototypeOf(e))==null?void 0:n.constructor)==null?void 0:t.name))!=null?s:"null":r}function w(e,r,n,t,s){var c,b,m,g,E,q,B,y;let i=s&&"input"in s?s.input:n.value,u=(b=(c=s==null?void 0:s.expected)!=null?c:e.expects)!=null?b:null,l=(m=s==null?void 0:s.received)!=null?m:$(i),o={kind:e.kind,type:e.type,input:i,expected:u,received:l,message:`Invalid ${r}: ${u?`Expected ${u} but r`:"R"}eceived ${l}`,requirement:e.requirement,path:s==null?void 0:s.path,issues:s==null?void 0:s.issues,lang:t.lang,abortEarly:t.abortEarly,abortPipeEarly:t.abortPipeEarly},p=e.kind==="schema",f=(y=(B=(q=(E=(g=s==null?void 0:s.message)!=null?g:e.message)!=null?E:Kn(e.reference,o.lang))!=null?q:p?zn(o.lang):null)!=null?B:t.message)!=null?y:Un(o.lang);f!==void 0&&(o.message=typeof f=="function"?f(o):f),p&&(n.typed=!1),n.issues?n.issues.push(o):n.issues=[o]}function S(e){return{version:1,vendor:"valibot",validate(r){return e["~run"]({value:r},on())}}}function Jn(e,r){return Object.hasOwn(e,r)&&r!=="__proto__"&&r!=="prototype"&&r!=="constructor"}function ln(e,r){var t;let n=[...new Set(e)];return n.length>1?`(${n.join(` ${r} `)})`:(t=n[0])!=null?t:"never"}var Mr=new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$","u");function De(e){return{kind:"validation",type:"integer",reference:De,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(r,n){return r.typed&&!this.requirement(r.value)&&w(this,"integer",r,n),r}}}function je(e,r){return{kind:"validation",type:"min_length",reference:je,async:!1,expects:`>=${e}`,requirement:e,message:r,"~run"(n,t){return n.typed&&n.value.length<this.requirement&&w(this,"length",n,t,{received:`${n.value.length}`}),n}}}function Oe(e,r){return{kind:"validation",type:"min_value",reference:Oe,async:!1,expects:`>=${e instanceof Date?e.toJSON():$(e)}`,requirement:e,message:r,"~run"(n,t){return n.typed&&!(n.value>=this.requirement)&&w(this,"value",n,t,{received:n.value instanceof Date?n.value.toJSON():$(n.value)}),n}}}function Xn(e,r,n){return typeof e.fallback=="function"?e.fallback(r,n):e.fallback}function ae(e,r,n){return typeof e.default=="function"?e.default(r,n):e.default}function Y(e,r){return{kind:"schema",type:"array",reference:Y,expects:"Array",async:!1,item:e,message:r,get"~standard"(){return S(this)},"~run"(n,t){var i;let s=n.value;if(Array.isArray(s)){n.typed=!0,n.value=[];for(let u=0;u<s.length;u++){let l=s[u],o=this.item["~run"]({value:l},t);if(o.issues){let p={type:"array",origin:"value",input:s,key:u,value:l};for(let f of o.issues)f.path?f.path.unshift(p):f.path=[p],(i=n.issues)==null||i.push(f);if(n.issues||(n.issues=o.issues),t.abortEarly){n.typed=!1;break}}o.typed||(n.typed=!1),n.value.push(o.value)}}else w(this,"type",n,t);return n}}}function Z(e){return{kind:"schema",type:"boolean",reference:Z,expects:"boolean",async:!1,message:e,get"~standard"(){return S(this)},"~run"(r,n){return typeof r.value=="boolean"?r.typed=!0:w(this,"type",r,n),r}}}function z(e,r){return{kind:"schema",type:"literal",reference:z,expects:$(e),async:!1,literal:e,message:r,get"~standard"(){return S(this)},"~run"(n,t){return n.value===this.literal?n.typed=!0:w(this,"type",n,t),n}}}function h(e,r){return{kind:"schema",type:"nullable",reference:h,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:r,get"~standard"(){return S(this)},"~run"(n,t){return n.value===null&&(this.default!==void 0&&(n.value=ae(this,n,t)),n.value===null)?(n.typed=!0,n):this.wrapped["~run"](n,t)}}}function I(e,r){return{kind:"schema",type:"nullish",reference:I,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:r,get"~standard"(){return S(this)},"~run"(n,t){return(n.value===null||n.value===void 0)&&(this.default!==void 0&&(n.value=ae(this,n,t)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,t)}}}function v(e){return{kind:"schema",type:"number",reference:v,expects:"number",async:!1,message:e,get"~standard"(){return S(this)},"~run"(r,n){return typeof r.value=="number"&&!isNaN(r.value)?r.typed=!0:w(this,"type",r,n),r}}}function d(e,r){return{kind:"schema",type:"object",reference:d,expects:"Object",async:!1,entries:e,message:r,get"~standard"(){return S(this)},"~run"(n,t){var i;let s=n.value;if(s&&typeof s=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in s||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let o=u in s?s[u]:ae(l),p=l["~run"]({value:o},t);if(p.issues){let f={type:"object",origin:"value",input:s,key:u,value:o};for(let c of p.issues)c.path?c.path.unshift(f):c.path=[f],(i=n.issues)==null||i.push(c);if(n.issues||(n.issues=p.issues),t.abortEarly){n.typed=!1;break}}p.typed||(n.typed=!1),n.value[u]=p.value}else if(l.fallback!==void 0)n.value[u]=Xn(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(w(this,"key",n,t,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:s,key:u,value:s[u]}]}),t.abortEarly))break}}else w(this,"type",n,t);return n}}}function x(e,r){return{kind:"schema",type:"optional",reference:x,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:r,get"~standard"(){return S(this)},"~run"(n,t){return n.value===void 0&&(this.default!==void 0&&(n.value=ae(this,n,t)),n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,t)}}}function T(e,r){return{kind:"schema",type:"picklist",reference:T,expects:ln(e.map($),"|"),async:!1,options:e,message:r,get"~standard"(){return S(this)},"~run"(n,t){return this.options.includes(n.value)?n.typed=!0:w(this,"type",n,t),n}}}function M(e,r,n){return{kind:"schema",type:"record",reference:M,expects:"Object",async:!1,key:e,value:r,message:n,get"~standard"(){return S(this)},"~run"(t,s){var u,l;let i=t.value;if(i&&typeof i=="object"){t.typed=!0,t.value={};for(let o in i)if(Jn(i,o)){let p=i[o],f=this.key["~run"]({value:o},s);if(f.issues){let b={type:"object",origin:"key",input:i,key:o,value:p};for(let m of f.issues)m.path=[b],(u=t.issues)==null||u.push(m);if(t.issues||(t.issues=f.issues),s.abortEarly){t.typed=!1;break}}let c=this.value["~run"]({value:p},s);if(c.issues){let b={type:"object",origin:"value",input:i,key:o,value:p};for(let m of c.issues)m.path?m.path.unshift(b):m.path=[b],(l=t.issues)==null||l.push(m);if(t.issues||(t.issues=c.issues),s.abortEarly){t.typed=!1;break}}(!f.typed||!c.typed)&&(t.typed=!1),f.typed&&(t.value[f.value]=c.value)}}else w(this,"type",t,s);return t}}}function a(e){return{kind:"schema",type:"string",reference:a,expects:"string",async:!1,message:e,get"~standard"(){return S(this)},"~run"(r,n){return typeof r.value=="string"?r.typed=!0:w(this,"type",r,n),r}}}function un(e){let r;if(e)for(let n of e)r?r.push(...n.issues):r=n.issues;return r}function Re(e,r){return{kind:"schema",type:"union",reference:Re,expects:ln(e.map(n=>n.expects),"|"),async:!1,options:e,message:r,get"~standard"(){return S(this)},"~run"(n,t){let s,i,u;for(let l of this.options){let o=l["~run"]({value:n.value},t);if(o.typed)if(o.issues)i?i.push(o):i=[o];else{s=o;break}else u?u.push(o):u=[o]}if(s)return s;if(i){if(i.length===1)return i[0];w(this,"type",n,t,{issues:un(i)}),n.typed=!0}else{if((u==null?void 0:u.length)===1)return u[0];w(this,"type",n,t,{issues:un(u)})}return n}}}function Ce(){return{kind:"schema",type:"unknown",reference:Ce,expects:"unknown",async:!1,get"~standard"(){return S(this)},"~run"(e){return e.typed=!0,e}}}function Ne(...e){return R(P({},e[0]),{pipe:e,get"~standard"(){return S(this)},"~run"(r,n){for(let t of e)if(t.kind!=="metadata"){if(r.issues&&(t.kind==="schema"||t.kind==="transformation")){r.typed=!1;break}(!r.issues||!n.abortEarly&&!n.abortPipeEarly)&&(r=t["~run"](r,n))}return r}})}function ce(e,r,n){let t=e["~run"]({value:r},on(n));return{typed:t.typed,success:!t.issues,output:t.value,issues:t.issues}}var Hn=["agent","sdk","form","integration","migration"],Wn=["PENDING","SUBMITTED","SCREENING","SHORTLISTED","INTERVIEW","OFFERED","HIRED","REJECTED","WITHDRAWN"],$n=["screening","cv_match","interview","overall"],Yn=["PENDING","SCHEDULED","IN_PROGRESS","COMPLETED","CANCELLED"],Zn=["job","company"],Qn=["created_at","updated_at"],er=["asc","desc"],pe=T(Hn),fe=T(Wn),ye=T($n),an=T(Yn),Vr=T(Zn),cn=T(Qn),pn=T(er);var nr=d({total:v(),page:v(),perPage:v(),lastPage:v()});function he(e){return d({data:Y(e),pagination:nr})}var Q=d({id:a(),email:h(a()),firstName:h(a()),lastName:h(a()),phone:h(a()),source:h(pe),identifiedAt:h(a()),createdAt:a(),updatedAt:a()});var K=Ne(a(),je(1)),fn=Ne(v(),De(),Oe(1)),L=M(a(),Ce());var yn=d({id:a(),applicationId:a(),status:an,scheduledAt:h(a()),completedAt:h(a()),meta:h(L),createdAt:a(),updatedAt:a()});var Le=d({score:v(),reason:a(),confidence:v()}),hn=d({id:a(),candidateId:a(),jobId:v(),status:fe,sessionId:h(v()),externalApplicationId:h(a()),meta:h(L),context:h(L),scoredAt:h(a()),shortlistedAt:h(a()),createdAt:a(),updatedAt:a()}),rr=d({id:a(),applicationId:a(),scoreType:ye,score:h(v()),reason:h(a()),categories:h(M(a(),Le)),scoredBy:h(a()),createdAt:a()}),mn=d(R(P({},hn.entries),{candidate:h(Q),score:h(rr),interview:h(yn)})),tr=d(R(P({},Q.entries),{applications:Y(hn)}));var dn=d({anonymousId:K,email:K,firstName:I(a()),lastName:I(a()),phone:I(a()),source:I(pe)}),vn=d({candidateId:a(),isNew:Z()});var at=d({status:x(fe),job_id:x(a()),candidate_id:x(a()),created_from:x(a()),created_to:x(a()),updated_from:x(a()),updated_to:x(a()),from:x(a()),to:x(a()),q:x(a()),scored:x(T(["true","false"])),shortlisted:x(T(["true","false"])),sort:x(cn),order:x(pn),page:x(a()),per_page:x(a())}),ct=d({candidateId:K,jobId:fn,meta:I(L),sessionId:I(v()),externalApplicationId:I(a()),context:I(L)}),gn=d({id:a(),status:a(),createdAt:a()}),pt=Re([d({ok:z(!0),duplicate:z(!1),applicationId:a(),candidateId:a()}),d({ok:z(!0),duplicate:z(!0),existingApplication:gn})]),bn=d({isDuplicate:Z(),existingApplication:x(gn)}),ft=d({applicationId:K,scoreType:ye,score:v(),reason:I(a()),categories:I(M(a(),Le)),scoredBy:I(a())}),yt=d({scoreId:a()}),ht=he(mn);var bt=he(Q);var xt=d({avg_score:h(v()),p90_score:h(v()),p85_score:h(v()),p80_score:h(v()),total_scores:v()});var qe=({environment:e,publishableKey:r,logger:n})=>{let t=rn[e];return{checkDuplicate(i){return A(this,null,function*(){try{let u=new URLSearchParams({email:i.email,scope:i.scope});i.scope==="job"&&i.jobId!=null&&u.set("job_id",String(i.jobId));let l=yield fetch(`${t}/applications/check-duplicate?${u}`,{method:"GET",headers:{Accept:"application/json","x-publishable-key":r}});if(!l.ok)return n.error(`[TalentBankClient] checkDuplicate failed with status ${l.status}`),{isDuplicate:!1};let o=ce(bn,yield l.json());return o.success?o.output:(n.error("[TalentBankClient] checkDuplicate returned an invalid response"),{isDuplicate:!1})}catch(u){return n.error("[TalentBankClient] checkDuplicate failed:",u),{isDuplicate:!1}}})},identify(i){return A(this,null,function*(){var u;try{if(!i.anonymousId)return n.error("[TalentBankClient] identify skipped because anonymousId is missing"),null;let l={email:i.email,firstName:i.firstName,lastName:i.lastName,phone:i.phone,anonymousId:i.anonymousId,source:(u=i.source)!=null?u:"sdk"},o=ce(dn,l);if(!o.success)return n.error("[TalentBankClient] identify received invalid input"),null;let p=yield fetch(`${t}/identify`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-publishable-key":r},body:JSON.stringify(o.output)});if(!p.ok)return n.error(`[TalentBankClient] identify failed with status ${p.status}`),null;let f=ce(vn,yield p.json());return f.success?f.output:(n.error("[TalentBankClient] identify returned an invalid response"),null)}catch(l){return n.error("[TalentBankClient] identify failed:",l),null}})}}};var Fe=()=>typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+e/4).toString(16));function Me(e){if(typeof document!="undefined"){if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",e,{once:!0});return}Promise.resolve().then(e)}}var Ve=e=>{let r=new Date;return r.setTime(r.getTime()+7*24*60*60*1e3),`${U}=${e};expires=${r.toUTCString()};path=/`},sr=(e,r)=>{let n=e.get("session_id");if(r||n)return n;let t=sessionStorage.getItem(`${U}-session_id`);return typeof t=="string"?t:null},ur=()=>{if(typeof window=="undefined")return null;try{let e=window.localStorage.getItem(oe);return typeof e=="string"&&e!==""?e:null}catch(e){return null}},or=e=>{if(typeof window!="undefined")try{e?window.localStorage.setItem(oe,e):window.localStorage.removeItem(oe)}catch(r){}},lr=new RegExp(`${U}=([^;]+)`),Ge=e=>{let r=e?e.url:location.href,{searchParams:n}=new URL(r),t=n.get("anonymous_id"),s=sr(n,typeof window=="undefined");if(t)return{anonymous_id:t,session_id:s};let i=e?e.headers.get("cookie"):document.cookie;if(i){let u=lr.exec(i),l=u==null?void 0:u[1];return{anonymous_id:l!=null?l:null,session_id:s}}return{anonymous_id:t,session_id:s}},kn=()=>{if(typeof window=="undefined")throw new Error("getOrCreateAnonymousId() can only be called in browser environment");let e=Ge().anonymous_id;if(e)return e;let r=Fe();return document.cookie=Ve(r),r},ar=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},cr=e=>e==="about:client"?"":e,pr={pathname:"/log",method:"POST",schema:{response:le(),body:le()}},xn=({rpcClient:e,logger:r,onEvent:n,talentBank:t})=>({log:i=>A(void 0,null,function*(){var l;ve(i.request||typeof window!="undefined","Cannot log on the server without a request. Please pass a request to `log`.");let u="request"in i&&i.request?{href:i.request.url,referrer:cr(i.request.referrer),title:""}:{href:location.href,referrer:document.referrer,title:document.title};try{let o={library:{name:"inploi-sdk",version:tn},page:u},p=Ge(i.request);i.event==="IDENTIFY"&&!p.anonymous_id&&!i.request&&typeof window!="undefined"&&(p=R(P({},p),{anonymous_id:kn()}));let f=ur();if(i.event==="IDENTIFY"&&t&&p.anonymous_id){let g=i.properties,E=yield t.identify({email:(l=g.email)!=null?l:g.identifier,firstName:g.first_name,lastName:g.last_name,phone:g.phone_number,anonymousId:p.anonymous_id,source:"sdk"});E!=null&&E.candidateId&&(f=E.candidateId,or(E.candidateId))}let c={anonymous_id:p.anonymous_id,session_id:p.session_id,candidate_id:f,event:i.event,sent_at:new Date().toISOString(),context:o,properties:i.properties,custom_properties:i.customProperties},b=yield e.request(pr,{body:c}),m=ar(b);return m!=null&&m.anonymous_id&&(c.anonymous_id=m.anonymous_id),m!=null&&m.session_id&&(c.session_id=m.session_id),typeof window!="undefined"&&c.anonymous_id&&(c.session_id&&sessionStorage.setItem(`${U}-session_id`,c.session_id.toString()),document.cookie=Ve(c.anonymous_id)),n==null||n(c),{success:!0,data:c}}catch(o){return r.error("Failed to send log to API. Inspect error response of `log` for more information."),{success:!1,error:o}}}),getHeaders:i=>{let u=new Headers;return i!=null&&i.anonymous_id&&u.append("Set-Cookie",Ve(i.anonymous_id)),u},getSessionInfo:Ge});function Be({publishableKey:e,env:r,logger:n=be,onEvent:t}){let s=We({baseUrl:ue[r],publishableKey:e}),i=n===!1?ke:n,u=new W({environment:r,apiKey:{type:"publishable",key:e},logger:i}),l=qe({environment:r,publishableKey:e,logger:i}),o=xn({rpcClient:u,logger:i,onEvent:t,talentBank:l});return{register:f=>f({logger:i,apiClient:s,analytics:o,rpcClient:u,publishableKey:e,env:r}),analytics:o,apiClient:s}}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=Be;window.inploi.ready=Me;})();
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var ne=Object.create;var I=Object.defineProperty;var re=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var se=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty;var ae=(e,t)=>{for(var n in t)I(e,n,{get:t[n],enumerable:!0})},K=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of oe(t))!ie.call(e,s)&&s!==n&&I(e,s,{get:()=>t[s],enumerable:!(r=re(t,s))||r.enumerable});return e};var pe=(e,t,n)=>(n=e!=null?ne(se(e)):{},K(t||!e||!e.__esModule?I(n,"default",{value:e,enumerable:!0}):n,e)),ce=e=>K(I({},"__esModule",{value:!0}),e);var Ie={};ae(Ie,{ApiError:()=>y,InploiRpcClient:()=>h,NotFoundError:()=>m,ParsingError:()=>l,SchemaValidationError:()=>d,SdkError:()=>V,UnauthorisedError:()=>f,createPlugin:()=>Y,createTalentBankClient:()=>L,endpoint:()=>j,generateUUID:()=>A,getOrCreateAnonymousId:()=>$,initialiseSdk:()=>Q,inploiBrandedLogger:()=>b,isSdkError:()=>J,noLogging:()=>E,ready:()=>ee,typed:()=>_,validateEndpointInputs:()=>q});module.exports=ce(Ie);var x="%c[inploi SDK]",k="color: #65BC67; font-weight: bold;",b={warn:(...e)=>console.warn(x,k,...e),error:(...e)=>console.error(x,k,...e),info:(...e)=>console.info(x,k,...e),log:(...e)=>console.log(x,k,...e)},E={info:()=>{},error:()=>{},log:()=>{},warn:()=>{}};var Y=e=>e;function N(e,t){if(!e)throw new Error(t)}function B(e,t){return t in e}var Oe=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});var de="Unauthenticated",le="This action is unauthorized.",u=class extends Error{constructor(n,r){super(n);this.status=r,this.name="ErrorWithStatus"}},m=class extends u{constructor(t){super(t??"Not found"),this.name="NotFoundError",this.status=404}},f=class extends u{constructor(t,n){super(t??"You are not authorised to perform this action."),this.name="UnauthorisedError",this.status=n??401}},d=class extends u{constructor(n,r){let s=r?` in ${r}`:"";super(`Schema validation failed${s}`);this.issues=n;this.source=r;this.name="SchemaValidationError",this.status=400}},y=class extends u{constructor(t,n){super(t),this.name="ApiError",this.status=n??500}},l=class extends u{constructor(n){super("Error parsing response into JSON.");this.response=n;this.name="ParsingError",this.status=500}};var ue=["message","error","errors","exception","exceptions"];function me(e){console.log("json",e);let t=[];if(typeof e=="object"&&e!==null){for(let n of ue)if(B(e,n)){console.log("hasProp",n,e[n]);let r=e[n];typeof r=="string"&&t.push(r),Array.isArray(r)&&r.every(s=>typeof s=="string")&&t.push(...r)}}return t.length===0&&t.push("Unknown error"),t.join(", ")}function D(e,t){if(t>=300&&t<=500){let n=me(e);throw t===404?new m(n):n===de?new f("You are not authenticated.",t):n===le?new f(n,t):new y(n,t)}}var H=e=>{let t={Accept:"application/json","Content-Type":"application/json","x-publishable-key":e.publishableKey};return{fetch:async(n,r={})=>{let s={...r,headers:{...r.headers,...t}},o=await fetch(`${e.baseUrl}${n}`,s);if(o.status===404)throw new m;let i=await o.json().catch(async()=>{throw new l(o)});return D(i,o.status),i}}},V={NotFound:m,Unauthorised:f,SchemaValidation:d,Api:y,JsonParsing:l};function J(e){return Object.values(V).some(t=>e instanceof t)}var G="2.0.1";var w={sandbox:"https://api.staging.inploi.com",production:"https://api.inploi.com",_internal_local:"http://api.test"},W={sandbox:"https://talent-bank.staging.inploi.com",production:"https://talent-bank.inploi.com",_internal_local:"http://localhost:8787"},z=G;var g="isdk_session",R=`${g}-candidate_id`;var A=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+e/4).toString(16));var U=e=>{let t=new Date;return t.setTime(t.getTime()+7*24*60*60*1e3),`${g}=${e};expires=${t.toUTCString()};path=/`},ye=(e,t)=>{let n=e.get("session_id");if(t||n)return n;let r=sessionStorage.getItem(`${g}-session_id`);return typeof r=="string"?r:null},ge=()=>{if(typeof window>"u")return null;try{let e=window.localStorage.getItem(R);return typeof e=="string"&&e!==""?e:null}catch{return null}},he=e=>{if(!(typeof window>"u"))try{e?window.localStorage.setItem(R,e):window.localStorage.removeItem(R)}catch{}},Te=new RegExp(`${g}=([^;]+)`),M=e=>{let t=e?e.url:location.href,{searchParams:n}=new URL(t),r=n.get("anonymous_id"),s=ye(n,typeof window>"u");if(r)return{anonymous_id:r,session_id:s};let o=e?e.headers.get("cookie"):document.cookie;return o?{anonymous_id:Te.exec(o)?.[1]??null,session_id:s}:{anonymous_id:r,session_id:s}},$=()=>{if(typeof window>"u")throw new Error("getOrCreateAnonymousId() can only be called in browser environment");let e=M().anonymous_id;if(e)return e;let t=A();return document.cookie=U(t),t},ve=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},Se=e=>e==="about:client"?"":e,_e={pathname:"/log",method:"POST",schema:{response:_(),body:_()}},X=({rpcClient:e,logger:t,onEvent:n,talentBank:r})=>({log:async o=>{N(o.request||typeof window<"u","Cannot log on the server without a request. Please pass a request to `log`.");let i="request"in o&&o.request?{href:o.request.url,referrer:Se(o.request.referrer),title:""}:{href:location.href,referrer:document.referrer,title:document.title};try{let a={library:{name:"inploi-sdk",version:z},page:i},p=M(o.request);o.event==="IDENTIFY"&&!p.anonymous_id&&!o.request&&typeof window<"u"&&(p={...p,anonymous_id:$()});let v=ge();if(o.event==="IDENTIFY"&&r&&p.anonymous_id){let S=o.properties,O=await r.identify({email:S.email??S.identifier,firstName:S.first_name,lastName:S.last_name,phone:S.phone_number,anonymousId:p.anonymous_id,source:"sdk"});O?.candidateId&&(v=O.candidateId,he(O.candidateId))}let c={anonymous_id:p.anonymous_id,session_id:p.session_id,candidate_id:v,event:o.event,sent_at:new Date().toISOString(),context:a,properties:o.properties,custom_properties:o.customProperties},te=await e.request(_e,{body:c}),P=ve(te);return P?.anonymous_id&&(c.anonymous_id=P.anonymous_id),P?.session_id&&(c.session_id=P.session_id),typeof window<"u"&&c.anonymous_id&&(c.session_id&&sessionStorage.setItem(`${g}-session_id`,c.session_id.toString()),document.cookie=U(c.anonymous_id)),n?.(c),{success:!0,data:c}}catch(a){return t.error("Failed to send log to API. Inspect error response of `log` for more information."),{success:!1,error:a}}},getHeaders:o=>{let i=new Headers;return o?.anonymous_id&&i.append("Set-Cookie",U(o.anonymous_id)),i},getSessionInfo:M});var Z=require("neoqs");function F(e,t,n){let r=e["~standard"].validate(t);if(r instanceof Promise)throw new TypeError("Async schema");if(r.issues)throw new d(r.issues,n);return r.value}function Pe(e,t,n){try{return{success:!0,output:F(e,t,n)}}catch(r){if(r instanceof d)return{success:!1,issues:r.issues,source:r.source};throw r}}var h=class{constructor(t){if(this.baseUrl=w[t.environment],this.headers=new Headers({"Content-Type":"application/json",Accept:"application/json"}),t.apiKey.type==="secret"){if(typeof window<"u")throw new Error("Secret key cannot be used in a browser environment");this.headers.set("x-secret-key",t.apiKey.key)}else this.headers.set("x-publishable-key",t.apiKey.key);this.logger=t.logger,this._environment=t.environment}get environment(){return this._environment}getFetchParams(t,n){let r=n.validateIn??!0,{searchParams:s,body:o}=r?q(t,n):n,i=new URL(this.baseUrl),a=t.pathname;if("params"in n&&n.params)for(let[p,v]of Object.entries(n.params))a=a.replace(`:${p}`,String(v));return i.pathname=a,t.schema.searchParams&&(i.search=(0,Z.stringify)(s)),[i.toString(),{method:t.method,body:o?JSON.stringify(o):void 0,headers:this.headers,signal:n.signal}]}async parseResponse(t,n){let r=await n.response.json().catch(i=>{throw this.logger.error(i),new l(n.response)});if(!(n.validateOut??!0))return r;let o=Pe(t.schema.response,r,"response");if(!o.success)throw D(r,n.response.status),new d(o.issues,o.source);return o.output}async request(t,n){try{let r=this.getFetchParams(t,n),s=await fetch(...r);return this.parseResponse(t,{response:s,validateOut:n.validateOut})}catch(r){throw r instanceof d?this.logger.error(r.message,r.issues):this.logger.error(r),r}}};function _(){return{"~standard":{vendor:"inploi",version:1,validate:e=>({value:e})}}}function j(e){return e}function q(e,t){let n={searchParams:void 0,body:void 0,validateIn:!1};return e.schema.searchParams&&(n.searchParams=F(e.schema.searchParams,"searchParams"in t?t.searchParams:{})),e.schema.body&&(n.body=F(e.schema.body,"body"in t?t.body:{})),n}var T=require("@inploi/talent-bank/contract"),C=pe(require("valibot"));var L=({environment:e,publishableKey:t,logger:n})=>{let r=W[e];return{async checkDuplicate(s){try{let o=new URLSearchParams({email:s.email,scope:s.scope});s.scope==="job"&&s.jobId!=null&&o.set("job_id",String(s.jobId));let i=await fetch(`${r}/applications/check-duplicate?${o}`,{method:"GET",headers:{Accept:"application/json","x-publishable-key":t}});if(!i.ok)return n.error(`[TalentBankClient] checkDuplicate failed with status ${i.status}`),{isDuplicate:!1};let a=C.safeParse(T.DuplicateCheckResultSchema,await i.json());return a.success?a.output:(n.error("[TalentBankClient] checkDuplicate returned an invalid response"),{isDuplicate:!1})}catch(o){return n.error("[TalentBankClient] checkDuplicate failed:",o),{isDuplicate:!1}}},async identify(s){try{if(!s.anonymousId)return n.error("[TalentBankClient] identify skipped because anonymousId is missing"),null;let o={email:s.email,firstName:s.firstName,lastName:s.lastName,phone:s.phone,anonymousId:s.anonymousId,source:s.source??"sdk"},i=C.safeParse(T.IdentifyInputSchema,o);if(!i.success)return n.error("[TalentBankClient] identify received invalid input"),null;let a=await fetch(`${r}/identify`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-publishable-key":t},body:JSON.stringify(i.output)});if(!a.ok)return n.error(`[TalentBankClient] identify failed with status ${a.status}`),null;let p=C.safeParse(T.IdentifyResultSchema,await a.json());return p.success?p.output:(n.error("[TalentBankClient] identify returned an invalid response"),null)}catch(o){return n.error("[TalentBankClient] identify failed:",o),null}}}};function Q({publishableKey:e,env:t,logger:n=b,onEvent:r}){let s=H({baseUrl:w[t],publishableKey:e}),o=n===!1?E:n,i=new h({environment:t,apiKey:{type:"publishable",key:e},logger:o}),a=L({environment:t,publishableKey:e,logger:o}),p=X({rpcClient:i,logger:o,onEvent:r,talentBank:a});return{register:c=>c({logger:o,apiClient:s,analytics:p,rpcClient:i,publishableKey:e,env:t}),analytics:p,apiClient:s}}function ee(e){if(!(typeof document>"u")){if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",e,{once:!0});return}Promise.resolve().then(e)}}0&&(module.exports={ApiError,InploiRpcClient,NotFoundError,ParsingError,SchemaValidationError,SdkError,UnauthorisedError,createPlugin,createTalentBankClient,endpoint,generateUUID,getOrCreateAnonymousId,initialiseSdk,inploiBrandedLogger,isSdkError,noLogging,ready,typed,validateEndpointInputs});
|
|
1
|
+
"use strict";var ne=Object.create;var I=Object.defineProperty;var re=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var se=Object.getPrototypeOf,ae=Object.prototype.hasOwnProperty;var ie=(e,t)=>{for(var n in t)I(e,n,{get:t[n],enumerable:!0})},K=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of oe(t))!ae.call(e,s)&&s!==n&&I(e,s,{get:()=>t[s],enumerable:!(r=re(t,s))||r.enumerable});return e};var pe=(e,t,n)=>(n=e!=null?ne(se(e)):{},K(t||!e||!e.__esModule?I(n,"default",{value:e,enumerable:!0}):n,e)),ce=e=>K(I({},"__esModule",{value:!0}),e);var Ie={};ie(Ie,{ApiError:()=>y,InploiRpcClient:()=>h,NotFoundError:()=>m,ParsingError:()=>l,SchemaValidationError:()=>d,SdkError:()=>V,UnauthorisedError:()=>f,createPlugin:()=>Y,createTalentBankClient:()=>L,endpoint:()=>j,generateUUID:()=>A,getOrCreateAnonymousId:()=>$,initialiseSdk:()=>Q,inploiBrandedLogger:()=>b,isSdkError:()=>J,noLogging:()=>E,ready:()=>ee,typed:()=>_,validateEndpointInputs:()=>q});module.exports=ce(Ie);var x="%c[inploi SDK]",k="color: #65BC67; font-weight: bold;",b={warn:(...e)=>console.warn(x,k,...e),error:(...e)=>console.error(x,k,...e),info:(...e)=>console.info(x,k,...e),log:(...e)=>console.log(x,k,...e)},E={info:()=>{},error:()=>{},log:()=>{},warn:()=>{}};var Y=e=>e;function N(e,t){if(!e)throw new Error(t)}function B(e,t){return t in e}var Oe=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});var de="Unauthenticated",le="This action is unauthorized.",u=class extends Error{constructor(n,r){super(n);this.status=r,this.name="ErrorWithStatus"}},m=class extends u{constructor(t){super(t??"Not found"),this.name="NotFoundError",this.status=404}},f=class extends u{constructor(t,n){super(t??"You are not authorised to perform this action."),this.name="UnauthorisedError",this.status=n??401}},d=class extends u{constructor(n,r){let s=r?` in ${r}`:"";super(`Schema validation failed${s}`);this.issues=n;this.source=r;this.name="SchemaValidationError",this.status=400}},y=class extends u{constructor(t,n){super(t),this.name="ApiError",this.status=n??500}},l=class extends u{constructor(n){super("Error parsing response into JSON.");this.response=n;this.name="ParsingError",this.status=500}};var ue=["message","error","errors","exception","exceptions"];function me(e){console.log("json",e);let t=[];if(typeof e=="object"&&e!==null){for(let n of ue)if(B(e,n)){console.log("hasProp",n,e[n]);let r=e[n];typeof r=="string"&&t.push(r),Array.isArray(r)&&r.every(s=>typeof s=="string")&&t.push(...r)}}return t.length===0&&t.push("Unknown error"),t.join(", ")}function D(e,t){if(t>=300&&t<=500){let n=me(e);throw t===404?new m(n):n===de?new f("You are not authenticated.",t):n===le?new f(n,t):new y(n,t)}}var H=e=>{let t={Accept:"application/json","Content-Type":"application/json","x-publishable-key":e.publishableKey};return{fetch:async(n,r={})=>{let s={...r,headers:{...r.headers,...t}},o=await fetch(`${e.baseUrl}${n}`,s);if(o.status===404)throw new m;let a=await o.json().catch(async()=>{throw new l(o)});return D(a,o.status),a}}},V={NotFound:m,Unauthorised:f,SchemaValidation:d,Api:y,JsonParsing:l};function J(e){return Object.values(V).some(t=>e instanceof t)}var G="2.0.2";var w={sandbox:"https://api.staging.inploi.com",production:"https://api.inploi.com",_internal_local:"http://api.test"},W={sandbox:"https://talent-bank.staging.inploi.com",production:"https://talent-bank.inploi.com",_internal_local:"http://localhost:8787"},z=G;var g="isdk_session",R=`${g}-candidate_id`;var A=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+e/4).toString(16));var U=e=>{let t=new Date;return t.setTime(t.getTime()+7*24*60*60*1e3),`${g}=${e};expires=${t.toUTCString()};path=/`},ye=(e,t)=>{let n=e.get("session_id");if(t||n)return n;let r=sessionStorage.getItem(`${g}-session_id`);return typeof r=="string"?r:null},ge=()=>{if(typeof window>"u")return null;try{let e=window.localStorage.getItem(R);return typeof e=="string"&&e!==""?e:null}catch{return null}},he=e=>{if(!(typeof window>"u"))try{e?window.localStorage.setItem(R,e):window.localStorage.removeItem(R)}catch{}},Te=new RegExp(`${g}=([^;]+)`),M=e=>{let t=e?e.url:location.href,{searchParams:n}=new URL(t),r=n.get("anonymous_id"),s=ye(n,typeof window>"u");if(r)return{anonymous_id:r,session_id:s};let o=e?e.headers.get("cookie"):document.cookie;return o?{anonymous_id:Te.exec(o)?.[1]??null,session_id:s}:{anonymous_id:r,session_id:s}},$=()=>{if(typeof window>"u")throw new Error("getOrCreateAnonymousId() can only be called in browser environment");let e=M().anonymous_id;if(e)return e;let t=A();return document.cookie=U(t),t},ve=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},Se=e=>e==="about:client"?"":e,_e={pathname:"/log",method:"POST",schema:{response:_(),body:_()}},X=({rpcClient:e,logger:t,onEvent:n,talentBank:r})=>({log:async o=>{N(o.request||typeof window<"u","Cannot log on the server without a request. Please pass a request to `log`.");let a="request"in o&&o.request?{href:o.request.url,referrer:Se(o.request.referrer),title:""}:{href:location.href,referrer:document.referrer,title:document.title};try{let i={library:{name:"inploi-sdk",version:z},page:a},p=M(o.request);o.event==="IDENTIFY"&&!p.anonymous_id&&!o.request&&typeof window<"u"&&(p={...p,anonymous_id:$()});let v=ge();if(o.event==="IDENTIFY"&&r&&p.anonymous_id){let S=o.properties,O=await r.identify({email:S.email??S.identifier,firstName:S.first_name,lastName:S.last_name,phone:S.phone_number,anonymousId:p.anonymous_id,source:"sdk"});O?.candidateId&&(v=O.candidateId,he(O.candidateId))}let c={anonymous_id:p.anonymous_id,session_id:p.session_id,candidate_id:v,event:o.event,sent_at:new Date().toISOString(),context:i,properties:o.properties,custom_properties:o.customProperties},te=await e.request(_e,{body:c}),P=ve(te);return P?.anonymous_id&&(c.anonymous_id=P.anonymous_id),P?.session_id&&(c.session_id=P.session_id),typeof window<"u"&&c.anonymous_id&&(c.session_id&&sessionStorage.setItem(`${g}-session_id`,c.session_id.toString()),document.cookie=U(c.anonymous_id)),n?.(c),{success:!0,data:c}}catch(i){return t.error("Failed to send log to API. Inspect error response of `log` for more information."),{success:!1,error:i}}},getHeaders:o=>{let a=new Headers;return o?.anonymous_id&&a.append("Set-Cookie",U(o.anonymous_id)),a},getSessionInfo:M});var Z=require("neoqs");function F(e,t,n){let r=e["~standard"].validate(t);if(r instanceof Promise)throw new TypeError("Async schema");if(r.issues)throw new d(r.issues,n);return r.value}function Pe(e,t,n){try{return{success:!0,output:F(e,t,n)}}catch(r){if(r instanceof d)return{success:!1,issues:r.issues,source:r.source};throw r}}var h=class{constructor(t){if(this.baseUrl=w[t.environment],this.headers=new Headers({"Content-Type":"application/json",Accept:"application/json"}),t.apiKey.type==="secret"){if(typeof window<"u")throw new Error("Secret key cannot be used in a browser environment");this.headers.set("x-secret-key",t.apiKey.key)}else this.headers.set("x-publishable-key",t.apiKey.key);this.logger=t.logger,this._environment=t.environment}get environment(){return this._environment}getFetchParams(t,n){let r=n.validateIn??!0,{searchParams:s,body:o}=r?q(t,n):n,a=new URL(this.baseUrl),i=t.pathname;if("params"in n&&n.params)for(let[p,v]of Object.entries(n.params))i=i.replace(`:${p}`,String(v));return a.pathname=i,t.schema.searchParams&&(a.search=(0,Z.stringify)(s)),[a.toString(),{method:t.method,body:o?JSON.stringify(o):void 0,headers:this.headers,signal:n.signal}]}async parseResponse(t,n){let r=await n.response.json().catch(a=>{throw this.logger.error(a),new l(n.response)});if(!(n.validateOut??!0))return r;let o=Pe(t.schema.response,r,"response");if(!o.success)throw D(r,n.response.status),new d(o.issues,o.source);return o.output}async request(t,n){try{let r=this.getFetchParams(t,n),s=await fetch(...r);return this.parseResponse(t,{response:s,validateOut:n.validateOut})}catch(r){throw r instanceof d?this.logger.error(r.message,r.issues):this.logger.error(r),r}}};function _(){return{"~standard":{vendor:"inploi",version:1,validate:e=>({value:e})}}}function j(e){return e}function q(e,t){let n={searchParams:void 0,body:void 0,validateIn:!1};return e.schema.searchParams&&(n.searchParams=F(e.schema.searchParams,"searchParams"in t?t.searchParams:{})),e.schema.body&&(n.body=F(e.schema.body,"body"in t?t.body:{})),n}var T=require("@inploi/talent-bank/contract"),C=pe(require("valibot"));var L=({environment:e,publishableKey:t,logger:n})=>{let r=W[e];return{async checkDuplicate(s){try{let o=new URLSearchParams({email:s.email,scope:s.scope});s.scope==="job"&&s.jobId!=null&&o.set("job_id",String(s.jobId));let a=await fetch(`${r}/applications/check-duplicate?${o}`,{method:"GET",headers:{Accept:"application/json","x-publishable-key":t}});if(!a.ok)return n.error(`[TalentBankClient] checkDuplicate failed with status ${a.status}`),{isDuplicate:!1};let i=C.safeParse(T.DuplicateCheckResultSchema,await a.json());return i.success?i.output:(n.error("[TalentBankClient] checkDuplicate returned an invalid response"),{isDuplicate:!1})}catch(o){return n.error("[TalentBankClient] checkDuplicate failed:",o),{isDuplicate:!1}}},async identify(s){try{if(!s.anonymousId)return n.error("[TalentBankClient] identify skipped because anonymousId is missing"),null;let o={email:s.email,firstName:s.firstName,lastName:s.lastName,phone:s.phone,anonymousId:s.anonymousId,source:s.source??"sdk"},a=C.safeParse(T.IdentifyInputSchema,o);if(!a.success)return n.error("[TalentBankClient] identify received invalid input"),null;let i=await fetch(`${r}/identify`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-publishable-key":t},body:JSON.stringify(a.output)});if(!i.ok)return n.error(`[TalentBankClient] identify failed with status ${i.status}`),null;let p=C.safeParse(T.IdentifyResultSchema,await i.json());return p.success?p.output:(n.error("[TalentBankClient] identify returned an invalid response"),null)}catch(o){return n.error("[TalentBankClient] identify failed:",o),null}}}};function Q({publishableKey:e,env:t,logger:n=b,onEvent:r}){let s=H({baseUrl:w[t],publishableKey:e}),o=n===!1?E:n,a=new h({environment:t,apiKey:{type:"publishable",key:e},logger:o}),i=L({environment:t,publishableKey:e,logger:o}),p=X({rpcClient:a,logger:o,onEvent:r,talentBank:i});return{register:c=>c({logger:o,apiClient:s,analytics:p,rpcClient:a,publishableKey:e,env:t}),analytics:p,apiClient:s}}function ee(e){if(!(typeof document>"u")){if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",e,{once:!0});return}Promise.resolve().then(e)}}0&&(module.exports={ApiError,InploiRpcClient,NotFoundError,ParsingError,SchemaValidationError,SdkError,UnauthorisedError,createPlugin,createTalentBankClient,endpoint,generateUUID,getOrCreateAnonymousId,initialiseSdk,inploiBrandedLogger,isSdkError,noLogging,ready,typed,validateEndpointInputs});
|
|
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","../../core/src/common/common.utils.ts","../../core/src/common/common.currency.ts","../../core/src/common/common.datetime.ts","../src/sdk.api.ts","../package.json","../src/sdk.constants.ts","../src/sdk.uuid.ts","../src/sdk.analytics.ts","../src/sdk.rpc.ts","../src/sdk.talent-bank.ts","../src/sdk.ts","../src/ready.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 {\n\tApiError,\n\tNotFoundError,\n\tJsonParsingError as ParsingError,\n\tUnauthorisedError,\n\tisSdkError,\n\tSchemaValidationError,\n\tSdkError,\n} from './sdk.api';\n\nexport { initialiseSdk } from './sdk';\nexport type { InitialiseInploiSdkParams, InploiSdk } from './sdk';\n\nexport type {\n\tAnalyticsService,\n\tAnalyticsLogEvent,\n\tAnalyticsLogParams,\n\tAnalyticsOnEventCallback,\n} from './sdk.analytics';\nexport { getOrCreateAnonymousId } from './sdk.analytics';\n\nexport { InploiRpcClient, endpoint, typed, validateEndpointInputs } from './sdk.rpc';\nexport type { RpcEndpoint } from './sdk.rpc';\n\nexport { createTalentBankClient } from './sdk.talent-bank';\nexport type {\n\tTalentBankCheckDuplicateResult,\n\tTalentBankClient,\n\tTalentBankIdentifyParams,\n\tTalentBankIdentifyResult,\n} from './sdk.talent-bank';\nexport { generateUUID } from './sdk.uuid';\nexport { ready } from './ready';\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 { InploiSdkEnvironment } from './sdk.constants';\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\t/** The publishable key used to initialise the SDK (available when registered via initialiseSdk) */\n\tpublishableKey?: string;\n\t/** The environment the SDK was initialised with — plugins can use this to select the correct service URL */\n\tenv?: InploiSdkEnvironment;\n};\n\nexport type InploiSdkPlugin = (dependencies: PluginDependencies) => any;\n\nexport const createPlugin = <T extends InploiSdkPlugin>(pluginFn: T) => pluginFn;\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\ttrailingZeroDisplay: 'stripIfInteger',\n\t});\n\tif (salary.pay_display === false) return undefined;\n\tif (salary.pay === null && salary.pay_min === null && salary.pay_max === null) 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","import { hasProp } from '@inploi/core/common';\nimport { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport const unauthenticatedMessage = 'Unauthenticated';\nexport const unauthorisedMessage = 'This action is unauthorized.';\n\nexport class ErrorWithStatus extends Error {\n\tpublic status?: number;\n\tconstructor(message?: string, status?: number) {\n\t\tsuper(message);\n\t\tthis.status = status;\n\t\tthis.name = 'ErrorWithStatus';\n\t}\n}\n\nexport class NotFoundError extends ErrorWithStatus {\n\tconstructor(message?: string) {\n\t\tsuper(message ?? 'Not found');\n\t\tthis.name = 'NotFoundError';\n\t\tthis.status = 404;\n\t}\n}\n\nexport class UnauthorisedError extends ErrorWithStatus {\n\tconstructor(message?: string, status?: number) {\n\t\tsuper(message ?? 'You are not authorised to perform this action.');\n\t\tthis.name = 'UnauthorisedError';\n\t\tthis.status = status ?? 401;\n\t}\n}\n\nexport class SchemaValidationError extends ErrorWithStatus {\n\tconstructor(\n\t\tpublic issues: readonly StandardSchemaV1.Issue[],\n\t\tpublic source?: 'body' | 'searchParams' | 'response',\n\t) {\n\t\tconst sourceText = source ? ` in ${source}` : '';\n\t\tsuper(`Schema validation failed${sourceText}`);\n\t\tthis.name = 'SchemaValidationError';\n\t\tthis.status = 400;\n\t}\n}\n\nexport class ApiError extends ErrorWithStatus {\n\tconstructor(message: string, status?: number) {\n\t\tsuper(message);\n\t\tthis.name = 'ApiError';\n\t\tthis.status = status ?? 500;\n\t}\n}\n\nexport class JsonParsingError extends ErrorWithStatus {\n\tconstructor(public response?: Response) {\n\t\tsuper('Error parsing response into JSON.');\n\t\tthis.name = 'ParsingError';\n\t\tthis.status = 500;\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\nconst ERROR_MESSAGE_KEYS = ['message', 'error', 'errors', 'exception', 'exceptions'] as const;\nfunction getErrorMessageFromJson(json: unknown): string {\n\tconsole.log('json', json);\n\tconst messages: string[] = [];\n\tif (typeof json === 'object' && json !== null) {\n\t\tfor (const key of ERROR_MESSAGE_KEYS) {\n\t\t\tif (hasProp(json, key)) {\n\t\t\t\tconsole.log('hasProp', key, json[key]);\n\t\t\t\tconst value = json[key];\n\t\t\t\tif (typeof value === 'string') messages.push(value);\n\t\t\t\tif (Array.isArray(value) && value.every((item): item is string => typeof item === 'string'))\n\t\t\t\t\tmessages.push(...value);\n\t\t\t}\n\t\t}\n\t}\n\tif (messages.length === 0) messages.push('Unknown error');\n\treturn messages.join(', ');\n}\n\n/** Throws branded errors when API returns a known error. */\nexport function handleApiExceptions(json: unknown, status: number) {\n\tif (status >= 300 && status <= 500) {\n\t\tconst message = getErrorMessageFromJson(json);\n\t\tif (status === 404) {\n\t\t\tthrow new NotFoundError(message);\n\t\t}\n\t\tif (message === unauthenticatedMessage) {\n\t\t\tthrow new UnauthorisedError('You are not authenticated.', status);\n\t\t}\n\t\tif (message === unauthorisedMessage) {\n\t\t\tthrow new UnauthorisedError(message, status);\n\t\t}\n\t\tthrow new ApiError(message, status);\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, response.status);\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\nexport const SdkError = {\n\tNotFound: NotFoundError,\n\tUnauthorised: UnauthorisedError,\n\tSchemaValidation: SchemaValidationError,\n\tApi: ApiError,\n\tJsonParsing: JsonParsingError,\n};\n\nexport function isSdkError(error: unknown): error is (typeof SdkError)[keyof typeof SdkError] {\n\treturn Object.values(SdkError).some(ErrorClass => error instanceof ErrorClass);\n}\n","{\n\t\"name\": \"@inploi/sdk\",\n\t\"version\": \"2.0.1\",\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\t\"test:coverage\": \"bun test --coverage --coverage-reporter=lcov\"\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\"@inploi/talent-bank\": \"github:inploi/talent-bank#667c4d51f3bb0042131dc8f0303a6ccdafa54958\",\n\t\t\"@standard-schema/spec\": \"^1.0.0\",\n\t\t\"neoqs\": \"^6.13.0\",\n\t\t\"valibot\": \"^1.3.1\"\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 ENV_TO_TALENT_BANK_URL: Record<InploiSdkEnvironment, string> = {\n\tsandbox: 'https://talent-bank.staging.inploi.com',\n\tproduction: 'https://talent-bank.inploi.com',\n\t// @ts-expect-error - local test environment\n\t_internal_local: 'http://localhost:8787',\n};\n\nexport const ANALYTICS_VERSION = version;\n\nexport const LOG_PATHNAME = '/log';\n\nexport const ANALYTICS_COOKIE_NAME = 'isdk_session';\n\n/**\n * Local-storage key used to persist the Talent Bank `candidateId` once the\n * user has identified via the SDK. The SDK forwards this id on every\n * subsequent analytics log request so Laravel can stamp it onto the session.\n */\nexport const ANALYTICS_CANDIDATE_ID_STORAGE_KEY = `${ANALYTICS_COOKIE_NAME}-candidate_id`;\n","/**\n * Generates a RFC 4122 v4 UUID.\n *\n * `crypto.randomUUID()` is only available in secure contexts (HTTPS). This\n * utility falls back to `crypto.getRandomValues`, which is available in all\n * browsing contexts including HTTP, so the SDK works on non-HTTPS staging\n * environments.\n */\nexport const generateUUID = (): `${string}-${string}-${string}-${string}-${string}` => {\n\tif (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n\t\treturn crypto.randomUUID();\n\t}\n\n\treturn '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, c =>\n\t\t(+c ^ (crypto.getRandomValues(new Uint8Array(1))[0]! & (15 >> (+c / 4)))).toString(16),\n\t) as `${string}-${string}-${string}-${string}-${string}`;\n};\n","import type { ResponseObj } from '@inploi/core/common';\nimport { invariant } from '@inploi/core/common';\n\nimport { InploiRpcClient, Logger, endpoint, typed } from '.';\nimport {\n\tANALYTICS_CANDIDATE_ID_STORAGE_KEY,\n\tANALYTICS_COOKIE_NAME,\n\tANALYTICS_VERSION,\n} from './sdk.constants';\nimport type { TalentBankClient } from './sdk.talent-bank';\nimport { generateUUID } from './sdk.uuid';\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\nexport type 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_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\t/**\n\t * Talent Bank candidate id — set once the SDK has identified the user\n\t * (via `TalentBankClient.identify`). Laravel's session middleware reads\n\t * this and stamps it onto `session.context.candidate_id` for attribution.\n\t * `null` for anonymous / unidentified users.\n\t */\n\tcandidate_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\n/**\n * Read the cached Talent Bank candidate id from localStorage.\n *\n * Returns `null` in non-browser / no-localStorage environments so server-side\n * logging and tests don't explode.\n */\nconst getStoredCandidateId = (): string | null => {\n\tif (typeof window === 'undefined') return null;\n\ttry {\n\t\tconst stored = window.localStorage.getItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY);\n\t\treturn typeof stored === 'string' && stored !== '' ? stored : null;\n\t} catch {\n\t\treturn null;\n\t}\n};\n\nconst setStoredCandidateId = (candidateId: string | null): void => {\n\tif (typeof window === 'undefined') return;\n\ttry {\n\t\tif (candidateId) {\n\t\t\twindow.localStorage.setItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY, candidateId);\n\t\t} else {\n\t\t\twindow.localStorage.removeItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY);\n\t\t}\n\t} catch {\n\t\t// localStorage may be unavailable (Safari private mode, sandboxed\n\t\t// iframes, etc). Identification still works for the current page — we\n\t\t// just won't remember it across reloads.\n\t}\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\n/**\n * Get or create a persistent anonymous ID.\n *\n * This is the universal identifier that bridges:\n * - SDK analytics (Laravel tracking)\n * - Agent conversations (Durable Object routing)\n * - Identity resolution\n *\n * The ID is:\n * - Generated client-side if none exists\n * - Persisted in cookie for 7 days\n * - The same across all SDK plugins\n *\n * @returns The anonymous ID (existing or newly generated)\n */\nexport const getOrCreateAnonymousId = (): string => {\n\t// Server-side: cannot generate, return empty (should not happen in normal flow)\n\tif (typeof window === 'undefined') {\n\t\tthrow new Error('getOrCreateAnonymousId() can only be called in browser environment');\n\t}\n\n\t// Check existing sources first\n\tconst existing = getSessionInfo().anonymous_id;\n\tif (existing) return existing;\n\n\t// Generate new ID and immediately persist to cookie\n\tconst newId = generateUUID();\n\tdocument.cookie = formatCookie(newId);\n\treturn newId;\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\tbody: typed<TrackPayload>(),\n\t},\n});\n\nexport type AnalyticsOnEventCallback = (event: AnalyticsLogParams) => void;\n\nexport const createAnalyticsService = ({\n\trpcClient,\n\tlogger,\n\tonEvent,\n\ttalentBank,\n}: {\n\tlogger: Logger;\n\trpcClient: InploiRpcClient;\n\tonEvent?: AnalyticsOnEventCallback;\n\t/**\n\t * Optional Talent Bank client. When provided, `IDENTIFY` events are sent\n\t * directly to Talent Bank's `POST /identify` (in addition to Laravel's\n\t * `/log`), and the returned `candidateId` is cached locally and forwarded\n\t * on every subsequent log call.\n\t */\n\ttalentBank?: TalentBankClient;\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\tlet sessionInfo = getSessionInfo(params.request);\n\t\t\tif (params.event === 'IDENTIFY' && !sessionInfo.anonymous_id && !params.request && typeof window !== 'undefined') {\n\t\t\t\tsessionInfo = { ...sessionInfo, anonymous_id: getOrCreateAnonymousId() };\n\t\t\t}\n\n\t\t\t// For IDENTIFY events, resolve the Talent Bank candidate directly\n\t\t\t// from the SDK before firing the /log call. The returned candidateId\n\t\t\t// is cached so every subsequent log request includes it. Identify\n\t\t\t// is best-effort: a failure here must not prevent the analytics log.\n\t\t\tlet resolvedCandidateId = getStoredCandidateId();\n\t\t\tif (params.event === 'IDENTIFY' && talentBank && sessionInfo.anonymous_id) {\n\t\t\t\tconst identifyProperties = params.properties as EventPropertyMap['IDENTIFY']['properties'];\n\t\t\t\tconst result = await talentBank.identify({\n\t\t\t\t\temail: identifyProperties.email ?? identifyProperties.identifier,\n\t\t\t\t\tfirstName: identifyProperties.first_name,\n\t\t\t\t\tlastName: identifyProperties.last_name,\n\t\t\t\t\tphone: identifyProperties.phone_number,\n\t\t\t\t\tanonymousId: sessionInfo.anonymous_id,\n\t\t\t\t\tsource: 'sdk',\n\t\t\t\t});\n\t\t\t\tif (result?.candidateId) {\n\t\t\t\t\tresolvedCandidateId = result.candidateId;\n\t\t\t\t\tsetStoredCandidateId(result.candidateId);\n\t\t\t\t}\n\t\t\t}\n\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\tcandidate_id: resolvedCandidateId,\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\tbody: 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\tonEvent?.(payload as AnalyticsLogParams);\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\tsource?: 'body' | 'searchParams' | 'response',\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, source);\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\tsource?: 'body' | 'searchParams' | 'response',\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\t\tsource?: 'body' | 'searchParams' | 'response';\n\t } {\n\ttry {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\toutput: parse(schema, input, source),\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\tsource: e.source,\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// eslint-disable-next-line @typescript-eslint/ban-types\ntype NonReducibleUnknown = {} | null | undefined;\ntype LooseAutocomplete<T extends BaseType, BaseType> = T | BaseType;\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\tprivate _environment: InploiSdkEnvironment;\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\tthis._environment = params.environment;\n\t}\n\n\tget environment() {\n\t\treturn this._environment;\n\t}\n\n\t/** Gets params for a fetch request to the given endpoint */\n\tgetFetchParams<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}> & {\n\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the inputs against the schema.\n\t\t\t\t * If you want to skip validation (e.g.: already validated yourself or with `validateEndpontInputs`), set this to false.\n\t\t\t\t */\n\t\t\t\tvalidateIn?: boolean;\n\t\t\t}\n\t\t:\tnever,\n\t): [url: string, options: RequestInit] {\n\t\tconst validateIn = options.validateIn ?? true;\n\t\tconst { searchParams, body } = validateIn ? validateEndpointInputs(endpoint, options) : options;\n\n\t\tconst url = new URL(this.baseUrl);\n\n\t\t// Replace path parameters in pathname\n\t\tlet pathname = endpoint.pathname;\n\t\tif ('params' in options && options.params) {\n\t\t\tfor (const [key, value] of Object.entries(options.params)) {\n\t\t\t\tpathname = pathname.replace(`:${key}`, String(value));\n\t\t\t}\n\t\t}\n\t\turl.pathname = pathname;\n\n\t\tif (endpoint.schema.searchParams) {\n\t\t\turl.search = stringify(searchParams);\n\t\t}\n\n\t\treturn [\n\t\t\turl.toString(),\n\t\t\t{\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\t\t];\n\t}\n\n\t/** Parses a response against an endpoint’s response schema, considering common errors thrown from the API.\n\t * @throws {JsonParsingError} - If the response is not valid JSON.\n\t * @throws {SchemaValidationError} - If the response does not match the schema.\n\t * @throws {ApiError} - If the API responded with an error message.\n\t */\n\tasync parseResponse<T extends RpcEndpoint>(\n\t\tendpoint: T,\n\t\toptions: {\n\t\t\tresponse: Response;\n\t\t\t/**\n\t\t\t * Whether to validate the response against the schema.\n\t\t\t * This is meant more as an escape hatch for when the response is not as expected and you want to handle it separately yourself.\n\t\t\t * ⚠️ This will lead to potential type/runtime mismatch as it does not verify the response against the schema.\n\t\t\t */\n\t\t\tvalidateOut?: boolean;\n\t\t},\n\t): Promise<StandardSchemaV1.InferOutput<T['schema']['response']>> {\n\t\tconst json = await options.response.json().catch(e => {\n\t\t\tthis.logger.error(e);\n\t\t\tthrow new JsonParsingError(options.response);\n\t\t});\n\n\t\tconst validateOut = options.validateOut ?? true;\n\t\tif (!validateOut) return json as StandardSchemaV1.InferOutput<T['schema']['response']>;\n\n\t\tconst result = safeParse(endpoint.schema.response, json, 'response');\n\t\tif (!result.success) {\n\t\t\thandleApiExceptions(json, options.response.status);\n\t\t\tthrow new SchemaValidationError(result.issues, result.source);\n\t\t}\n\n\t\treturn result.output as StandardSchemaV1.InferOutput<T['schema']['response']>;\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}> & {\n\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the inputs against the schema.\n\t\t\t\t * If you want to skip validation (e.g.: already validated yourself or with `validateEndpontInputs`), set this to false.\n\t\t\t\t */\n\t\t\t\tvalidateIn?: boolean;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the response against the schema.\n\t\t\t\t * This is meant more as an escape hatch for when the response is not as expected and you want to handle it separately yourself.\n\t\t\t\t * ⚠️ This will lead to potential type/runtime mismatch as it does not verify the response against the schema.\n\t\t\t\t */\n\t\t\t\tvalidateOut?: boolean;\n\t\t\t}\n\t\t:\tnever,\n\t): Promise<StandardSchemaV1.InferOutput<T['schema']['response']>> {\n\t\ttry {\n\t\t\tconst fetchParams = this.getFetchParams(endpoint, options);\n\t\t\tconst response = await fetch(...fetchParams);\n\t\t\treturn this.parseResponse(endpoint, { response, validateOut: options.validateOut });\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 : LooseAutocomplete<T[K], NonReducibleUnknown>;\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\n/** Validates the inputs for an endpoint ahead of time\n * Useful when you need to validate and throw earlier, or use the inputs for something other than the API call.\n */\nexport function validateEndpointInputs<T extends RpcEndpoint>(\n\tendpoint: T,\n\toptions: GetSchemaValues<{ body: unknown; searchParams: unknown }>,\n) {\n\tconst validatedInputs = {\n\t\tsearchParams: undefined,\n\t\tbody: undefined,\n\t\tvalidateIn: false,\n\t} as T extends RpcEndpoint<infer _, infer __, infer ___, infer TSearch, infer TBody> ?\n\t\tGetSchemaValues<{\n\t\t\tbody: TBody;\n\t\t\tsearchParams: TSearch;\n\t\t}> & {\n\t\t\tvalidateIn: false;\n\t\t}\n\t:\tnever;\n\n\tif (endpoint.schema.searchParams) {\n\t\tvalidatedInputs.searchParams = parse(\n\t\t\tendpoint.schema.searchParams,\n\t\t\t'searchParams' in options ? options.searchParams : {},\n\t\t);\n\t}\n\n\tif (endpoint.schema.body) {\n\t\tvalidatedInputs.body = parse(endpoint.schema.body, 'body' in options ? options.body : {});\n\t}\n\n\treturn validatedInputs;\n}\n","import {\n\ttype CandidateSource,\n\ttype DuplicateCheckResult,\n\tDuplicateCheckResultSchema,\n\ttype DuplicateCheckScope,\n\ttype IdentifyInput,\n\tIdentifyInputSchema,\n\ttype IdentifyResult,\n\tIdentifyResultSchema,\n} from '@inploi/talent-bank/contract';\nimport * as v from 'valibot';\n\nimport { ENV_TO_TALENT_BANK_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger } from './sdk.logger';\n\nexport type TalentBankCheckDuplicateResult = DuplicateCheckResult;\n\nexport type TalentBankIdentifyParams = Pick<IdentifyInput, 'anonymousId' | 'email'> &\n\tPartial<Pick<IdentifyInput, 'firstName' | 'lastName' | 'phone'>> & {\n\t\t/** Caller tag — defaults to `'sdk'`. */\n\t\tsource?: CandidateSource;\n\t};\n\nexport type TalentBankIdentifyResult = IdentifyResult;\n\nexport interface TalentBankClient {\n\tcheckDuplicate(params: {\n\t\temail: string;\n\t\tjobId?: string | number;\n\t\tscope: DuplicateCheckScope;\n\t}): Promise<TalentBankCheckDuplicateResult>;\n\n\t/**\n\t * Resolve or create a Talent Bank candidate for the supplied identifier.\n\t *\n\t * This is the direct-to-Talent-Bank replacement for the old Laravel-proxied\n\t * `/log` IDENTIFY flow. The SDK calls this and then forwards the returned\n\t * `candidateId` on every subsequent analytics log so Laravel can stamp it\n\t * onto the session for attribution.\n\t *\n\t * Returns `null` if the call fails — identification is best-effort and must\n\t * never break the host page.\n\t */\n\tidentify(params: TalentBankIdentifyParams): Promise<TalentBankIdentifyResult | null>;\n}\n\nexport const createTalentBankClient = ({\n\tenvironment,\n\tpublishableKey,\n\tlogger,\n}: {\n\tenvironment: InploiSdkEnvironment;\n\tpublishableKey: string;\n\tlogger: Logger;\n}): TalentBankClient => {\n\tconst baseUrl = ENV_TO_TALENT_BANK_URL[environment];\n\n\treturn {\n\t\tasync checkDuplicate(params) {\n\t\t\ttry {\n\t\t\t\tconst searchParams = new URLSearchParams({ email: params.email, scope: params.scope });\n\t\t\t\tif (params.scope === 'job' && params.jobId != null) {\n\t\t\t\t\tsearchParams.set('job_id', String(params.jobId));\n\t\t\t\t}\n\n\t\t\t\tconst response = await fetch(`${baseUrl}/applications/check-duplicate?${searchParams}`, {\n\t\t\t\t\tmethod: 'GET',\n\t\t\t\t\theaders: { Accept: 'application/json', 'x-publishable-key': publishableKey },\n\t\t\t\t});\n\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlogger.error(`[TalentBankClient] checkDuplicate failed with status ${response.status}`);\n\t\t\t\t\treturn { isDuplicate: false };\n\t\t\t\t}\n\n\t\t\t\tconst parsed = v.safeParse(DuplicateCheckResultSchema, await response.json());\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] checkDuplicate returned an invalid response');\n\t\t\t\t\treturn { isDuplicate: false };\n\t\t\t\t}\n\n\t\t\t\treturn parsed.output;\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error('[TalentBankClient] checkDuplicate failed:', e);\n\t\t\t\treturn { isDuplicate: false };\n\t\t\t}\n\t\t},\n\n\t\tasync identify(params) {\n\t\t\ttry {\n\t\t\t\tif (!params.anonymousId) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify skipped because anonymousId is missing');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst body: IdentifyInput = {\n\t\t\t\t\temail: params.email,\n\t\t\t\t\tfirstName: params.firstName,\n\t\t\t\t\tlastName: params.lastName,\n\t\t\t\t\tphone: params.phone,\n\t\t\t\t\tanonymousId: params.anonymousId,\n\t\t\t\t\tsource: params.source ?? 'sdk',\n\t\t\t\t};\n\t\t\t\tconst parsedBody = v.safeParse(IdentifyInputSchema, body);\n\t\t\t\tif (!parsedBody.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify received invalid input');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst response = await fetch(`${baseUrl}/identify`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t\tAccept: 'application/json',\n\t\t\t\t\t\t'x-publishable-key': publishableKey,\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(parsedBody.output),\n\t\t\t\t});\n\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlogger.error(`[TalentBankClient] identify failed with status ${response.status}`);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst parsed = v.safeParse(IdentifyResultSchema, await response.json());\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify returned an invalid response');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\treturn parsed.output;\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error('[TalentBankClient] identify failed:', e);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\t};\n};\n","import { AnalyticsOnEventCallback, 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';\nimport { createTalentBankClient } from './sdk.talent-bank';\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\t/** When provided, this callback will be called with every event that is logged to the analytics service. */\n\tonEvent?: AnalyticsOnEventCallback;\n};\n\nexport function initialiseSdk({\n\tpublishableKey,\n\tenv,\n\tlogger = inploiBrandedLogger,\n\tonEvent,\n}: 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 talentBank = createTalentBankClient({ environment: env, publishableKey, logger: loggerService });\n\tconst analytics = createAnalyticsService({\n\t\trpcClient,\n\t\tlogger: loggerService,\n\t\tonEvent,\n\t\ttalentBank,\n\t});\n\n\tconst register = <P extends InploiSdkPlugin>(plugin: P): ReturnType<P> => {\n\t\treturn plugin({ logger: loggerService, apiClient, analytics, rpcClient, publishableKey, env });\n\t};\n\n\treturn { register, analytics, apiClient };\n}\n\nexport type InploiSdk = ReturnType<typeof initialiseSdk>;\n","export function ready(callback: () => void): void {\n\tif (typeof document === 'undefined') return;\n\n\tif (document.readyState === 'loading') {\n\t\tdocument.addEventListener('DOMContentLoaded', callback, { once: true });\n\t\treturn;\n\t}\n\n\tPromise.resolve().then(callback);\n}\n"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KAAM,cAAe,IAAKD,CAAe,EACnD,OAAQQ,CACT,CAAC,EACKI,EAAaC,EAAuB,CAAE,YAAaZ,EAAK,eAAAD,EAAgB,OAAQQ,CAAc,CAAC,EAC/FM,EAAYC,EAAuB,CACxC,UAAAL,EACA,OAAQF,EACR,QAAAJ,EACA,WAAAQ,CACD,CAAC,EAMD,MAAO,CAAE,SAJoCI,GACrCA,EAAO,CAAE,OAAQR,EAAe,UAAAH,EAAW,UAAAS,EAAW,UAAAJ,EAAW,eAAAV,EAAgB,IAAAC,CAAI,CAAC,EAG3E,UAAAa,EAAW,UAAAT,CAAU,CACzC,CCnDO,SAASY,GAAMC,EAA4B,CACjD,GAAI,SAAO,SAAa,KAExB,IAAI,SAAS,aAAe,UAAW,CACtC,SAAS,iBAAiB,mBAAoBA,EAAU,CAAE,KAAM,EAAK,CAAC,EACtE,MACD,CAEA,QAAQ,QAAQ,EAAE,KAAKA,CAAQ,EAChC","names":["src_exports","__export","ApiError","InploiRpcClient","NotFoundError","JsonParsingError","SchemaValidationError","SdkError","UnauthorisedError","createPlugin","createTalentBankClient","endpoint","generateUUID","getOrCreateAnonymousId","initialiseSdk","inploiBrandedLogger","isSdkError","noLogging","ready","typed","validateEndpointInputs","__toCommonJS","CONSOLE_PREFIX","CONSOLE_STYLE","inploiBrandedLogger","args","noLogging","createPlugin","pluginFn","invariant","condition","message","hasProp","data","prop","DEFAULT_FORMATTER","unauthenticatedMessage","unauthorisedMessage","ErrorWithStatus","message","status","NotFoundError","UnauthorisedError","SchemaValidationError","issues","source","sourceText","ApiError","JsonParsingError","response","ERROR_MESSAGE_KEYS","getErrorMessageFromJson","json","messages","key","hasProp","value","item","handleApiExceptions","status","message","NotFoundError","unauthenticatedMessage","UnauthorisedError","unauthorisedMessage","ApiError","createApiClient","params","defaultHeaders","pathname","options","init","response","JsonParsingError","SdkError","SchemaValidationError","isSdkError","error","ErrorClass","version","ENV_TO_API_URL","ENV_TO_TALENT_BANK_URL","ANALYTICS_VERSION","version","ANALYTICS_COOKIE_NAME","ANALYTICS_CANDIDATE_ID_STORAGE_KEY","generateUUID","c","formatCookie","value","now","ANALYTICS_COOKIE_NAME","getSessionId","searchParams","isServer","fromSearchParams","fromSessionStorage","getStoredCandidateId","stored","ANALYTICS_CANDIDATE_ID_STORAGE_KEY","setStoredCandidateId","candidateId","cookieRegex","getSessionInfo","request","href","anonymous_id","session_id","cookie","getOrCreateAnonymousId","existing","newId","generateUUID","getSessionInfoFromResponse","response","serverReferrer","referrer","analyticsLogEndpoint","typed","createAnalyticsService","rpcClient","logger","onEvent","talentBank","params","invariant","page","context","ANALYTICS_VERSION","sessionInfo","resolvedCandidateId","identifyProperties","result","payload","responseJson","newSession","e","headers","import_neoqs","parse","schema","input","source","result","SchemaValidationError","safeParse","e","InploiRpcClient","params","ENV_TO_API_URL","endpoint","options","validateIn","searchParams","body","validateEndpointInputs","url","pathname","key","value","json","JsonParsingError","handleApiExceptions","fetchParams","response","typed","validatedInputs","import_contract","v","createTalentBankClient","environment","publishableKey","logger","baseUrl","ENV_TO_TALENT_BANK_URL","params","searchParams","response","parsed","e","body","parsedBody","initialiseSdk","publishableKey","env","logger","inploiBrandedLogger","onEvent","apiClient","createApiClient","ENV_TO_API_URL","loggerService","noLogging","rpcClient","InploiRpcClient","talentBank","createTalentBankClient","analytics","createAnalyticsService","plugin","ready","callback"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/sdk.logger.ts","../src/sdk.plugins.ts","../../core/src/common/common.utils.ts","../../core/src/common/common.currency.ts","../../core/src/common/common.datetime.ts","../src/sdk.api.ts","../package.json","../src/sdk.constants.ts","../src/sdk.uuid.ts","../src/sdk.analytics.ts","../src/sdk.rpc.ts","../src/sdk.talent-bank.ts","../src/sdk.ts","../src/ready.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 {\n\tApiError,\n\tNotFoundError,\n\tJsonParsingError as ParsingError,\n\tUnauthorisedError,\n\tisSdkError,\n\tSchemaValidationError,\n\tSdkError,\n} from './sdk.api';\n\nexport { initialiseSdk } from './sdk';\nexport type { InitialiseInploiSdkParams, InploiSdk } from './sdk';\n\nexport type {\n\tAnalyticsService,\n\tAnalyticsLogEvent,\n\tAnalyticsLogParams,\n\tAnalyticsOnEventCallback,\n} from './sdk.analytics';\nexport { getOrCreateAnonymousId } from './sdk.analytics';\n\nexport { InploiRpcClient, endpoint, typed, validateEndpointInputs } from './sdk.rpc';\nexport type { RpcEndpoint } from './sdk.rpc';\n\nexport { createTalentBankClient } from './sdk.talent-bank';\nexport type {\n\tTalentBankCheckDuplicateResult,\n\tTalentBankClient,\n\tTalentBankIdentifyParams,\n\tTalentBankIdentifyResult,\n} from './sdk.talent-bank';\nexport { generateUUID } from './sdk.uuid';\nexport { ready } from './ready';\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 { InploiSdkEnvironment } from './sdk.constants';\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\t/** The publishable key used to initialise the SDK (available when registered via initialiseSdk) */\n\tpublishableKey?: string;\n\t/** The environment the SDK was initialised with — plugins can use this to select the correct service URL */\n\tenv?: InploiSdkEnvironment;\n};\n\nexport type InploiSdkPlugin = (dependencies: PluginDependencies) => any;\n\nexport const createPlugin = <T extends InploiSdkPlugin>(pluginFn: T) => pluginFn;\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\ttrailingZeroDisplay: 'stripIfInteger',\n\t});\n\tif (salary.pay_display === false) return undefined;\n\tif (salary.pay === null && salary.pay_min === null && salary.pay_max === null) 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","import { hasProp } from '@inploi/core/common';\nimport { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport const unauthenticatedMessage = 'Unauthenticated';\nexport const unauthorisedMessage = 'This action is unauthorized.';\n\nexport class ErrorWithStatus extends Error {\n\tpublic status?: number;\n\tconstructor(message?: string, status?: number) {\n\t\tsuper(message);\n\t\tthis.status = status;\n\t\tthis.name = 'ErrorWithStatus';\n\t}\n}\n\nexport class NotFoundError extends ErrorWithStatus {\n\tconstructor(message?: string) {\n\t\tsuper(message ?? 'Not found');\n\t\tthis.name = 'NotFoundError';\n\t\tthis.status = 404;\n\t}\n}\n\nexport class UnauthorisedError extends ErrorWithStatus {\n\tconstructor(message?: string, status?: number) {\n\t\tsuper(message ?? 'You are not authorised to perform this action.');\n\t\tthis.name = 'UnauthorisedError';\n\t\tthis.status = status ?? 401;\n\t}\n}\n\nexport class SchemaValidationError extends ErrorWithStatus {\n\tconstructor(\n\t\tpublic issues: readonly StandardSchemaV1.Issue[],\n\t\tpublic source?: 'body' | 'searchParams' | 'response',\n\t) {\n\t\tconst sourceText = source ? ` in ${source}` : '';\n\t\tsuper(`Schema validation failed${sourceText}`);\n\t\tthis.name = 'SchemaValidationError';\n\t\tthis.status = 400;\n\t}\n}\n\nexport class ApiError extends ErrorWithStatus {\n\tconstructor(message: string, status?: number) {\n\t\tsuper(message);\n\t\tthis.name = 'ApiError';\n\t\tthis.status = status ?? 500;\n\t}\n}\n\nexport class JsonParsingError extends ErrorWithStatus {\n\tconstructor(public response?: Response) {\n\t\tsuper('Error parsing response into JSON.');\n\t\tthis.name = 'ParsingError';\n\t\tthis.status = 500;\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\nconst ERROR_MESSAGE_KEYS = ['message', 'error', 'errors', 'exception', 'exceptions'] as const;\nfunction getErrorMessageFromJson(json: unknown): string {\n\tconsole.log('json', json);\n\tconst messages: string[] = [];\n\tif (typeof json === 'object' && json !== null) {\n\t\tfor (const key of ERROR_MESSAGE_KEYS) {\n\t\t\tif (hasProp(json, key)) {\n\t\t\t\tconsole.log('hasProp', key, json[key]);\n\t\t\t\tconst value = json[key];\n\t\t\t\tif (typeof value === 'string') messages.push(value);\n\t\t\t\tif (Array.isArray(value) && value.every((item): item is string => typeof item === 'string'))\n\t\t\t\t\tmessages.push(...value);\n\t\t\t}\n\t\t}\n\t}\n\tif (messages.length === 0) messages.push('Unknown error');\n\treturn messages.join(', ');\n}\n\n/** Throws branded errors when API returns a known error. */\nexport function handleApiExceptions(json: unknown, status: number) {\n\tif (status >= 300 && status <= 500) {\n\t\tconst message = getErrorMessageFromJson(json);\n\t\tif (status === 404) {\n\t\t\tthrow new NotFoundError(message);\n\t\t}\n\t\tif (message === unauthenticatedMessage) {\n\t\t\tthrow new UnauthorisedError('You are not authenticated.', status);\n\t\t}\n\t\tif (message === unauthorisedMessage) {\n\t\t\tthrow new UnauthorisedError(message, status);\n\t\t}\n\t\tthrow new ApiError(message, status);\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, response.status);\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\nexport const SdkError = {\n\tNotFound: NotFoundError,\n\tUnauthorised: UnauthorisedError,\n\tSchemaValidation: SchemaValidationError,\n\tApi: ApiError,\n\tJsonParsing: JsonParsingError,\n};\n\nexport function isSdkError(error: unknown): error is (typeof SdkError)[keyof typeof SdkError] {\n\treturn Object.values(SdkError).some(ErrorClass => error instanceof ErrorClass);\n}\n","{\n\t\"name\": \"@inploi/sdk\",\n\t\"version\": \"2.0.2\",\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\t\"test:coverage\": \"bun test --coverage --coverage-reporter=lcov\"\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\"@inploi/talent-bank\": \"github:inploi/talent-bank#a5826c57a235acedd6af2209b2ea25dc414a8cfa\",\n\t\t\"@standard-schema/spec\": \"^1.0.0\",\n\t\t\"neoqs\": \"^6.13.0\",\n\t\t\"valibot\": \"^1.3.1\"\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 ENV_TO_TALENT_BANK_URL: Record<InploiSdkEnvironment, string> = {\n\tsandbox: 'https://talent-bank.staging.inploi.com',\n\tproduction: 'https://talent-bank.inploi.com',\n\t// @ts-expect-error - local test environment\n\t_internal_local: 'http://localhost:8787',\n};\n\nexport const ANALYTICS_VERSION = version;\n\nexport const LOG_PATHNAME = '/log';\n\nexport const ANALYTICS_COOKIE_NAME = 'isdk_session';\n\n/**\n * Local-storage key used to persist the Talent Bank `candidateId` once the\n * user has identified via the SDK. The SDK forwards this id on every\n * subsequent analytics log request so Laravel can stamp it onto the session.\n */\nexport const ANALYTICS_CANDIDATE_ID_STORAGE_KEY = `${ANALYTICS_COOKIE_NAME}-candidate_id`;\n","/**\n * Generates a RFC 4122 v4 UUID.\n *\n * `crypto.randomUUID()` is only available in secure contexts (HTTPS). This\n * utility falls back to `crypto.getRandomValues`, which is available in all\n * browsing contexts including HTTP, so the SDK works on non-HTTPS staging\n * environments.\n */\nexport const generateUUID = (): `${string}-${string}-${string}-${string}-${string}` => {\n\tif (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n\t\treturn crypto.randomUUID();\n\t}\n\n\treturn '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, c =>\n\t\t(+c ^ (crypto.getRandomValues(new Uint8Array(1))[0]! & (15 >> (+c / 4)))).toString(16),\n\t) as `${string}-${string}-${string}-${string}-${string}`;\n};\n","import type { ResponseObj } from '@inploi/core/common';\nimport { invariant } from '@inploi/core/common';\n\nimport { InploiRpcClient, Logger, endpoint, typed } from '.';\nimport {\n\tANALYTICS_CANDIDATE_ID_STORAGE_KEY,\n\tANALYTICS_COOKIE_NAME,\n\tANALYTICS_VERSION,\n} from './sdk.constants';\nimport type { TalentBankClient } from './sdk.talent-bank';\nimport { generateUUID } from './sdk.uuid';\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\nexport type 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_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\t/**\n\t * Talent Bank candidate id — set once the SDK has identified the user\n\t * (via `TalentBankClient.identify`). Laravel's session middleware reads\n\t * this and stamps it onto `session.context.candidate_id` for attribution.\n\t * `null` for anonymous / unidentified users.\n\t */\n\tcandidate_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\n/**\n * Read the cached Talent Bank candidate id from localStorage.\n *\n * Returns `null` in non-browser / no-localStorage environments so server-side\n * logging and tests don't explode.\n */\nconst getStoredCandidateId = (): string | null => {\n\tif (typeof window === 'undefined') return null;\n\ttry {\n\t\tconst stored = window.localStorage.getItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY);\n\t\treturn typeof stored === 'string' && stored !== '' ? stored : null;\n\t} catch {\n\t\treturn null;\n\t}\n};\n\nconst setStoredCandidateId = (candidateId: string | null): void => {\n\tif (typeof window === 'undefined') return;\n\ttry {\n\t\tif (candidateId) {\n\t\t\twindow.localStorage.setItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY, candidateId);\n\t\t} else {\n\t\t\twindow.localStorage.removeItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY);\n\t\t}\n\t} catch {\n\t\t// localStorage may be unavailable (Safari private mode, sandboxed\n\t\t// iframes, etc). Identification still works for the current page — we\n\t\t// just won't remember it across reloads.\n\t}\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\n/**\n * Get or create a persistent anonymous ID.\n *\n * This is the universal identifier that bridges:\n * - SDK analytics (Laravel tracking)\n * - Agent conversations (Durable Object routing)\n * - Identity resolution\n *\n * The ID is:\n * - Generated client-side if none exists\n * - Persisted in cookie for 7 days\n * - The same across all SDK plugins\n *\n * @returns The anonymous ID (existing or newly generated)\n */\nexport const getOrCreateAnonymousId = (): string => {\n\t// Server-side: cannot generate, return empty (should not happen in normal flow)\n\tif (typeof window === 'undefined') {\n\t\tthrow new Error('getOrCreateAnonymousId() can only be called in browser environment');\n\t}\n\n\t// Check existing sources first\n\tconst existing = getSessionInfo().anonymous_id;\n\tif (existing) return existing;\n\n\t// Generate new ID and immediately persist to cookie\n\tconst newId = generateUUID();\n\tdocument.cookie = formatCookie(newId);\n\treturn newId;\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\tbody: typed<TrackPayload>(),\n\t},\n});\n\nexport type AnalyticsOnEventCallback = (event: AnalyticsLogParams) => void;\n\nexport const createAnalyticsService = ({\n\trpcClient,\n\tlogger,\n\tonEvent,\n\ttalentBank,\n}: {\n\tlogger: Logger;\n\trpcClient: InploiRpcClient;\n\tonEvent?: AnalyticsOnEventCallback;\n\t/**\n\t * Optional Talent Bank client. When provided, `IDENTIFY` events are sent\n\t * directly to Talent Bank's `POST /identify` (in addition to Laravel's\n\t * `/log`), and the returned `candidateId` is cached locally and forwarded\n\t * on every subsequent log call.\n\t */\n\ttalentBank?: TalentBankClient;\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\tlet sessionInfo = getSessionInfo(params.request);\n\t\t\tif (params.event === 'IDENTIFY' && !sessionInfo.anonymous_id && !params.request && typeof window !== 'undefined') {\n\t\t\t\tsessionInfo = { ...sessionInfo, anonymous_id: getOrCreateAnonymousId() };\n\t\t\t}\n\n\t\t\t// For IDENTIFY events, resolve the Talent Bank candidate directly\n\t\t\t// from the SDK before firing the /log call. The returned candidateId\n\t\t\t// is cached so every subsequent log request includes it. Identify\n\t\t\t// is best-effort: a failure here must not prevent the analytics log.\n\t\t\tlet resolvedCandidateId = getStoredCandidateId();\n\t\t\tif (params.event === 'IDENTIFY' && talentBank && sessionInfo.anonymous_id) {\n\t\t\t\tconst identifyProperties = params.properties as EventPropertyMap['IDENTIFY']['properties'];\n\t\t\t\tconst result = await talentBank.identify({\n\t\t\t\t\temail: identifyProperties.email ?? identifyProperties.identifier,\n\t\t\t\t\tfirstName: identifyProperties.first_name,\n\t\t\t\t\tlastName: identifyProperties.last_name,\n\t\t\t\t\tphone: identifyProperties.phone_number,\n\t\t\t\t\tanonymousId: sessionInfo.anonymous_id,\n\t\t\t\t\tsource: 'sdk',\n\t\t\t\t});\n\t\t\t\tif (result?.candidateId) {\n\t\t\t\t\tresolvedCandidateId = result.candidateId;\n\t\t\t\t\tsetStoredCandidateId(result.candidateId);\n\t\t\t\t}\n\t\t\t}\n\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\tcandidate_id: resolvedCandidateId,\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\tbody: 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\tonEvent?.(payload as AnalyticsLogParams);\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\tsource?: 'body' | 'searchParams' | 'response',\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, source);\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\tsource?: 'body' | 'searchParams' | 'response',\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\t\tsource?: 'body' | 'searchParams' | 'response';\n\t } {\n\ttry {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\toutput: parse(schema, input, source),\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\tsource: e.source,\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// eslint-disable-next-line @typescript-eslint/ban-types\ntype NonReducibleUnknown = {} | null | undefined;\ntype LooseAutocomplete<T extends BaseType, BaseType> = T | BaseType;\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\tprivate _environment: InploiSdkEnvironment;\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\tthis._environment = params.environment;\n\t}\n\n\tget environment() {\n\t\treturn this._environment;\n\t}\n\n\t/** Gets params for a fetch request to the given endpoint */\n\tgetFetchParams<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}> & {\n\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the inputs against the schema.\n\t\t\t\t * If you want to skip validation (e.g.: already validated yourself or with `validateEndpontInputs`), set this to false.\n\t\t\t\t */\n\t\t\t\tvalidateIn?: boolean;\n\t\t\t}\n\t\t:\tnever,\n\t): [url: string, options: RequestInit] {\n\t\tconst validateIn = options.validateIn ?? true;\n\t\tconst { searchParams, body } = validateIn ? validateEndpointInputs(endpoint, options) : options;\n\n\t\tconst url = new URL(this.baseUrl);\n\n\t\t// Replace path parameters in pathname\n\t\tlet pathname = endpoint.pathname;\n\t\tif ('params' in options && options.params) {\n\t\t\tfor (const [key, value] of Object.entries(options.params)) {\n\t\t\t\tpathname = pathname.replace(`:${key}`, String(value));\n\t\t\t}\n\t\t}\n\t\turl.pathname = pathname;\n\n\t\tif (endpoint.schema.searchParams) {\n\t\t\turl.search = stringify(searchParams);\n\t\t}\n\n\t\treturn [\n\t\t\turl.toString(),\n\t\t\t{\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\t\t];\n\t}\n\n\t/** Parses a response against an endpoint’s response schema, considering common errors thrown from the API.\n\t * @throws {JsonParsingError} - If the response is not valid JSON.\n\t * @throws {SchemaValidationError} - If the response does not match the schema.\n\t * @throws {ApiError} - If the API responded with an error message.\n\t */\n\tasync parseResponse<T extends RpcEndpoint>(\n\t\tendpoint: T,\n\t\toptions: {\n\t\t\tresponse: Response;\n\t\t\t/**\n\t\t\t * Whether to validate the response against the schema.\n\t\t\t * This is meant more as an escape hatch for when the response is not as expected and you want to handle it separately yourself.\n\t\t\t * ⚠️ This will lead to potential type/runtime mismatch as it does not verify the response against the schema.\n\t\t\t */\n\t\t\tvalidateOut?: boolean;\n\t\t},\n\t): Promise<StandardSchemaV1.InferOutput<T['schema']['response']>> {\n\t\tconst json = await options.response.json().catch(e => {\n\t\t\tthis.logger.error(e);\n\t\t\tthrow new JsonParsingError(options.response);\n\t\t});\n\n\t\tconst validateOut = options.validateOut ?? true;\n\t\tif (!validateOut) return json as StandardSchemaV1.InferOutput<T['schema']['response']>;\n\n\t\tconst result = safeParse(endpoint.schema.response, json, 'response');\n\t\tif (!result.success) {\n\t\t\thandleApiExceptions(json, options.response.status);\n\t\t\tthrow new SchemaValidationError(result.issues, result.source);\n\t\t}\n\n\t\treturn result.output as StandardSchemaV1.InferOutput<T['schema']['response']>;\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}> & {\n\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the inputs against the schema.\n\t\t\t\t * If you want to skip validation (e.g.: already validated yourself or with `validateEndpontInputs`), set this to false.\n\t\t\t\t */\n\t\t\t\tvalidateIn?: boolean;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the response against the schema.\n\t\t\t\t * This is meant more as an escape hatch for when the response is not as expected and you want to handle it separately yourself.\n\t\t\t\t * ⚠️ This will lead to potential type/runtime mismatch as it does not verify the response against the schema.\n\t\t\t\t */\n\t\t\t\tvalidateOut?: boolean;\n\t\t\t}\n\t\t:\tnever,\n\t): Promise<StandardSchemaV1.InferOutput<T['schema']['response']>> {\n\t\ttry {\n\t\t\tconst fetchParams = this.getFetchParams(endpoint, options);\n\t\t\tconst response = await fetch(...fetchParams);\n\t\t\treturn this.parseResponse(endpoint, { response, validateOut: options.validateOut });\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 : LooseAutocomplete<T[K], NonReducibleUnknown>;\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\n/** Validates the inputs for an endpoint ahead of time\n * Useful when you need to validate and throw earlier, or use the inputs for something other than the API call.\n */\nexport function validateEndpointInputs<T extends RpcEndpoint>(\n\tendpoint: T,\n\toptions: GetSchemaValues<{ body: unknown; searchParams: unknown }>,\n) {\n\tconst validatedInputs = {\n\t\tsearchParams: undefined,\n\t\tbody: undefined,\n\t\tvalidateIn: false,\n\t} as T extends RpcEndpoint<infer _, infer __, infer ___, infer TSearch, infer TBody> ?\n\t\tGetSchemaValues<{\n\t\t\tbody: TBody;\n\t\t\tsearchParams: TSearch;\n\t\t}> & {\n\t\t\tvalidateIn: false;\n\t\t}\n\t:\tnever;\n\n\tif (endpoint.schema.searchParams) {\n\t\tvalidatedInputs.searchParams = parse(\n\t\t\tendpoint.schema.searchParams,\n\t\t\t'searchParams' in options ? options.searchParams : {},\n\t\t);\n\t}\n\n\tif (endpoint.schema.body) {\n\t\tvalidatedInputs.body = parse(endpoint.schema.body, 'body' in options ? options.body : {});\n\t}\n\n\treturn validatedInputs;\n}\n","import {\n\ttype CandidateSource,\n\ttype DuplicateCheckResult,\n\tDuplicateCheckResultSchema,\n\ttype DuplicateCheckScope,\n\ttype IdentifyInput,\n\tIdentifyInputSchema,\n\ttype IdentifyResult,\n\tIdentifyResultSchema,\n} from '@inploi/talent-bank/contract';\nimport * as v from 'valibot';\n\nimport { ENV_TO_TALENT_BANK_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger } from './sdk.logger';\n\nexport type TalentBankCheckDuplicateResult = DuplicateCheckResult;\n\nexport type TalentBankIdentifyParams = Pick<IdentifyInput, 'anonymousId' | 'email'> &\n\tPartial<Pick<IdentifyInput, 'firstName' | 'lastName' | 'phone'>> & {\n\t\t/** Caller tag — defaults to `'sdk'`. */\n\t\tsource?: CandidateSource;\n\t};\n\nexport type TalentBankIdentifyResult = IdentifyResult;\n\nexport interface TalentBankClient {\n\tcheckDuplicate(params: {\n\t\temail: string;\n\t\tjobId?: string | number;\n\t\tscope: DuplicateCheckScope;\n\t}): Promise<TalentBankCheckDuplicateResult>;\n\n\t/**\n\t * Resolve or create a Talent Bank candidate for the supplied identifier.\n\t *\n\t * This is the direct-to-Talent-Bank replacement for the old Laravel-proxied\n\t * `/log` IDENTIFY flow. The SDK calls this and then forwards the returned\n\t * `candidateId` on every subsequent analytics log so Laravel can stamp it\n\t * onto the session for attribution.\n\t *\n\t * Returns `null` if the call fails — identification is best-effort and must\n\t * never break the host page.\n\t */\n\tidentify(params: TalentBankIdentifyParams): Promise<TalentBankIdentifyResult | null>;\n}\n\nexport const createTalentBankClient = ({\n\tenvironment,\n\tpublishableKey,\n\tlogger,\n}: {\n\tenvironment: InploiSdkEnvironment;\n\tpublishableKey: string;\n\tlogger: Logger;\n}): TalentBankClient => {\n\tconst baseUrl = ENV_TO_TALENT_BANK_URL[environment];\n\n\treturn {\n\t\tasync checkDuplicate(params) {\n\t\t\ttry {\n\t\t\t\tconst searchParams = new URLSearchParams({ email: params.email, scope: params.scope });\n\t\t\t\tif (params.scope === 'job' && params.jobId != null) {\n\t\t\t\t\tsearchParams.set('job_id', String(params.jobId));\n\t\t\t\t}\n\n\t\t\t\tconst response = await fetch(`${baseUrl}/applications/check-duplicate?${searchParams}`, {\n\t\t\t\t\tmethod: 'GET',\n\t\t\t\t\theaders: { Accept: 'application/json', 'x-publishable-key': publishableKey },\n\t\t\t\t});\n\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlogger.error(`[TalentBankClient] checkDuplicate failed with status ${response.status}`);\n\t\t\t\t\treturn { isDuplicate: false };\n\t\t\t\t}\n\n\t\t\t\tconst parsed = v.safeParse(DuplicateCheckResultSchema, await response.json());\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] checkDuplicate returned an invalid response');\n\t\t\t\t\treturn { isDuplicate: false };\n\t\t\t\t}\n\n\t\t\t\treturn parsed.output;\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error('[TalentBankClient] checkDuplicate failed:', e);\n\t\t\t\treturn { isDuplicate: false };\n\t\t\t}\n\t\t},\n\n\t\tasync identify(params) {\n\t\t\ttry {\n\t\t\t\tif (!params.anonymousId) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify skipped because anonymousId is missing');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst body: IdentifyInput = {\n\t\t\t\t\temail: params.email,\n\t\t\t\t\tfirstName: params.firstName,\n\t\t\t\t\tlastName: params.lastName,\n\t\t\t\t\tphone: params.phone,\n\t\t\t\t\tanonymousId: params.anonymousId,\n\t\t\t\t\tsource: params.source ?? 'sdk',\n\t\t\t\t};\n\t\t\t\tconst parsedBody = v.safeParse(IdentifyInputSchema, body);\n\t\t\t\tif (!parsedBody.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify received invalid input');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst response = await fetch(`${baseUrl}/identify`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t\tAccept: 'application/json',\n\t\t\t\t\t\t'x-publishable-key': publishableKey,\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(parsedBody.output),\n\t\t\t\t});\n\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlogger.error(`[TalentBankClient] identify failed with status ${response.status}`);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst parsed = v.safeParse(IdentifyResultSchema, await response.json());\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify returned an invalid response');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\treturn parsed.output;\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error('[TalentBankClient] identify failed:', e);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\t};\n};\n","import { AnalyticsOnEventCallback, 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';\nimport { createTalentBankClient } from './sdk.talent-bank';\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\t/** When provided, this callback will be called with every event that is logged to the analytics service. */\n\tonEvent?: AnalyticsOnEventCallback;\n};\n\nexport function initialiseSdk({\n\tpublishableKey,\n\tenv,\n\tlogger = inploiBrandedLogger,\n\tonEvent,\n}: 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 talentBank = createTalentBankClient({ environment: env, publishableKey, logger: loggerService });\n\tconst analytics = createAnalyticsService({\n\t\trpcClient,\n\t\tlogger: loggerService,\n\t\tonEvent,\n\t\ttalentBank,\n\t});\n\n\tconst register = <P extends InploiSdkPlugin>(plugin: P): ReturnType<P> => {\n\t\treturn plugin({ logger: loggerService, apiClient, analytics, rpcClient, publishableKey, env });\n\t};\n\n\treturn { register, analytics, apiClient };\n}\n\nexport type InploiSdk = ReturnType<typeof initialiseSdk>;\n","export function ready(callback: () => void): void {\n\tif (typeof document === 'undefined') return;\n\n\tif (document.readyState === 'loading') {\n\t\tdocument.addEventListener('DOMContentLoaded', callback, { once: true });\n\t\treturn;\n\t}\n\n\tPromise.resolve().then(callback);\n}\n"],"mappings":"ukBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,cAAAE,EAAA,oBAAAC,EAAA,kBAAAC,EAAA,iBAAAC,EAAA,0BAAAC,EAAA,aAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,2BAAAC,EAAA,aAAAC,EAAA,iBAAAC,EAAA,2BAAAC,EAAA,kBAAAC,EAAA,wBAAAC,EAAA,eAAAC,EAAA,cAAAC,EAAA,UAAAC,GAAA,UAAAC,EAAA,2BAAAC,IAAA,eAAAC,GAAArB,ICAO,IAAMsB,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,ECW3G,IAAMC,EAA2CC,GAAgBA,ECzBjE,SAASC,EAAUC,EAAgBC,EAAqC,CAC9E,GAAI,CAAAD,EAIJ,MAAM,IAAI,MAAMC,CAAO,CACxB,CA2BO,SAASC,EAA+BC,EAAcC,EAAqC,CACjG,OAAOA,KAAQD,CAChB,CE9BA,IAAME,GAAoB,IAAI,KAAK,mBAAmB,OAAW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,eAAAC,EACA,IAAAC,EACA,OAAAC,EAASC,EACT,QAAAC,CACD,EAA8B,CAE7B,IAAMC,EAAYC,EAAgB,CAAE,QAASC,EAAeN,CAAG,EAAG,eAAAD,CAAe,CAAC,EAC5EQ,EAAgBN,IAAW,GAAQO,EAAYP,EAC/CQ,EAAY,IAAIC,EAAgB,CACrC,YAAaV,EACb,OAAQ,CAAE,KAAM,cAAe,IAAKD,CAAe,EACnD,OAAQQ,CACT,CAAC,EACKI,EAAaC,EAAuB,CAAE,YAAaZ,EAAK,eAAAD,EAAgB,OAAQQ,CAAc,CAAC,EAC/FM,EAAYC,EAAuB,CACxC,UAAAL,EACA,OAAQF,EACR,QAAAJ,EACA,WAAAQ,CACD,CAAC,EAMD,MAAO,CAAE,SAJoCI,GACrCA,EAAO,CAAE,OAAQR,EAAe,UAAAH,EAAW,UAAAS,EAAW,UAAAJ,EAAW,eAAAV,EAAgB,IAAAC,CAAI,CAAC,EAG3E,UAAAa,EAAW,UAAAT,CAAU,CACzC,CCnDO,SAASY,GAAMC,EAA4B,CACjD,GAAI,SAAO,SAAa,KAExB,IAAI,SAAS,aAAe,UAAW,CACtC,SAAS,iBAAiB,mBAAoBA,EAAU,CAAE,KAAM,EAAK,CAAC,EACtE,MACD,CAEA,QAAQ,QAAQ,EAAE,KAAKA,CAAQ,EAChC","names":["src_exports","__export","ApiError","InploiRpcClient","NotFoundError","JsonParsingError","SchemaValidationError","SdkError","UnauthorisedError","createPlugin","createTalentBankClient","endpoint","generateUUID","getOrCreateAnonymousId","initialiseSdk","inploiBrandedLogger","isSdkError","noLogging","ready","typed","validateEndpointInputs","__toCommonJS","CONSOLE_PREFIX","CONSOLE_STYLE","inploiBrandedLogger","args","noLogging","createPlugin","pluginFn","invariant","condition","message","hasProp","data","prop","DEFAULT_FORMATTER","unauthenticatedMessage","unauthorisedMessage","ErrorWithStatus","message","status","NotFoundError","UnauthorisedError","SchemaValidationError","issues","source","sourceText","ApiError","JsonParsingError","response","ERROR_MESSAGE_KEYS","getErrorMessageFromJson","json","messages","key","hasProp","value","item","handleApiExceptions","status","message","NotFoundError","unauthenticatedMessage","UnauthorisedError","unauthorisedMessage","ApiError","createApiClient","params","defaultHeaders","pathname","options","init","response","JsonParsingError","SdkError","SchemaValidationError","isSdkError","error","ErrorClass","version","ENV_TO_API_URL","ENV_TO_TALENT_BANK_URL","ANALYTICS_VERSION","version","ANALYTICS_COOKIE_NAME","ANALYTICS_CANDIDATE_ID_STORAGE_KEY","generateUUID","c","formatCookie","value","now","ANALYTICS_COOKIE_NAME","getSessionId","searchParams","isServer","fromSearchParams","fromSessionStorage","getStoredCandidateId","stored","ANALYTICS_CANDIDATE_ID_STORAGE_KEY","setStoredCandidateId","candidateId","cookieRegex","getSessionInfo","request","href","anonymous_id","session_id","cookie","getOrCreateAnonymousId","existing","newId","generateUUID","getSessionInfoFromResponse","response","serverReferrer","referrer","analyticsLogEndpoint","typed","createAnalyticsService","rpcClient","logger","onEvent","talentBank","params","invariant","page","context","ANALYTICS_VERSION","sessionInfo","resolvedCandidateId","identifyProperties","result","payload","responseJson","newSession","e","headers","import_neoqs","parse","schema","input","source","result","SchemaValidationError","safeParse","e","InploiRpcClient","params","ENV_TO_API_URL","endpoint","options","validateIn","searchParams","body","validateEndpointInputs","url","pathname","key","value","json","JsonParsingError","handleApiExceptions","fetchParams","response","typed","validatedInputs","import_contract","v","createTalentBankClient","environment","publishableKey","logger","baseUrl","ENV_TO_TALENT_BANK_URL","params","searchParams","response","parsed","e","body","parsedBody","initialiseSdk","publishableKey","env","logger","inploiBrandedLogger","onEvent","apiClient","createApiClient","ENV_TO_API_URL","loggerService","noLogging","rpcClient","InploiRpcClient","talentBank","createTalentBankClient","analytics","createAnalyticsService","plugin","ready","callback"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var _="%c[inploi SDK]",P="color: #65BC67; font-weight: bold;",w={warn:(...e)=>console.warn(_,P,...e),error:(...e)=>console.error(_,P,...e),info:(...e)=>console.info(_,P,...e),log:(...e)=>console.log(_,P,...e)},R={info:()=>{},error:()=>{},log:()=>{},warn:()=>{}};var G=e=>e;function A(e,t){if(!e)throw new Error(t)}function C(e,t){return t in e}var Ie=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});var W="Unauthenticated",z="This action is unauthorized.",l=class extends Error{constructor(n,r){super(n);this.status=r,this.name="ErrorWithStatus"}},m=class extends l{constructor(t){super(t??"Not found"),this.name="NotFoundError",this.status=404}},f=class extends l{constructor(t,n){super(t??"You are not authorised to perform this action."),this.name="UnauthorisedError",this.status=n??401}},d=class extends l{constructor(n,r){let s=r?` in ${r}`:"";super(`Schema validation failed${s}`);this.issues=n;this.source=r;this.name="SchemaValidationError",this.status=400}},T=class extends l{constructor(t,n){super(t),this.name="ApiError",this.status=n??500}},u=class extends l{constructor(n){super("Error parsing response into JSON.");this.response=n;this.name="ParsingError",this.status=500}};var X=["message","error","errors","exception","exceptions"];function Z(e){console.log("json",e);let t=[];if(typeof e=="object"&&e!==null){for(let n of X)if(C(e,n)){console.log("hasProp",n,e[n]);let r=e[n];typeof r=="string"&&t.push(r),Array.isArray(r)&&r.every(s=>typeof s=="string")&&t.push(...r)}}return t.length===0&&t.push("Unknown error"),t.join(", ")}function L(e,t){if(t>=300&&t<=500){let n=Z(e);throw t===404?new m(n):n===W?new f("You are not authenticated.",t):n===z?new f(n,t):new T(n,t)}}var U=e=>{let t={Accept:"application/json","Content-Type":"application/json","x-publishable-key":e.publishableKey};return{fetch:async(n,r={})=>{let s={...r,headers:{...r.headers,...t}},o=await fetch(`${e.baseUrl}${n}`,s);if(o.status===404)throw new m;let i=await o.json().catch(async()=>{throw new u(o)});return L(i,o.status),i}}},M={NotFound:m,Unauthorised:f,SchemaValidation:d,Api:T,JsonParsing:u};function Q(e){return Object.values(M).some(t=>e instanceof t)}var $="2.0.1";var I={sandbox:"https://api.staging.inploi.com",production:"https://api.inploi.com",_internal_local:"http://api.test"},j={sandbox:"https://talent-bank.staging.inploi.com",production:"https://talent-bank.inploi.com",_internal_local:"http://localhost:8787"},F=$;var y="isdk_session",x=`${y}-candidate_id`;var O=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+e/4).toString(16));var N=e=>{let t=new Date;return t.setTime(t.getTime()+7*24*60*60*1e3),`${y}=${e};expires=${t.toUTCString()};path=/`},te=(e,t)=>{let n=e.get("session_id");if(t||n)return n;let r=sessionStorage.getItem(`${y}-session_id`);return typeof r=="string"?r:null},ne=()=>{if(typeof window>"u")return null;try{let e=window.localStorage.getItem(x);return typeof e=="string"&&e!==""?e:null}catch{return null}},re=e=>{if(!(typeof window>"u"))try{e?window.localStorage.setItem(x,e):window.localStorage.removeItem(x)}catch{}},oe=new RegExp(`${y}=([^;]+)`),B=e=>{let t=e?e.url:location.href,{searchParams:n}=new URL(t),r=n.get("anonymous_id"),s=te(n,typeof window>"u");if(r)return{anonymous_id:r,session_id:s};let o=e?e.headers.get("cookie"):document.cookie;return o?{anonymous_id:oe.exec(o)?.[1]??null,session_id:s}:{anonymous_id:r,session_id:s}},q=()=>{if(typeof window>"u")throw new Error("getOrCreateAnonymousId() can only be called in browser environment");let e=B().anonymous_id;if(e)return e;let t=O();return document.cookie=N(t),t},se=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},ie=e=>e==="about:client"?"":e,ae={pathname:"/log",method:"POST",schema:{response:k(),body:k()}},K=({rpcClient:e,logger:t,onEvent:n,talentBank:r})=>({log:async o=>{A(o.request||typeof window<"u","Cannot log on the server without a request. Please pass a request to `log`.");let i="request"in o&&o.request?{href:o.request.url,referrer:ie(o.request.referrer),title:""}:{href:location.href,referrer:document.referrer,title:document.title};try{let a={library:{name:"inploi-sdk",version:F},page:i},p=B(o.request);o.event==="IDENTIFY"&&!p.anonymous_id&&!o.request&&typeof window<"u"&&(p={...p,anonymous_id:q()});let g=ne();if(o.event==="IDENTIFY"&&r&&p.anonymous_id){let h=o.properties,E=await r.identify({email:h.email??h.identifier,firstName:h.first_name,lastName:h.last_name,phone:h.phone_number,anonymousId:p.anonymous_id,source:"sdk"});E?.candidateId&&(g=E.candidateId,re(E.candidateId))}let c={anonymous_id:p.anonymous_id,session_id:p.session_id,candidate_id:g,event:o.event,sent_at:new Date().toISOString(),context:a,properties:o.properties,custom_properties:o.customProperties},J=await e.request(ae,{body:c}),S=se(J);return S?.anonymous_id&&(c.anonymous_id=S.anonymous_id),S?.session_id&&(c.session_id=S.session_id),typeof window<"u"&&c.anonymous_id&&(c.session_id&&sessionStorage.setItem(`${y}-session_id`,c.session_id.toString()),document.cookie=N(c.anonymous_id)),n?.(c),{success:!0,data:c}}catch(a){return t.error("Failed to send log to API. Inspect error response of `log` for more information."),{success:!1,error:a}}},getHeaders:o=>{let i=new Headers;return o?.anonymous_id&&i.append("Set-Cookie",N(o.anonymous_id)),i},getSessionInfo:B});import{stringify as pe}from"neoqs";function D(e,t,n){let r=e["~standard"].validate(t);if(r instanceof Promise)throw new TypeError("Async schema");if(r.issues)throw new d(r.issues,n);return r.value}function ce(e,t,n){try{return{success:!0,output:D(e,t,n)}}catch(r){if(r instanceof d)return{success:!1,issues:r.issues,source:r.source};throw r}}var v=class{constructor(t){if(this.baseUrl=I[t.environment],this.headers=new Headers({"Content-Type":"application/json",Accept:"application/json"}),t.apiKey.type==="secret"){if(typeof window<"u")throw new Error("Secret key cannot be used in a browser environment");this.headers.set("x-secret-key",t.apiKey.key)}else this.headers.set("x-publishable-key",t.apiKey.key);this.logger=t.logger,this._environment=t.environment}get environment(){return this._environment}getFetchParams(t,n){let r=n.validateIn??!0,{searchParams:s,body:o}=r?H(t,n):n,i=new URL(this.baseUrl),a=t.pathname;if("params"in n&&n.params)for(let[p,g]of Object.entries(n.params))a=a.replace(`:${p}`,String(g));return i.pathname=a,t.schema.searchParams&&(i.search=pe(s)),[i.toString(),{method:t.method,body:o?JSON.stringify(o):void 0,headers:this.headers,signal:n.signal}]}async parseResponse(t,n){let r=await n.response.json().catch(i=>{throw this.logger.error(i),new u(n.response)});if(!(n.validateOut??!0))return r;let o=ce(t.schema.response,r,"response");if(!o.success)throw L(r,n.response.status),new d(o.issues,o.source);return o.output}async request(t,n){try{let r=this.getFetchParams(t,n),s=await fetch(...r);return this.parseResponse(t,{response:s,validateOut:n.validateOut})}catch(r){throw r instanceof d?this.logger.error(r.message,r.issues):this.logger.error(r),r}}};function k(){return{"~standard":{vendor:"inploi",version:1,validate:e=>({value:e})}}}function Y(e){return e}function H(e,t){let n={searchParams:void 0,body:void 0,validateIn:!1};return e.schema.searchParams&&(n.searchParams=D(e.schema.searchParams,"searchParams"in t?t.searchParams:{})),e.schema.body&&(n.body=D(e.schema.body,"body"in t?t.body:{})),n}import{DuplicateCheckResultSchema as de,IdentifyInputSchema as le,IdentifyResultSchema as ue}from"@inploi/talent-bank/contract";import*as b from"valibot";var V=({environment:e,publishableKey:t,logger:n})=>{let r=j[e];return{async checkDuplicate(s){try{let o=new URLSearchParams({email:s.email,scope:s.scope});s.scope==="job"&&s.jobId!=null&&o.set("job_id",String(s.jobId));let i=await fetch(`${r}/applications/check-duplicate?${o}`,{method:"GET",headers:{Accept:"application/json","x-publishable-key":t}});if(!i.ok)return n.error(`[TalentBankClient] checkDuplicate failed with status ${i.status}`),{isDuplicate:!1};let a=b.safeParse(de,await i.json());return a.success?a.output:(n.error("[TalentBankClient] checkDuplicate returned an invalid response"),{isDuplicate:!1})}catch(o){return n.error("[TalentBankClient] checkDuplicate failed:",o),{isDuplicate:!1}}},async identify(s){try{if(!s.anonymousId)return n.error("[TalentBankClient] identify skipped because anonymousId is missing"),null;let o={email:s.email,firstName:s.firstName,lastName:s.lastName,phone:s.phone,anonymousId:s.anonymousId,source:s.source??"sdk"},i=b.safeParse(le,o);if(!i.success)return n.error("[TalentBankClient] identify received invalid input"),null;let a=await fetch(`${r}/identify`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-publishable-key":t},body:JSON.stringify(i.output)});if(!a.ok)return n.error(`[TalentBankClient] identify failed with status ${a.status}`),null;let p=b.safeParse(ue,await a.json());return p.success?p.output:(n.error("[TalentBankClient] identify returned an invalid response"),null)}catch(o){return n.error("[TalentBankClient] identify failed:",o),null}}}};function me({publishableKey:e,env:t,logger:n=w,onEvent:r}){let s=U({baseUrl:I[t],publishableKey:e}),o=n===!1?R:n,i=new v({environment:t,apiKey:{type:"publishable",key:e},logger:o}),a=V({environment:t,publishableKey:e,logger:o}),p=K({rpcClient:i,logger:o,onEvent:r,talentBank:a});return{register:c=>c({logger:o,apiClient:s,analytics:p,rpcClient:i,publishableKey:e,env:t}),analytics:p,apiClient:s}}function fe(e){if(!(typeof document>"u")){if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",e,{once:!0});return}Promise.resolve().then(e)}}export{T as ApiError,v as InploiRpcClient,m as NotFoundError,u as ParsingError,d as SchemaValidationError,M as SdkError,f as UnauthorisedError,G as createPlugin,V as createTalentBankClient,Y as endpoint,O as generateUUID,q as getOrCreateAnonymousId,me as initialiseSdk,w as inploiBrandedLogger,Q as isSdkError,R as noLogging,fe as ready,k as typed,H as validateEndpointInputs};
|
|
1
|
+
var _="%c[inploi SDK]",P="color: #65BC67; font-weight: bold;",w={warn:(...e)=>console.warn(_,P,...e),error:(...e)=>console.error(_,P,...e),info:(...e)=>console.info(_,P,...e),log:(...e)=>console.log(_,P,...e)},R={info:()=>{},error:()=>{},log:()=>{},warn:()=>{}};var G=e=>e;function A(e,t){if(!e)throw new Error(t)}function C(e,t){return t in e}var Ie=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});var W="Unauthenticated",z="This action is unauthorized.",l=class extends Error{constructor(n,r){super(n);this.status=r,this.name="ErrorWithStatus"}},m=class extends l{constructor(t){super(t??"Not found"),this.name="NotFoundError",this.status=404}},f=class extends l{constructor(t,n){super(t??"You are not authorised to perform this action."),this.name="UnauthorisedError",this.status=n??401}},d=class extends l{constructor(n,r){let s=r?` in ${r}`:"";super(`Schema validation failed${s}`);this.issues=n;this.source=r;this.name="SchemaValidationError",this.status=400}},T=class extends l{constructor(t,n){super(t),this.name="ApiError",this.status=n??500}},u=class extends l{constructor(n){super("Error parsing response into JSON.");this.response=n;this.name="ParsingError",this.status=500}};var X=["message","error","errors","exception","exceptions"];function Z(e){console.log("json",e);let t=[];if(typeof e=="object"&&e!==null){for(let n of X)if(C(e,n)){console.log("hasProp",n,e[n]);let r=e[n];typeof r=="string"&&t.push(r),Array.isArray(r)&&r.every(s=>typeof s=="string")&&t.push(...r)}}return t.length===0&&t.push("Unknown error"),t.join(", ")}function L(e,t){if(t>=300&&t<=500){let n=Z(e);throw t===404?new m(n):n===W?new f("You are not authenticated.",t):n===z?new f(n,t):new T(n,t)}}var U=e=>{let t={Accept:"application/json","Content-Type":"application/json","x-publishable-key":e.publishableKey};return{fetch:async(n,r={})=>{let s={...r,headers:{...r.headers,...t}},o=await fetch(`${e.baseUrl}${n}`,s);if(o.status===404)throw new m;let a=await o.json().catch(async()=>{throw new u(o)});return L(a,o.status),a}}},M={NotFound:m,Unauthorised:f,SchemaValidation:d,Api:T,JsonParsing:u};function Q(e){return Object.values(M).some(t=>e instanceof t)}var $="2.0.2";var I={sandbox:"https://api.staging.inploi.com",production:"https://api.inploi.com",_internal_local:"http://api.test"},j={sandbox:"https://talent-bank.staging.inploi.com",production:"https://talent-bank.inploi.com",_internal_local:"http://localhost:8787"},F=$;var y="isdk_session",x=`${y}-candidate_id`;var O=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+e/4).toString(16));var N=e=>{let t=new Date;return t.setTime(t.getTime()+7*24*60*60*1e3),`${y}=${e};expires=${t.toUTCString()};path=/`},te=(e,t)=>{let n=e.get("session_id");if(t||n)return n;let r=sessionStorage.getItem(`${y}-session_id`);return typeof r=="string"?r:null},ne=()=>{if(typeof window>"u")return null;try{let e=window.localStorage.getItem(x);return typeof e=="string"&&e!==""?e:null}catch{return null}},re=e=>{if(!(typeof window>"u"))try{e?window.localStorage.setItem(x,e):window.localStorage.removeItem(x)}catch{}},oe=new RegExp(`${y}=([^;]+)`),B=e=>{let t=e?e.url:location.href,{searchParams:n}=new URL(t),r=n.get("anonymous_id"),s=te(n,typeof window>"u");if(r)return{anonymous_id:r,session_id:s};let o=e?e.headers.get("cookie"):document.cookie;return o?{anonymous_id:oe.exec(o)?.[1]??null,session_id:s}:{anonymous_id:r,session_id:s}},q=()=>{if(typeof window>"u")throw new Error("getOrCreateAnonymousId() can only be called in browser environment");let e=B().anonymous_id;if(e)return e;let t=O();return document.cookie=N(t),t},se=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},ae=e=>e==="about:client"?"":e,ie={pathname:"/log",method:"POST",schema:{response:k(),body:k()}},K=({rpcClient:e,logger:t,onEvent:n,talentBank:r})=>({log:async o=>{A(o.request||typeof window<"u","Cannot log on the server without a request. Please pass a request to `log`.");let a="request"in o&&o.request?{href:o.request.url,referrer:ae(o.request.referrer),title:""}:{href:location.href,referrer:document.referrer,title:document.title};try{let i={library:{name:"inploi-sdk",version:F},page:a},p=B(o.request);o.event==="IDENTIFY"&&!p.anonymous_id&&!o.request&&typeof window<"u"&&(p={...p,anonymous_id:q()});let g=ne();if(o.event==="IDENTIFY"&&r&&p.anonymous_id){let h=o.properties,E=await r.identify({email:h.email??h.identifier,firstName:h.first_name,lastName:h.last_name,phone:h.phone_number,anonymousId:p.anonymous_id,source:"sdk"});E?.candidateId&&(g=E.candidateId,re(E.candidateId))}let c={anonymous_id:p.anonymous_id,session_id:p.session_id,candidate_id:g,event:o.event,sent_at:new Date().toISOString(),context:i,properties:o.properties,custom_properties:o.customProperties},J=await e.request(ie,{body:c}),S=se(J);return S?.anonymous_id&&(c.anonymous_id=S.anonymous_id),S?.session_id&&(c.session_id=S.session_id),typeof window<"u"&&c.anonymous_id&&(c.session_id&&sessionStorage.setItem(`${y}-session_id`,c.session_id.toString()),document.cookie=N(c.anonymous_id)),n?.(c),{success:!0,data:c}}catch(i){return t.error("Failed to send log to API. Inspect error response of `log` for more information."),{success:!1,error:i}}},getHeaders:o=>{let a=new Headers;return o?.anonymous_id&&a.append("Set-Cookie",N(o.anonymous_id)),a},getSessionInfo:B});import{stringify as pe}from"neoqs";function D(e,t,n){let r=e["~standard"].validate(t);if(r instanceof Promise)throw new TypeError("Async schema");if(r.issues)throw new d(r.issues,n);return r.value}function ce(e,t,n){try{return{success:!0,output:D(e,t,n)}}catch(r){if(r instanceof d)return{success:!1,issues:r.issues,source:r.source};throw r}}var v=class{constructor(t){if(this.baseUrl=I[t.environment],this.headers=new Headers({"Content-Type":"application/json",Accept:"application/json"}),t.apiKey.type==="secret"){if(typeof window<"u")throw new Error("Secret key cannot be used in a browser environment");this.headers.set("x-secret-key",t.apiKey.key)}else this.headers.set("x-publishable-key",t.apiKey.key);this.logger=t.logger,this._environment=t.environment}get environment(){return this._environment}getFetchParams(t,n){let r=n.validateIn??!0,{searchParams:s,body:o}=r?H(t,n):n,a=new URL(this.baseUrl),i=t.pathname;if("params"in n&&n.params)for(let[p,g]of Object.entries(n.params))i=i.replace(`:${p}`,String(g));return a.pathname=i,t.schema.searchParams&&(a.search=pe(s)),[a.toString(),{method:t.method,body:o?JSON.stringify(o):void 0,headers:this.headers,signal:n.signal}]}async parseResponse(t,n){let r=await n.response.json().catch(a=>{throw this.logger.error(a),new u(n.response)});if(!(n.validateOut??!0))return r;let o=ce(t.schema.response,r,"response");if(!o.success)throw L(r,n.response.status),new d(o.issues,o.source);return o.output}async request(t,n){try{let r=this.getFetchParams(t,n),s=await fetch(...r);return this.parseResponse(t,{response:s,validateOut:n.validateOut})}catch(r){throw r instanceof d?this.logger.error(r.message,r.issues):this.logger.error(r),r}}};function k(){return{"~standard":{vendor:"inploi",version:1,validate:e=>({value:e})}}}function Y(e){return e}function H(e,t){let n={searchParams:void 0,body:void 0,validateIn:!1};return e.schema.searchParams&&(n.searchParams=D(e.schema.searchParams,"searchParams"in t?t.searchParams:{})),e.schema.body&&(n.body=D(e.schema.body,"body"in t?t.body:{})),n}import{DuplicateCheckResultSchema as de,IdentifyInputSchema as le,IdentifyResultSchema as ue}from"@inploi/talent-bank/contract";import*as b from"valibot";var V=({environment:e,publishableKey:t,logger:n})=>{let r=j[e];return{async checkDuplicate(s){try{let o=new URLSearchParams({email:s.email,scope:s.scope});s.scope==="job"&&s.jobId!=null&&o.set("job_id",String(s.jobId));let a=await fetch(`${r}/applications/check-duplicate?${o}`,{method:"GET",headers:{Accept:"application/json","x-publishable-key":t}});if(!a.ok)return n.error(`[TalentBankClient] checkDuplicate failed with status ${a.status}`),{isDuplicate:!1};let i=b.safeParse(de,await a.json());return i.success?i.output:(n.error("[TalentBankClient] checkDuplicate returned an invalid response"),{isDuplicate:!1})}catch(o){return n.error("[TalentBankClient] checkDuplicate failed:",o),{isDuplicate:!1}}},async identify(s){try{if(!s.anonymousId)return n.error("[TalentBankClient] identify skipped because anonymousId is missing"),null;let o={email:s.email,firstName:s.firstName,lastName:s.lastName,phone:s.phone,anonymousId:s.anonymousId,source:s.source??"sdk"},a=b.safeParse(le,o);if(!a.success)return n.error("[TalentBankClient] identify received invalid input"),null;let i=await fetch(`${r}/identify`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-publishable-key":t},body:JSON.stringify(a.output)});if(!i.ok)return n.error(`[TalentBankClient] identify failed with status ${i.status}`),null;let p=b.safeParse(ue,await i.json());return p.success?p.output:(n.error("[TalentBankClient] identify returned an invalid response"),null)}catch(o){return n.error("[TalentBankClient] identify failed:",o),null}}}};function me({publishableKey:e,env:t,logger:n=w,onEvent:r}){let s=U({baseUrl:I[t],publishableKey:e}),o=n===!1?R:n,a=new v({environment:t,apiKey:{type:"publishable",key:e},logger:o}),i=V({environment:t,publishableKey:e,logger:o}),p=K({rpcClient:a,logger:o,onEvent:r,talentBank:i});return{register:c=>c({logger:o,apiClient:s,analytics:p,rpcClient:a,publishableKey:e,env:t}),analytics:p,apiClient:s}}function fe(e){if(!(typeof document>"u")){if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",e,{once:!0});return}Promise.resolve().then(e)}}export{T as ApiError,v as InploiRpcClient,m as NotFoundError,u as ParsingError,d as SchemaValidationError,M as SdkError,f as UnauthorisedError,G as createPlugin,V as createTalentBankClient,Y as endpoint,O as generateUUID,q as getOrCreateAnonymousId,me as initialiseSdk,w as inploiBrandedLogger,Q as isSdkError,R as noLogging,fe as ready,k as typed,H as validateEndpointInputs};
|
|
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","../../core/src/common/common.utils.ts","../../core/src/common/common.currency.ts","../../core/src/common/common.datetime.ts","../src/sdk.api.ts","../package.json","../src/sdk.constants.ts","../src/sdk.uuid.ts","../src/sdk.analytics.ts","../src/sdk.rpc.ts","../src/sdk.talent-bank.ts","../src/sdk.ts","../src/ready.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 { InploiSdkEnvironment } from './sdk.constants';\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\t/** The publishable key used to initialise the SDK (available when registered via initialiseSdk) */\n\tpublishableKey?: string;\n\t/** The environment the SDK was initialised with — plugins can use this to select the correct service URL */\n\tenv?: InploiSdkEnvironment;\n};\n\nexport type InploiSdkPlugin = (dependencies: PluginDependencies) => any;\n\nexport const createPlugin = <T extends InploiSdkPlugin>(pluginFn: T) => pluginFn;\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\ttrailingZeroDisplay: 'stripIfInteger',\n\t});\n\tif (salary.pay_display === false) return undefined;\n\tif (salary.pay === null && salary.pay_min === null && salary.pay_max === null) 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","import { hasProp } from '@inploi/core/common';\nimport { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport const unauthenticatedMessage = 'Unauthenticated';\nexport const unauthorisedMessage = 'This action is unauthorized.';\n\nexport class ErrorWithStatus extends Error {\n\tpublic status?: number;\n\tconstructor(message?: string, status?: number) {\n\t\tsuper(message);\n\t\tthis.status = status;\n\t\tthis.name = 'ErrorWithStatus';\n\t}\n}\n\nexport class NotFoundError extends ErrorWithStatus {\n\tconstructor(message?: string) {\n\t\tsuper(message ?? 'Not found');\n\t\tthis.name = 'NotFoundError';\n\t\tthis.status = 404;\n\t}\n}\n\nexport class UnauthorisedError extends ErrorWithStatus {\n\tconstructor(message?: string, status?: number) {\n\t\tsuper(message ?? 'You are not authorised to perform this action.');\n\t\tthis.name = 'UnauthorisedError';\n\t\tthis.status = status ?? 401;\n\t}\n}\n\nexport class SchemaValidationError extends ErrorWithStatus {\n\tconstructor(\n\t\tpublic issues: readonly StandardSchemaV1.Issue[],\n\t\tpublic source?: 'body' | 'searchParams' | 'response',\n\t) {\n\t\tconst sourceText = source ? ` in ${source}` : '';\n\t\tsuper(`Schema validation failed${sourceText}`);\n\t\tthis.name = 'SchemaValidationError';\n\t\tthis.status = 400;\n\t}\n}\n\nexport class ApiError extends ErrorWithStatus {\n\tconstructor(message: string, status?: number) {\n\t\tsuper(message);\n\t\tthis.name = 'ApiError';\n\t\tthis.status = status ?? 500;\n\t}\n}\n\nexport class JsonParsingError extends ErrorWithStatus {\n\tconstructor(public response?: Response) {\n\t\tsuper('Error parsing response into JSON.');\n\t\tthis.name = 'ParsingError';\n\t\tthis.status = 500;\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\nconst ERROR_MESSAGE_KEYS = ['message', 'error', 'errors', 'exception', 'exceptions'] as const;\nfunction getErrorMessageFromJson(json: unknown): string {\n\tconsole.log('json', json);\n\tconst messages: string[] = [];\n\tif (typeof json === 'object' && json !== null) {\n\t\tfor (const key of ERROR_MESSAGE_KEYS) {\n\t\t\tif (hasProp(json, key)) {\n\t\t\t\tconsole.log('hasProp', key, json[key]);\n\t\t\t\tconst value = json[key];\n\t\t\t\tif (typeof value === 'string') messages.push(value);\n\t\t\t\tif (Array.isArray(value) && value.every((item): item is string => typeof item === 'string'))\n\t\t\t\t\tmessages.push(...value);\n\t\t\t}\n\t\t}\n\t}\n\tif (messages.length === 0) messages.push('Unknown error');\n\treturn messages.join(', ');\n}\n\n/** Throws branded errors when API returns a known error. */\nexport function handleApiExceptions(json: unknown, status: number) {\n\tif (status >= 300 && status <= 500) {\n\t\tconst message = getErrorMessageFromJson(json);\n\t\tif (status === 404) {\n\t\t\tthrow new NotFoundError(message);\n\t\t}\n\t\tif (message === unauthenticatedMessage) {\n\t\t\tthrow new UnauthorisedError('You are not authenticated.', status);\n\t\t}\n\t\tif (message === unauthorisedMessage) {\n\t\t\tthrow new UnauthorisedError(message, status);\n\t\t}\n\t\tthrow new ApiError(message, status);\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, response.status);\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\nexport const SdkError = {\n\tNotFound: NotFoundError,\n\tUnauthorised: UnauthorisedError,\n\tSchemaValidation: SchemaValidationError,\n\tApi: ApiError,\n\tJsonParsing: JsonParsingError,\n};\n\nexport function isSdkError(error: unknown): error is (typeof SdkError)[keyof typeof SdkError] {\n\treturn Object.values(SdkError).some(ErrorClass => error instanceof ErrorClass);\n}\n","{\n\t\"name\": \"@inploi/sdk\",\n\t\"version\": \"2.0.1\",\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\t\"test:coverage\": \"bun test --coverage --coverage-reporter=lcov\"\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\"@inploi/talent-bank\": \"github:inploi/talent-bank#667c4d51f3bb0042131dc8f0303a6ccdafa54958\",\n\t\t\"@standard-schema/spec\": \"^1.0.0\",\n\t\t\"neoqs\": \"^6.13.0\",\n\t\t\"valibot\": \"^1.3.1\"\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 ENV_TO_TALENT_BANK_URL: Record<InploiSdkEnvironment, string> = {\n\tsandbox: 'https://talent-bank.staging.inploi.com',\n\tproduction: 'https://talent-bank.inploi.com',\n\t// @ts-expect-error - local test environment\n\t_internal_local: 'http://localhost:8787',\n};\n\nexport const ANALYTICS_VERSION = version;\n\nexport const LOG_PATHNAME = '/log';\n\nexport const ANALYTICS_COOKIE_NAME = 'isdk_session';\n\n/**\n * Local-storage key used to persist the Talent Bank `candidateId` once the\n * user has identified via the SDK. The SDK forwards this id on every\n * subsequent analytics log request so Laravel can stamp it onto the session.\n */\nexport const ANALYTICS_CANDIDATE_ID_STORAGE_KEY = `${ANALYTICS_COOKIE_NAME}-candidate_id`;\n","/**\n * Generates a RFC 4122 v4 UUID.\n *\n * `crypto.randomUUID()` is only available in secure contexts (HTTPS). This\n * utility falls back to `crypto.getRandomValues`, which is available in all\n * browsing contexts including HTTP, so the SDK works on non-HTTPS staging\n * environments.\n */\nexport const generateUUID = (): `${string}-${string}-${string}-${string}-${string}` => {\n\tif (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n\t\treturn crypto.randomUUID();\n\t}\n\n\treturn '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, c =>\n\t\t(+c ^ (crypto.getRandomValues(new Uint8Array(1))[0]! & (15 >> (+c / 4)))).toString(16),\n\t) as `${string}-${string}-${string}-${string}-${string}`;\n};\n","import type { ResponseObj } from '@inploi/core/common';\nimport { invariant } from '@inploi/core/common';\n\nimport { InploiRpcClient, Logger, endpoint, typed } from '.';\nimport {\n\tANALYTICS_CANDIDATE_ID_STORAGE_KEY,\n\tANALYTICS_COOKIE_NAME,\n\tANALYTICS_VERSION,\n} from './sdk.constants';\nimport type { TalentBankClient } from './sdk.talent-bank';\nimport { generateUUID } from './sdk.uuid';\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\nexport type 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_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\t/**\n\t * Talent Bank candidate id — set once the SDK has identified the user\n\t * (via `TalentBankClient.identify`). Laravel's session middleware reads\n\t * this and stamps it onto `session.context.candidate_id` for attribution.\n\t * `null` for anonymous / unidentified users.\n\t */\n\tcandidate_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\n/**\n * Read the cached Talent Bank candidate id from localStorage.\n *\n * Returns `null` in non-browser / no-localStorage environments so server-side\n * logging and tests don't explode.\n */\nconst getStoredCandidateId = (): string | null => {\n\tif (typeof window === 'undefined') return null;\n\ttry {\n\t\tconst stored = window.localStorage.getItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY);\n\t\treturn typeof stored === 'string' && stored !== '' ? stored : null;\n\t} catch {\n\t\treturn null;\n\t}\n};\n\nconst setStoredCandidateId = (candidateId: string | null): void => {\n\tif (typeof window === 'undefined') return;\n\ttry {\n\t\tif (candidateId) {\n\t\t\twindow.localStorage.setItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY, candidateId);\n\t\t} else {\n\t\t\twindow.localStorage.removeItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY);\n\t\t}\n\t} catch {\n\t\t// localStorage may be unavailable (Safari private mode, sandboxed\n\t\t// iframes, etc). Identification still works for the current page — we\n\t\t// just won't remember it across reloads.\n\t}\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\n/**\n * Get or create a persistent anonymous ID.\n *\n * This is the universal identifier that bridges:\n * - SDK analytics (Laravel tracking)\n * - Agent conversations (Durable Object routing)\n * - Identity resolution\n *\n * The ID is:\n * - Generated client-side if none exists\n * - Persisted in cookie for 7 days\n * - The same across all SDK plugins\n *\n * @returns The anonymous ID (existing or newly generated)\n */\nexport const getOrCreateAnonymousId = (): string => {\n\t// Server-side: cannot generate, return empty (should not happen in normal flow)\n\tif (typeof window === 'undefined') {\n\t\tthrow new Error('getOrCreateAnonymousId() can only be called in browser environment');\n\t}\n\n\t// Check existing sources first\n\tconst existing = getSessionInfo().anonymous_id;\n\tif (existing) return existing;\n\n\t// Generate new ID and immediately persist to cookie\n\tconst newId = generateUUID();\n\tdocument.cookie = formatCookie(newId);\n\treturn newId;\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\tbody: typed<TrackPayload>(),\n\t},\n});\n\nexport type AnalyticsOnEventCallback = (event: AnalyticsLogParams) => void;\n\nexport const createAnalyticsService = ({\n\trpcClient,\n\tlogger,\n\tonEvent,\n\ttalentBank,\n}: {\n\tlogger: Logger;\n\trpcClient: InploiRpcClient;\n\tonEvent?: AnalyticsOnEventCallback;\n\t/**\n\t * Optional Talent Bank client. When provided, `IDENTIFY` events are sent\n\t * directly to Talent Bank's `POST /identify` (in addition to Laravel's\n\t * `/log`), and the returned `candidateId` is cached locally and forwarded\n\t * on every subsequent log call.\n\t */\n\ttalentBank?: TalentBankClient;\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\tlet sessionInfo = getSessionInfo(params.request);\n\t\t\tif (params.event === 'IDENTIFY' && !sessionInfo.anonymous_id && !params.request && typeof window !== 'undefined') {\n\t\t\t\tsessionInfo = { ...sessionInfo, anonymous_id: getOrCreateAnonymousId() };\n\t\t\t}\n\n\t\t\t// For IDENTIFY events, resolve the Talent Bank candidate directly\n\t\t\t// from the SDK before firing the /log call. The returned candidateId\n\t\t\t// is cached so every subsequent log request includes it. Identify\n\t\t\t// is best-effort: a failure here must not prevent the analytics log.\n\t\t\tlet resolvedCandidateId = getStoredCandidateId();\n\t\t\tif (params.event === 'IDENTIFY' && talentBank && sessionInfo.anonymous_id) {\n\t\t\t\tconst identifyProperties = params.properties as EventPropertyMap['IDENTIFY']['properties'];\n\t\t\t\tconst result = await talentBank.identify({\n\t\t\t\t\temail: identifyProperties.email ?? identifyProperties.identifier,\n\t\t\t\t\tfirstName: identifyProperties.first_name,\n\t\t\t\t\tlastName: identifyProperties.last_name,\n\t\t\t\t\tphone: identifyProperties.phone_number,\n\t\t\t\t\tanonymousId: sessionInfo.anonymous_id,\n\t\t\t\t\tsource: 'sdk',\n\t\t\t\t});\n\t\t\t\tif (result?.candidateId) {\n\t\t\t\t\tresolvedCandidateId = result.candidateId;\n\t\t\t\t\tsetStoredCandidateId(result.candidateId);\n\t\t\t\t}\n\t\t\t}\n\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\tcandidate_id: resolvedCandidateId,\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\tbody: 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\tonEvent?.(payload as AnalyticsLogParams);\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\tsource?: 'body' | 'searchParams' | 'response',\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, source);\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\tsource?: 'body' | 'searchParams' | 'response',\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\t\tsource?: 'body' | 'searchParams' | 'response';\n\t } {\n\ttry {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\toutput: parse(schema, input, source),\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\tsource: e.source,\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// eslint-disable-next-line @typescript-eslint/ban-types\ntype NonReducibleUnknown = {} | null | undefined;\ntype LooseAutocomplete<T extends BaseType, BaseType> = T | BaseType;\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\tprivate _environment: InploiSdkEnvironment;\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\tthis._environment = params.environment;\n\t}\n\n\tget environment() {\n\t\treturn this._environment;\n\t}\n\n\t/** Gets params for a fetch request to the given endpoint */\n\tgetFetchParams<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}> & {\n\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the inputs against the schema.\n\t\t\t\t * If you want to skip validation (e.g.: already validated yourself or with `validateEndpontInputs`), set this to false.\n\t\t\t\t */\n\t\t\t\tvalidateIn?: boolean;\n\t\t\t}\n\t\t:\tnever,\n\t): [url: string, options: RequestInit] {\n\t\tconst validateIn = options.validateIn ?? true;\n\t\tconst { searchParams, body } = validateIn ? validateEndpointInputs(endpoint, options) : options;\n\n\t\tconst url = new URL(this.baseUrl);\n\n\t\t// Replace path parameters in pathname\n\t\tlet pathname = endpoint.pathname;\n\t\tif ('params' in options && options.params) {\n\t\t\tfor (const [key, value] of Object.entries(options.params)) {\n\t\t\t\tpathname = pathname.replace(`:${key}`, String(value));\n\t\t\t}\n\t\t}\n\t\turl.pathname = pathname;\n\n\t\tif (endpoint.schema.searchParams) {\n\t\t\turl.search = stringify(searchParams);\n\t\t}\n\n\t\treturn [\n\t\t\turl.toString(),\n\t\t\t{\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\t\t];\n\t}\n\n\t/** Parses a response against an endpoint’s response schema, considering common errors thrown from the API.\n\t * @throws {JsonParsingError} - If the response is not valid JSON.\n\t * @throws {SchemaValidationError} - If the response does not match the schema.\n\t * @throws {ApiError} - If the API responded with an error message.\n\t */\n\tasync parseResponse<T extends RpcEndpoint>(\n\t\tendpoint: T,\n\t\toptions: {\n\t\t\tresponse: Response;\n\t\t\t/**\n\t\t\t * Whether to validate the response against the schema.\n\t\t\t * This is meant more as an escape hatch for when the response is not as expected and you want to handle it separately yourself.\n\t\t\t * ⚠️ This will lead to potential type/runtime mismatch as it does not verify the response against the schema.\n\t\t\t */\n\t\t\tvalidateOut?: boolean;\n\t\t},\n\t): Promise<StandardSchemaV1.InferOutput<T['schema']['response']>> {\n\t\tconst json = await options.response.json().catch(e => {\n\t\t\tthis.logger.error(e);\n\t\t\tthrow new JsonParsingError(options.response);\n\t\t});\n\n\t\tconst validateOut = options.validateOut ?? true;\n\t\tif (!validateOut) return json as StandardSchemaV1.InferOutput<T['schema']['response']>;\n\n\t\tconst result = safeParse(endpoint.schema.response, json, 'response');\n\t\tif (!result.success) {\n\t\t\thandleApiExceptions(json, options.response.status);\n\t\t\tthrow new SchemaValidationError(result.issues, result.source);\n\t\t}\n\n\t\treturn result.output as StandardSchemaV1.InferOutput<T['schema']['response']>;\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}> & {\n\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the inputs against the schema.\n\t\t\t\t * If you want to skip validation (e.g.: already validated yourself or with `validateEndpontInputs`), set this to false.\n\t\t\t\t */\n\t\t\t\tvalidateIn?: boolean;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the response against the schema.\n\t\t\t\t * This is meant more as an escape hatch for when the response is not as expected and you want to handle it separately yourself.\n\t\t\t\t * ⚠️ This will lead to potential type/runtime mismatch as it does not verify the response against the schema.\n\t\t\t\t */\n\t\t\t\tvalidateOut?: boolean;\n\t\t\t}\n\t\t:\tnever,\n\t): Promise<StandardSchemaV1.InferOutput<T['schema']['response']>> {\n\t\ttry {\n\t\t\tconst fetchParams = this.getFetchParams(endpoint, options);\n\t\t\tconst response = await fetch(...fetchParams);\n\t\t\treturn this.parseResponse(endpoint, { response, validateOut: options.validateOut });\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 : LooseAutocomplete<T[K], NonReducibleUnknown>;\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\n/** Validates the inputs for an endpoint ahead of time\n * Useful when you need to validate and throw earlier, or use the inputs for something other than the API call.\n */\nexport function validateEndpointInputs<T extends RpcEndpoint>(\n\tendpoint: T,\n\toptions: GetSchemaValues<{ body: unknown; searchParams: unknown }>,\n) {\n\tconst validatedInputs = {\n\t\tsearchParams: undefined,\n\t\tbody: undefined,\n\t\tvalidateIn: false,\n\t} as T extends RpcEndpoint<infer _, infer __, infer ___, infer TSearch, infer TBody> ?\n\t\tGetSchemaValues<{\n\t\t\tbody: TBody;\n\t\t\tsearchParams: TSearch;\n\t\t}> & {\n\t\t\tvalidateIn: false;\n\t\t}\n\t:\tnever;\n\n\tif (endpoint.schema.searchParams) {\n\t\tvalidatedInputs.searchParams = parse(\n\t\t\tendpoint.schema.searchParams,\n\t\t\t'searchParams' in options ? options.searchParams : {},\n\t\t);\n\t}\n\n\tif (endpoint.schema.body) {\n\t\tvalidatedInputs.body = parse(endpoint.schema.body, 'body' in options ? options.body : {});\n\t}\n\n\treturn validatedInputs;\n}\n","import {\n\ttype CandidateSource,\n\ttype DuplicateCheckResult,\n\tDuplicateCheckResultSchema,\n\ttype DuplicateCheckScope,\n\ttype IdentifyInput,\n\tIdentifyInputSchema,\n\ttype IdentifyResult,\n\tIdentifyResultSchema,\n} from '@inploi/talent-bank/contract';\nimport * as v from 'valibot';\n\nimport { ENV_TO_TALENT_BANK_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger } from './sdk.logger';\n\nexport type TalentBankCheckDuplicateResult = DuplicateCheckResult;\n\nexport type TalentBankIdentifyParams = Pick<IdentifyInput, 'anonymousId' | 'email'> &\n\tPartial<Pick<IdentifyInput, 'firstName' | 'lastName' | 'phone'>> & {\n\t\t/** Caller tag — defaults to `'sdk'`. */\n\t\tsource?: CandidateSource;\n\t};\n\nexport type TalentBankIdentifyResult = IdentifyResult;\n\nexport interface TalentBankClient {\n\tcheckDuplicate(params: {\n\t\temail: string;\n\t\tjobId?: string | number;\n\t\tscope: DuplicateCheckScope;\n\t}): Promise<TalentBankCheckDuplicateResult>;\n\n\t/**\n\t * Resolve or create a Talent Bank candidate for the supplied identifier.\n\t *\n\t * This is the direct-to-Talent-Bank replacement for the old Laravel-proxied\n\t * `/log` IDENTIFY flow. The SDK calls this and then forwards the returned\n\t * `candidateId` on every subsequent analytics log so Laravel can stamp it\n\t * onto the session for attribution.\n\t *\n\t * Returns `null` if the call fails — identification is best-effort and must\n\t * never break the host page.\n\t */\n\tidentify(params: TalentBankIdentifyParams): Promise<TalentBankIdentifyResult | null>;\n}\n\nexport const createTalentBankClient = ({\n\tenvironment,\n\tpublishableKey,\n\tlogger,\n}: {\n\tenvironment: InploiSdkEnvironment;\n\tpublishableKey: string;\n\tlogger: Logger;\n}): TalentBankClient => {\n\tconst baseUrl = ENV_TO_TALENT_BANK_URL[environment];\n\n\treturn {\n\t\tasync checkDuplicate(params) {\n\t\t\ttry {\n\t\t\t\tconst searchParams = new URLSearchParams({ email: params.email, scope: params.scope });\n\t\t\t\tif (params.scope === 'job' && params.jobId != null) {\n\t\t\t\t\tsearchParams.set('job_id', String(params.jobId));\n\t\t\t\t}\n\n\t\t\t\tconst response = await fetch(`${baseUrl}/applications/check-duplicate?${searchParams}`, {\n\t\t\t\t\tmethod: 'GET',\n\t\t\t\t\theaders: { Accept: 'application/json', 'x-publishable-key': publishableKey },\n\t\t\t\t});\n\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlogger.error(`[TalentBankClient] checkDuplicate failed with status ${response.status}`);\n\t\t\t\t\treturn { isDuplicate: false };\n\t\t\t\t}\n\n\t\t\t\tconst parsed = v.safeParse(DuplicateCheckResultSchema, await response.json());\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] checkDuplicate returned an invalid response');\n\t\t\t\t\treturn { isDuplicate: false };\n\t\t\t\t}\n\n\t\t\t\treturn parsed.output;\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error('[TalentBankClient] checkDuplicate failed:', e);\n\t\t\t\treturn { isDuplicate: false };\n\t\t\t}\n\t\t},\n\n\t\tasync identify(params) {\n\t\t\ttry {\n\t\t\t\tif (!params.anonymousId) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify skipped because anonymousId is missing');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst body: IdentifyInput = {\n\t\t\t\t\temail: params.email,\n\t\t\t\t\tfirstName: params.firstName,\n\t\t\t\t\tlastName: params.lastName,\n\t\t\t\t\tphone: params.phone,\n\t\t\t\t\tanonymousId: params.anonymousId,\n\t\t\t\t\tsource: params.source ?? 'sdk',\n\t\t\t\t};\n\t\t\t\tconst parsedBody = v.safeParse(IdentifyInputSchema, body);\n\t\t\t\tif (!parsedBody.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify received invalid input');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst response = await fetch(`${baseUrl}/identify`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t\tAccept: 'application/json',\n\t\t\t\t\t\t'x-publishable-key': publishableKey,\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(parsedBody.output),\n\t\t\t\t});\n\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlogger.error(`[TalentBankClient] identify failed with status ${response.status}`);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst parsed = v.safeParse(IdentifyResultSchema, await response.json());\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify returned an invalid response');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\treturn parsed.output;\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error('[TalentBankClient] identify failed:', e);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\t};\n};\n","import { AnalyticsOnEventCallback, 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';\nimport { createTalentBankClient } from './sdk.talent-bank';\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\t/** When provided, this callback will be called with every event that is logged to the analytics service. */\n\tonEvent?: AnalyticsOnEventCallback;\n};\n\nexport function initialiseSdk({\n\tpublishableKey,\n\tenv,\n\tlogger = inploiBrandedLogger,\n\tonEvent,\n}: 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 talentBank = createTalentBankClient({ environment: env, publishableKey, logger: loggerService });\n\tconst analytics = createAnalyticsService({\n\t\trpcClient,\n\t\tlogger: loggerService,\n\t\tonEvent,\n\t\ttalentBank,\n\t});\n\n\tconst register = <P extends InploiSdkPlugin>(plugin: P): ReturnType<P> => {\n\t\treturn plugin({ logger: loggerService, apiClient, analytics, rpcClient, publishableKey, env });\n\t};\n\n\treturn { register, analytics, apiClient };\n}\n\nexport type InploiSdk = ReturnType<typeof initialiseSdk>;\n","export function ready(callback: () => void): void {\n\tif (typeof document === 'undefined') return;\n\n\tif (document.readyState === 'loading') {\n\t\tdocument.addEventListener('DOMContentLoaded', callback, { once: true });\n\t\treturn;\n\t}\n\n\tPromise.resolve().then(callback);\n}\n"],"mappings":"AAAO,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,ECW3G,IAAMC,EAA2CC,GAAgBA,ECzBjE,SAASC,EAAUC,EAAgBC,EAAqC,CAC9E,GAAI,CAAAD,EAIJ,MAAM,IAAI,MAAMC,CAAO,CACxB,CA2BO,SAASC,EAA+BC,EAAcC,EAAqC,CACjG,OAAOA,KAAQD,CAChB,CE9BA,IAAME,GAAoB,IAAI,KAAK,mBAAmB,OAAW,CAAE,QAAS,MAAO,CAAC,ECN7E,IAAMC,EAAyB,kBACzBC,EAAsB,+BAEtBC,E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AAAC,EAASC,EACT,QAAAC,CACD,EAA8B,CAE7B,IAAMC,EAAYC,EAAgB,CAAE,QAASC,EAAeN,CAAG,EAAG,eAAAD,CAAe,CAAC,EAC5EQ,EAAgBN,IAAW,GAAQO,EAAYP,EAC/CQ,EAAY,IAAIC,EAAgB,CACrC,YAAaV,EACb,OAAQ,CAAE,KAAM,cAAe,IAAKD,CAAe,EACnD,OAAQQ,CACT,CAAC,EACKI,EAAaC,EAAuB,CAAE,YAAaZ,EAAK,eAAAD,EAAgB,OAAQQ,CAAc,CAAC,EAC/FM,EAAYC,EAAuB,CACxC,UAAAL,EACA,OAAQF,EACR,QAAAJ,EACA,WAAAQ,CACD,CAAC,EAMD,MAAO,CAAE,SAJoCI,GACrCA,EAAO,CAAE,OAAQR,EAAe,UAAAH,EAAW,UAAAS,EAAW,UAAAJ,EAAW,eAAAV,EAAgB,IAAAC,CAAI,CAAC,EAG3E,UAAAa,EAAW,UAAAT,CAAU,CACzC,CCnDO,SAASY,GAAMC,EAA4B,CACjD,GAAI,SAAO,SAAa,KAExB,IAAI,SAAS,aAAe,UAAW,CACtC,SAAS,iBAAiB,mBAAoBA,EAAU,CAAE,KAAM,EAAK,CAAC,EACtE,MACD,CAEA,QAAQ,QAAQ,EAAE,KAAKA,CAAQ,EAChC","names":["CONSOLE_PREFIX","CONSOLE_STYLE","inploiBrandedLogger","args","noLogging","createPlugin","pluginFn","invariant","condition","message","hasProp","data","prop","DEFAULT_FORMATTER","unauthenticatedMessage","unauthorisedMessage","ErrorWithStatus","message","status","NotFoundError","UnauthorisedError","SchemaValidationError","issues","source","sourceText","ApiError","JsonParsingError","response","ERROR_MESSAGE_KEYS","getErrorMessageFromJson","json","messages","key","hasProp","value","item","handleApiExceptions","status","message","NotFoundError","unauthenticatedMessage","UnauthorisedError","unauthorisedMessage","ApiError","createApiClient","params","defaultHeaders","pathname","options","init","response","JsonParsingError","SdkError","SchemaValidationError","isSdkError","error","ErrorClass","version","ENV_TO_API_URL","ENV_TO_TALENT_BANK_URL","ANALYTICS_VERSION","version","ANALYTICS_COOKIE_NAME","ANALYTICS_CANDIDATE_ID_STORAGE_KEY","generateUUID","c","formatCookie","value","now","ANALYTICS_COOKIE_NAME","getSessionId","searchParams","isServer","fromSearchParams","fromSessionStorage","getStoredCandidateId","stored","ANALYTICS_CANDIDATE_ID_STORAGE_KEY","setStoredCandidateId","candidateId","cookieRegex","getSessionInfo","request","href","anonymous_id","session_id","cookie","getOrCreateAnonymousId","existing","newId","generateUUID","getSessionInfoFromResponse","response","serverReferrer","referrer","analyticsLogEndpoint","typed","createAnalyticsService","rpcClient","logger","onEvent","talentBank","params","invariant","page","context","ANALYTICS_VERSION","sessionInfo","resolvedCandidateId","identifyProperties","result","payload","responseJson","newSession","e","headers","stringify","parse","schema","input","source","result","SchemaValidationError","safeParse","e","InploiRpcClient","params","ENV_TO_API_URL","endpoint","options","validateIn","searchParams","body","validateEndpointInputs","url","pathname","key","value","stringify","json","JsonParsingError","handleApiExceptions","fetchParams","response","typed","validatedInputs","DuplicateCheckResultSchema","IdentifyInputSchema","IdentifyResultSchema","v","createTalentBankClient","environment","publishableKey","logger","baseUrl","ENV_TO_TALENT_BANK_URL","params","searchParams","response","parsed","DuplicateCheckResultSchema","e","body","parsedBody","IdentifyInputSchema","IdentifyResultSchema","initialiseSdk","publishableKey","env","logger","inploiBrandedLogger","onEvent","apiClient","createApiClient","ENV_TO_API_URL","loggerService","noLogging","rpcClient","InploiRpcClient","talentBank","createTalentBankClient","analytics","createAnalyticsService","plugin","ready","callback"]}
|
|
1
|
+
{"version":3,"sources":["../src/sdk.logger.ts","../src/sdk.plugins.ts","../../core/src/common/common.utils.ts","../../core/src/common/common.currency.ts","../../core/src/common/common.datetime.ts","../src/sdk.api.ts","../package.json","../src/sdk.constants.ts","../src/sdk.uuid.ts","../src/sdk.analytics.ts","../src/sdk.rpc.ts","../src/sdk.talent-bank.ts","../src/sdk.ts","../src/ready.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 { InploiSdkEnvironment } from './sdk.constants';\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\t/** The publishable key used to initialise the SDK (available when registered via initialiseSdk) */\n\tpublishableKey?: string;\n\t/** The environment the SDK was initialised with — plugins can use this to select the correct service URL */\n\tenv?: InploiSdkEnvironment;\n};\n\nexport type InploiSdkPlugin = (dependencies: PluginDependencies) => any;\n\nexport const createPlugin = <T extends InploiSdkPlugin>(pluginFn: T) => pluginFn;\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\ttrailingZeroDisplay: 'stripIfInteger',\n\t});\n\tif (salary.pay_display === false) return undefined;\n\tif (salary.pay === null && salary.pay_min === null && salary.pay_max === null) 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","import { hasProp } from '@inploi/core/common';\nimport { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport const unauthenticatedMessage = 'Unauthenticated';\nexport const unauthorisedMessage = 'This action is unauthorized.';\n\nexport class ErrorWithStatus extends Error {\n\tpublic status?: number;\n\tconstructor(message?: string, status?: number) {\n\t\tsuper(message);\n\t\tthis.status = status;\n\t\tthis.name = 'ErrorWithStatus';\n\t}\n}\n\nexport class NotFoundError extends ErrorWithStatus {\n\tconstructor(message?: string) {\n\t\tsuper(message ?? 'Not found');\n\t\tthis.name = 'NotFoundError';\n\t\tthis.status = 404;\n\t}\n}\n\nexport class UnauthorisedError extends ErrorWithStatus {\n\tconstructor(message?: string, status?: number) {\n\t\tsuper(message ?? 'You are not authorised to perform this action.');\n\t\tthis.name = 'UnauthorisedError';\n\t\tthis.status = status ?? 401;\n\t}\n}\n\nexport class SchemaValidationError extends ErrorWithStatus {\n\tconstructor(\n\t\tpublic issues: readonly StandardSchemaV1.Issue[],\n\t\tpublic source?: 'body' | 'searchParams' | 'response',\n\t) {\n\t\tconst sourceText = source ? ` in ${source}` : '';\n\t\tsuper(`Schema validation failed${sourceText}`);\n\t\tthis.name = 'SchemaValidationError';\n\t\tthis.status = 400;\n\t}\n}\n\nexport class ApiError extends ErrorWithStatus {\n\tconstructor(message: string, status?: number) {\n\t\tsuper(message);\n\t\tthis.name = 'ApiError';\n\t\tthis.status = status ?? 500;\n\t}\n}\n\nexport class JsonParsingError extends ErrorWithStatus {\n\tconstructor(public response?: Response) {\n\t\tsuper('Error parsing response into JSON.');\n\t\tthis.name = 'ParsingError';\n\t\tthis.status = 500;\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\nconst ERROR_MESSAGE_KEYS = ['message', 'error', 'errors', 'exception', 'exceptions'] as const;\nfunction getErrorMessageFromJson(json: unknown): string {\n\tconsole.log('json', json);\n\tconst messages: string[] = [];\n\tif (typeof json === 'object' && json !== null) {\n\t\tfor (const key of ERROR_MESSAGE_KEYS) {\n\t\t\tif (hasProp(json, key)) {\n\t\t\t\tconsole.log('hasProp', key, json[key]);\n\t\t\t\tconst value = json[key];\n\t\t\t\tif (typeof value === 'string') messages.push(value);\n\t\t\t\tif (Array.isArray(value) && value.every((item): item is string => typeof item === 'string'))\n\t\t\t\t\tmessages.push(...value);\n\t\t\t}\n\t\t}\n\t}\n\tif (messages.length === 0) messages.push('Unknown error');\n\treturn messages.join(', ');\n}\n\n/** Throws branded errors when API returns a known error. */\nexport function handleApiExceptions(json: unknown, status: number) {\n\tif (status >= 300 && status <= 500) {\n\t\tconst message = getErrorMessageFromJson(json);\n\t\tif (status === 404) {\n\t\t\tthrow new NotFoundError(message);\n\t\t}\n\t\tif (message === unauthenticatedMessage) {\n\t\t\tthrow new UnauthorisedError('You are not authenticated.', status);\n\t\t}\n\t\tif (message === unauthorisedMessage) {\n\t\t\tthrow new UnauthorisedError(message, status);\n\t\t}\n\t\tthrow new ApiError(message, status);\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, response.status);\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\nexport const SdkError = {\n\tNotFound: NotFoundError,\n\tUnauthorised: UnauthorisedError,\n\tSchemaValidation: SchemaValidationError,\n\tApi: ApiError,\n\tJsonParsing: JsonParsingError,\n};\n\nexport function isSdkError(error: unknown): error is (typeof SdkError)[keyof typeof SdkError] {\n\treturn Object.values(SdkError).some(ErrorClass => error instanceof ErrorClass);\n}\n","{\n\t\"name\": \"@inploi/sdk\",\n\t\"version\": \"2.0.2\",\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\t\"test:coverage\": \"bun test --coverage --coverage-reporter=lcov\"\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\"@inploi/talent-bank\": \"github:inploi/talent-bank#a5826c57a235acedd6af2209b2ea25dc414a8cfa\",\n\t\t\"@standard-schema/spec\": \"^1.0.0\",\n\t\t\"neoqs\": \"^6.13.0\",\n\t\t\"valibot\": \"^1.3.1\"\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 ENV_TO_TALENT_BANK_URL: Record<InploiSdkEnvironment, string> = {\n\tsandbox: 'https://talent-bank.staging.inploi.com',\n\tproduction: 'https://talent-bank.inploi.com',\n\t// @ts-expect-error - local test environment\n\t_internal_local: 'http://localhost:8787',\n};\n\nexport const ANALYTICS_VERSION = version;\n\nexport const LOG_PATHNAME = '/log';\n\nexport const ANALYTICS_COOKIE_NAME = 'isdk_session';\n\n/**\n * Local-storage key used to persist the Talent Bank `candidateId` once the\n * user has identified via the SDK. The SDK forwards this id on every\n * subsequent analytics log request so Laravel can stamp it onto the session.\n */\nexport const ANALYTICS_CANDIDATE_ID_STORAGE_KEY = `${ANALYTICS_COOKIE_NAME}-candidate_id`;\n","/**\n * Generates a RFC 4122 v4 UUID.\n *\n * `crypto.randomUUID()` is only available in secure contexts (HTTPS). This\n * utility falls back to `crypto.getRandomValues`, which is available in all\n * browsing contexts including HTTP, so the SDK works on non-HTTPS staging\n * environments.\n */\nexport const generateUUID = (): `${string}-${string}-${string}-${string}-${string}` => {\n\tif (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n\t\treturn crypto.randomUUID();\n\t}\n\n\treturn '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, c =>\n\t\t(+c ^ (crypto.getRandomValues(new Uint8Array(1))[0]! & (15 >> (+c / 4)))).toString(16),\n\t) as `${string}-${string}-${string}-${string}-${string}`;\n};\n","import type { ResponseObj } from '@inploi/core/common';\nimport { invariant } from '@inploi/core/common';\n\nimport { InploiRpcClient, Logger, endpoint, typed } from '.';\nimport {\n\tANALYTICS_CANDIDATE_ID_STORAGE_KEY,\n\tANALYTICS_COOKIE_NAME,\n\tANALYTICS_VERSION,\n} from './sdk.constants';\nimport type { TalentBankClient } from './sdk.talent-bank';\nimport { generateUUID } from './sdk.uuid';\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\nexport type 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_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\t/**\n\t * Talent Bank candidate id — set once the SDK has identified the user\n\t * (via `TalentBankClient.identify`). Laravel's session middleware reads\n\t * this and stamps it onto `session.context.candidate_id` for attribution.\n\t * `null` for anonymous / unidentified users.\n\t */\n\tcandidate_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\n/**\n * Read the cached Talent Bank candidate id from localStorage.\n *\n * Returns `null` in non-browser / no-localStorage environments so server-side\n * logging and tests don't explode.\n */\nconst getStoredCandidateId = (): string | null => {\n\tif (typeof window === 'undefined') return null;\n\ttry {\n\t\tconst stored = window.localStorage.getItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY);\n\t\treturn typeof stored === 'string' && stored !== '' ? stored : null;\n\t} catch {\n\t\treturn null;\n\t}\n};\n\nconst setStoredCandidateId = (candidateId: string | null): void => {\n\tif (typeof window === 'undefined') return;\n\ttry {\n\t\tif (candidateId) {\n\t\t\twindow.localStorage.setItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY, candidateId);\n\t\t} else {\n\t\t\twindow.localStorage.removeItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY);\n\t\t}\n\t} catch {\n\t\t// localStorage may be unavailable (Safari private mode, sandboxed\n\t\t// iframes, etc). Identification still works for the current page — we\n\t\t// just won't remember it across reloads.\n\t}\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\n/**\n * Get or create a persistent anonymous ID.\n *\n * This is the universal identifier that bridges:\n * - SDK analytics (Laravel tracking)\n * - Agent conversations (Durable Object routing)\n * - Identity resolution\n *\n * The ID is:\n * - Generated client-side if none exists\n * - Persisted in cookie for 7 days\n * - The same across all SDK plugins\n *\n * @returns The anonymous ID (existing or newly generated)\n */\nexport const getOrCreateAnonymousId = (): string => {\n\t// Server-side: cannot generate, return empty (should not happen in normal flow)\n\tif (typeof window === 'undefined') {\n\t\tthrow new Error('getOrCreateAnonymousId() can only be called in browser environment');\n\t}\n\n\t// Check existing sources first\n\tconst existing = getSessionInfo().anonymous_id;\n\tif (existing) return existing;\n\n\t// Generate new ID and immediately persist to cookie\n\tconst newId = generateUUID();\n\tdocument.cookie = formatCookie(newId);\n\treturn newId;\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\tbody: typed<TrackPayload>(),\n\t},\n});\n\nexport type AnalyticsOnEventCallback = (event: AnalyticsLogParams) => void;\n\nexport const createAnalyticsService = ({\n\trpcClient,\n\tlogger,\n\tonEvent,\n\ttalentBank,\n}: {\n\tlogger: Logger;\n\trpcClient: InploiRpcClient;\n\tonEvent?: AnalyticsOnEventCallback;\n\t/**\n\t * Optional Talent Bank client. When provided, `IDENTIFY` events are sent\n\t * directly to Talent Bank's `POST /identify` (in addition to Laravel's\n\t * `/log`), and the returned `candidateId` is cached locally and forwarded\n\t * on every subsequent log call.\n\t */\n\ttalentBank?: TalentBankClient;\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\tlet sessionInfo = getSessionInfo(params.request);\n\t\t\tif (params.event === 'IDENTIFY' && !sessionInfo.anonymous_id && !params.request && typeof window !== 'undefined') {\n\t\t\t\tsessionInfo = { ...sessionInfo, anonymous_id: getOrCreateAnonymousId() };\n\t\t\t}\n\n\t\t\t// For IDENTIFY events, resolve the Talent Bank candidate directly\n\t\t\t// from the SDK before firing the /log call. The returned candidateId\n\t\t\t// is cached so every subsequent log request includes it. Identify\n\t\t\t// is best-effort: a failure here must not prevent the analytics log.\n\t\t\tlet resolvedCandidateId = getStoredCandidateId();\n\t\t\tif (params.event === 'IDENTIFY' && talentBank && sessionInfo.anonymous_id) {\n\t\t\t\tconst identifyProperties = params.properties as EventPropertyMap['IDENTIFY']['properties'];\n\t\t\t\tconst result = await talentBank.identify({\n\t\t\t\t\temail: identifyProperties.email ?? identifyProperties.identifier,\n\t\t\t\t\tfirstName: identifyProperties.first_name,\n\t\t\t\t\tlastName: identifyProperties.last_name,\n\t\t\t\t\tphone: identifyProperties.phone_number,\n\t\t\t\t\tanonymousId: sessionInfo.anonymous_id,\n\t\t\t\t\tsource: 'sdk',\n\t\t\t\t});\n\t\t\t\tif (result?.candidateId) {\n\t\t\t\t\tresolvedCandidateId = result.candidateId;\n\t\t\t\t\tsetStoredCandidateId(result.candidateId);\n\t\t\t\t}\n\t\t\t}\n\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\tcandidate_id: resolvedCandidateId,\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\tbody: 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\tonEvent?.(payload as AnalyticsLogParams);\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\tsource?: 'body' | 'searchParams' | 'response',\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, source);\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\tsource?: 'body' | 'searchParams' | 'response',\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\t\tsource?: 'body' | 'searchParams' | 'response';\n\t } {\n\ttry {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\toutput: parse(schema, input, source),\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\tsource: e.source,\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// eslint-disable-next-line @typescript-eslint/ban-types\ntype NonReducibleUnknown = {} | null | undefined;\ntype LooseAutocomplete<T extends BaseType, BaseType> = T | BaseType;\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\tprivate _environment: InploiSdkEnvironment;\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\tthis._environment = params.environment;\n\t}\n\n\tget environment() {\n\t\treturn this._environment;\n\t}\n\n\t/** Gets params for a fetch request to the given endpoint */\n\tgetFetchParams<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}> & {\n\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the inputs against the schema.\n\t\t\t\t * If you want to skip validation (e.g.: already validated yourself or with `validateEndpontInputs`), set this to false.\n\t\t\t\t */\n\t\t\t\tvalidateIn?: boolean;\n\t\t\t}\n\t\t:\tnever,\n\t): [url: string, options: RequestInit] {\n\t\tconst validateIn = options.validateIn ?? true;\n\t\tconst { searchParams, body } = validateIn ? validateEndpointInputs(endpoint, options) : options;\n\n\t\tconst url = new URL(this.baseUrl);\n\n\t\t// Replace path parameters in pathname\n\t\tlet pathname = endpoint.pathname;\n\t\tif ('params' in options && options.params) {\n\t\t\tfor (const [key, value] of Object.entries(options.params)) {\n\t\t\t\tpathname = pathname.replace(`:${key}`, String(value));\n\t\t\t}\n\t\t}\n\t\turl.pathname = pathname;\n\n\t\tif (endpoint.schema.searchParams) {\n\t\t\turl.search = stringify(searchParams);\n\t\t}\n\n\t\treturn [\n\t\t\turl.toString(),\n\t\t\t{\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\t\t];\n\t}\n\n\t/** Parses a response against an endpoint’s response schema, considering common errors thrown from the API.\n\t * @throws {JsonParsingError} - If the response is not valid JSON.\n\t * @throws {SchemaValidationError} - If the response does not match the schema.\n\t * @throws {ApiError} - If the API responded with an error message.\n\t */\n\tasync parseResponse<T extends RpcEndpoint>(\n\t\tendpoint: T,\n\t\toptions: {\n\t\t\tresponse: Response;\n\t\t\t/**\n\t\t\t * Whether to validate the response against the schema.\n\t\t\t * This is meant more as an escape hatch for when the response is not as expected and you want to handle it separately yourself.\n\t\t\t * ⚠️ This will lead to potential type/runtime mismatch as it does not verify the response against the schema.\n\t\t\t */\n\t\t\tvalidateOut?: boolean;\n\t\t},\n\t): Promise<StandardSchemaV1.InferOutput<T['schema']['response']>> {\n\t\tconst json = await options.response.json().catch(e => {\n\t\t\tthis.logger.error(e);\n\t\t\tthrow new JsonParsingError(options.response);\n\t\t});\n\n\t\tconst validateOut = options.validateOut ?? true;\n\t\tif (!validateOut) return json as StandardSchemaV1.InferOutput<T['schema']['response']>;\n\n\t\tconst result = safeParse(endpoint.schema.response, json, 'response');\n\t\tif (!result.success) {\n\t\t\thandleApiExceptions(json, options.response.status);\n\t\t\tthrow new SchemaValidationError(result.issues, result.source);\n\t\t}\n\n\t\treturn result.output as StandardSchemaV1.InferOutput<T['schema']['response']>;\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}> & {\n\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the inputs against the schema.\n\t\t\t\t * If you want to skip validation (e.g.: already validated yourself or with `validateEndpontInputs`), set this to false.\n\t\t\t\t */\n\t\t\t\tvalidateIn?: boolean;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the response against the schema.\n\t\t\t\t * This is meant more as an escape hatch for when the response is not as expected and you want to handle it separately yourself.\n\t\t\t\t * ⚠️ This will lead to potential type/runtime mismatch as it does not verify the response against the schema.\n\t\t\t\t */\n\t\t\t\tvalidateOut?: boolean;\n\t\t\t}\n\t\t:\tnever,\n\t): Promise<StandardSchemaV1.InferOutput<T['schema']['response']>> {\n\t\ttry {\n\t\t\tconst fetchParams = this.getFetchParams(endpoint, options);\n\t\t\tconst response = await fetch(...fetchParams);\n\t\t\treturn this.parseResponse(endpoint, { response, validateOut: options.validateOut });\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 : LooseAutocomplete<T[K], NonReducibleUnknown>;\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\n/** Validates the inputs for an endpoint ahead of time\n * Useful when you need to validate and throw earlier, or use the inputs for something other than the API call.\n */\nexport function validateEndpointInputs<T extends RpcEndpoint>(\n\tendpoint: T,\n\toptions: GetSchemaValues<{ body: unknown; searchParams: unknown }>,\n) {\n\tconst validatedInputs = {\n\t\tsearchParams: undefined,\n\t\tbody: undefined,\n\t\tvalidateIn: false,\n\t} as T extends RpcEndpoint<infer _, infer __, infer ___, infer TSearch, infer TBody> ?\n\t\tGetSchemaValues<{\n\t\t\tbody: TBody;\n\t\t\tsearchParams: TSearch;\n\t\t}> & {\n\t\t\tvalidateIn: false;\n\t\t}\n\t:\tnever;\n\n\tif (endpoint.schema.searchParams) {\n\t\tvalidatedInputs.searchParams = parse(\n\t\t\tendpoint.schema.searchParams,\n\t\t\t'searchParams' in options ? options.searchParams : {},\n\t\t);\n\t}\n\n\tif (endpoint.schema.body) {\n\t\tvalidatedInputs.body = parse(endpoint.schema.body, 'body' in options ? options.body : {});\n\t}\n\n\treturn validatedInputs;\n}\n","import {\n\ttype CandidateSource,\n\ttype DuplicateCheckResult,\n\tDuplicateCheckResultSchema,\n\ttype DuplicateCheckScope,\n\ttype IdentifyInput,\n\tIdentifyInputSchema,\n\ttype IdentifyResult,\n\tIdentifyResultSchema,\n} from '@inploi/talent-bank/contract';\nimport * as v from 'valibot';\n\nimport { ENV_TO_TALENT_BANK_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger } from './sdk.logger';\n\nexport type TalentBankCheckDuplicateResult = DuplicateCheckResult;\n\nexport type TalentBankIdentifyParams = Pick<IdentifyInput, 'anonymousId' | 'email'> &\n\tPartial<Pick<IdentifyInput, 'firstName' | 'lastName' | 'phone'>> & {\n\t\t/** Caller tag — defaults to `'sdk'`. */\n\t\tsource?: CandidateSource;\n\t};\n\nexport type TalentBankIdentifyResult = IdentifyResult;\n\nexport interface TalentBankClient {\n\tcheckDuplicate(params: {\n\t\temail: string;\n\t\tjobId?: string | number;\n\t\tscope: DuplicateCheckScope;\n\t}): Promise<TalentBankCheckDuplicateResult>;\n\n\t/**\n\t * Resolve or create a Talent Bank candidate for the supplied identifier.\n\t *\n\t * This is the direct-to-Talent-Bank replacement for the old Laravel-proxied\n\t * `/log` IDENTIFY flow. The SDK calls this and then forwards the returned\n\t * `candidateId` on every subsequent analytics log so Laravel can stamp it\n\t * onto the session for attribution.\n\t *\n\t * Returns `null` if the call fails — identification is best-effort and must\n\t * never break the host page.\n\t */\n\tidentify(params: TalentBankIdentifyParams): Promise<TalentBankIdentifyResult | null>;\n}\n\nexport const createTalentBankClient = ({\n\tenvironment,\n\tpublishableKey,\n\tlogger,\n}: {\n\tenvironment: InploiSdkEnvironment;\n\tpublishableKey: string;\n\tlogger: Logger;\n}): TalentBankClient => {\n\tconst baseUrl = ENV_TO_TALENT_BANK_URL[environment];\n\n\treturn {\n\t\tasync checkDuplicate(params) {\n\t\t\ttry {\n\t\t\t\tconst searchParams = new URLSearchParams({ email: params.email, scope: params.scope });\n\t\t\t\tif (params.scope === 'job' && params.jobId != null) {\n\t\t\t\t\tsearchParams.set('job_id', String(params.jobId));\n\t\t\t\t}\n\n\t\t\t\tconst response = await fetch(`${baseUrl}/applications/check-duplicate?${searchParams}`, {\n\t\t\t\t\tmethod: 'GET',\n\t\t\t\t\theaders: { Accept: 'application/json', 'x-publishable-key': publishableKey },\n\t\t\t\t});\n\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlogger.error(`[TalentBankClient] checkDuplicate failed with status ${response.status}`);\n\t\t\t\t\treturn { isDuplicate: false };\n\t\t\t\t}\n\n\t\t\t\tconst parsed = v.safeParse(DuplicateCheckResultSchema, await response.json());\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] checkDuplicate returned an invalid response');\n\t\t\t\t\treturn { isDuplicate: false };\n\t\t\t\t}\n\n\t\t\t\treturn parsed.output;\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error('[TalentBankClient] checkDuplicate failed:', e);\n\t\t\t\treturn { isDuplicate: false };\n\t\t\t}\n\t\t},\n\n\t\tasync identify(params) {\n\t\t\ttry {\n\t\t\t\tif (!params.anonymousId) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify skipped because anonymousId is missing');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst body: IdentifyInput = {\n\t\t\t\t\temail: params.email,\n\t\t\t\t\tfirstName: params.firstName,\n\t\t\t\t\tlastName: params.lastName,\n\t\t\t\t\tphone: params.phone,\n\t\t\t\t\tanonymousId: params.anonymousId,\n\t\t\t\t\tsource: params.source ?? 'sdk',\n\t\t\t\t};\n\t\t\t\tconst parsedBody = v.safeParse(IdentifyInputSchema, body);\n\t\t\t\tif (!parsedBody.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify received invalid input');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst response = await fetch(`${baseUrl}/identify`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t\tAccept: 'application/json',\n\t\t\t\t\t\t'x-publishable-key': publishableKey,\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(parsedBody.output),\n\t\t\t\t});\n\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlogger.error(`[TalentBankClient] identify failed with status ${response.status}`);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst parsed = v.safeParse(IdentifyResultSchema, await response.json());\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify returned an invalid response');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\treturn parsed.output;\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error('[TalentBankClient] identify failed:', e);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\t};\n};\n","import { AnalyticsOnEventCallback, 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';\nimport { createTalentBankClient } from './sdk.talent-bank';\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\t/** When provided, this callback will be called with every event that is logged to the analytics service. */\n\tonEvent?: AnalyticsOnEventCallback;\n};\n\nexport function initialiseSdk({\n\tpublishableKey,\n\tenv,\n\tlogger = inploiBrandedLogger,\n\tonEvent,\n}: 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 talentBank = createTalentBankClient({ environment: env, publishableKey, logger: loggerService });\n\tconst analytics = createAnalyticsService({\n\t\trpcClient,\n\t\tlogger: loggerService,\n\t\tonEvent,\n\t\ttalentBank,\n\t});\n\n\tconst register = <P extends InploiSdkPlugin>(plugin: P): ReturnType<P> => {\n\t\treturn plugin({ logger: loggerService, apiClient, analytics, rpcClient, publishableKey, env });\n\t};\n\n\treturn { register, analytics, apiClient };\n}\n\nexport type InploiSdk = ReturnType<typeof initialiseSdk>;\n","export function ready(callback: () => void): void {\n\tif (typeof document === 'undefined') return;\n\n\tif (document.readyState === 'loading') {\n\t\tdocument.addEventListener('DOMContentLoaded', callback, { once: true });\n\t\treturn;\n\t}\n\n\tPromise.resolve().then(callback);\n}\n"],"mappings":"AAAO,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,I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ACb,OAAAL,EAAO,MAAM,kDAAkDK,EAAS,MAAM,EAAE,EACzE,KAGR,IAAMC,EAAW,YAAUM,GAAsB,MAAMP,EAAS,KAAK,CAAC,EACtE,OAAKC,EAAO,QAKLA,EAAO,QAJbN,EAAO,MAAM,0DAA0D,EAChE,KAIT,OAASQ,EAAG,CACX,OAAAR,EAAO,MAAM,sCAAuCQ,CAAC,EAC9C,IACR,CACD,CACD,CACD,ECjHO,SAASK,GAAc,CAC7B,eAAAC,EACA,IAAAC,EACA,OAAAC,EAASC,EACT,QAAAC,CACD,EAA8B,CAE7B,IAAMC,EAAYC,EAAgB,CAAE,QAASC,EAAeN,CAAG,EAAG,eAAAD,CAAe,CAAC,EAC5EQ,EAAgBN,IAAW,GAAQO,EAAYP,EAC/CQ,EAAY,IAAIC,EAAgB,CACrC,YAAaV,EACb,OAAQ,CAAE,KAAM,cAAe,IAAKD,CAAe,EACnD,OAAQQ,CACT,CAAC,EACKI,EAAaC,EAAuB,CAAE,YAAaZ,EAAK,eAAAD,EAAgB,OAAQQ,CAAc,CAAC,EAC/FM,EAAYC,EAAuB,CACxC,UAAAL,EACA,OAAQF,EACR,QAAAJ,EACA,WAAAQ,CACD,CAAC,EAMD,MAAO,CAAE,SAJoCI,GACrCA,EAAO,CAAE,OAAQR,EAAe,UAAAH,EAAW,UAAAS,EAAW,UAAAJ,EAAW,eAAAV,EAAgB,IAAAC,CAAI,CAAC,EAG3E,UAAAa,EAAW,UAAAT,CAAU,CACzC,CCnDO,SAASY,GAAMC,EAA4B,CACjD,GAAI,SAAO,SAAa,KAExB,IAAI,SAAS,aAAe,UAAW,CACtC,SAAS,iBAAiB,mBAAoBA,EAAU,CAAE,KAAM,EAAK,CAAC,EACtE,MACD,CAEA,QAAQ,QAAQ,EAAE,KAAKA,CAAQ,EAChC","names":["CONSOLE_PREFIX","CONSOLE_STYLE","inploiBrandedLogger","args","noLogging","createPlugin","pluginFn","invariant","condition","message","hasProp","data","prop","DEFAULT_FORMATTER","unauthenticatedMessage","unauthorisedMessage","ErrorWithStatus","message","status","NotFoundError","UnauthorisedError","SchemaValidationError","issues","source","sourceText","ApiError","JsonParsingError","response","ERROR_MESSAGE_KEYS","getErrorMessageFromJson","json","messages","key","hasProp","value","item","handleApiExceptions","status","message","NotFoundError","unauthenticatedMessage","UnauthorisedError","unauthorisedMessage","ApiError","createApiClient","params","defaultHeaders","pathname","options","init","response","JsonParsingError","SdkError","SchemaValidationError","isSdkError","error","ErrorClass","version","ENV_TO_API_URL","ENV_TO_TALENT_BANK_URL","ANALYTICS_VERSION","version","ANALYTICS_COOKIE_NAME","ANALYTICS_CANDIDATE_ID_STORAGE_KEY","generateUUID","c","formatCookie","value","now","ANALYTICS_COOKIE_NAME","getSessionId","searchParams","isServer","fromSearchParams","fromSessionStorage","getStoredCandidateId","stored","ANALYTICS_CANDIDATE_ID_STORAGE_KEY","setStoredCandidateId","candidateId","cookieRegex","getSessionInfo","request","href","anonymous_id","session_id","cookie","getOrCreateAnonymousId","existing","newId","generateUUID","getSessionInfoFromResponse","response","serverReferrer","referrer","analyticsLogEndpoint","typed","createAnalyticsService","rpcClient","logger","onEvent","talentBank","params","invariant","page","context","ANALYTICS_VERSION","sessionInfo","resolvedCandidateId","identifyProperties","result","payload","responseJson","newSession","e","headers","stringify","parse","schema","input","source","result","SchemaValidationError","safeParse","e","InploiRpcClient","params","ENV_TO_API_URL","endpoint","options","validateIn","searchParams","body","validateEndpointInputs","url","pathname","key","value","stringify","json","JsonParsingError","handleApiExceptions","fetchParams","response","typed","validatedInputs","DuplicateCheckResultSchema","IdentifyInputSchema","IdentifyResultSchema","v","createTalentBankClient","environment","publishableKey","logger","baseUrl","ENV_TO_TALENT_BANK_URL","params","searchParams","response","parsed","DuplicateCheckResultSchema","e","body","parsedBody","IdentifyInputSchema","IdentifyResultSchema","initialiseSdk","publishableKey","env","logger","inploiBrandedLogger","onEvent","apiClient","createApiClient","ENV_TO_API_URL","loggerService","noLogging","rpcClient","InploiRpcClient","talentBank","createTalentBankClient","analytics","createAnalyticsService","plugin","ready","callback"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inploi/sdk",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.2",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"license": "MIT",
|
|
@@ -28,11 +28,11 @@
|
|
|
28
28
|
"ts-toolbelt": "^9.6.0",
|
|
29
29
|
"tsup": "^7.2.0",
|
|
30
30
|
"@inploi/core": "1.16.3",
|
|
31
|
-
"
|
|
32
|
-
"
|
|
31
|
+
"tsconfig": "0.1.0",
|
|
32
|
+
"eslint-config-custom": "0.1.0"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@inploi/talent-bank": "github:inploi/talent-bank#
|
|
35
|
+
"@inploi/talent-bank": "github:inploi/talent-bank#a5826c57a235acedd6af2209b2ea25dc414a8cfa",
|
|
36
36
|
"@standard-schema/spec": "^1.0.0",
|
|
37
37
|
"neoqs": "^6.13.0",
|
|
38
38
|
"valibot": "^1.3.1"
|