@checktiv/sdk-web 1.8.1 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/manifest.json +12 -0
- package/dist/api-EY_fOZm-.d.ts +578 -0
- package/dist/capture-ui.d.ts +4 -4
- package/dist/capture-ui.js +4 -3
- package/dist/capture.d.ts +3 -3
- package/dist/capture.js +2 -1
- package/dist/challenge.js +1 -1
- package/dist/chunk-2SPZA3CQ.js +3 -0
- package/dist/chunk-4HIQN4KL.js +3 -0
- package/dist/chunk-C7GRMEYT.js +3 -0
- package/dist/chunk-KYV5BPCD.js +6 -0
- package/dist/chunk-LRKS6JEP.js +9 -0
- package/dist/chunk-SU6RE6UR.js +12 -0
- package/dist/chunk-T6NMRTFB.js +7 -0
- package/dist/chunk-UVTAPUGQ.js +3 -0
- package/dist/{chunk-WC6TLR42.js → chunk-WALPQ6TH.js} +2 -1
- package/dist/chunk-YK4WW4LX.js +7 -0
- package/dist/chunk-YRM5SYRT.js +8 -0
- package/dist/chunk-ZU4L3NDZ.js +3 -0
- package/dist/collect-user-info.d.ts +4 -4
- package/dist/collect-user-info.js +5 -5
- package/dist/{controller-DYXlBzQS.d.ts → controller-CO5r6vXD.d.ts} +2 -2
- package/dist/{copy-DVW_qbbM.d.ts → copy-D6Sd0BIe.d.ts} +3 -2
- package/dist/custom-form.css +1 -1
- package/dist/custom-form.d.ts +3 -3
- package/dist/custom-form.js +6 -7
- package/dist/esign/ceremony-runtime.js +7 -0
- package/dist/esign.d.ts +4 -0
- package/dist/esign.js +422 -0
- package/dist/fraud.d.ts +3 -3
- package/dist/fraud.js +4 -5
- package/dist/idv/cross-device.d.ts +3 -3
- package/dist/idv/cross-device.js +4 -4
- package/dist/idv.d.ts +3 -3
- package/dist/idv.js +12 -11
- package/dist/{index-DBJeQp6J.d.ts → index-iyKwn5_z.d.ts} +3 -3
- package/dist/index.d.ts +6 -6
- package/dist/index.js +6 -7
- package/dist/{machine-Z0b9Q7zQ.d.ts → machine-DXxarDcC.d.ts} +39 -2
- package/dist/react.d.ts +4 -4
- package/dist/react.js +7 -8
- package/dist/workspace.d.ts +3 -3
- package/dist/workspace.js +2 -1
- package/package.json +10 -3
- package/dist/api-DicBOi5f.d.ts +0 -342
- package/dist/chunk-523TT3PD.js +0 -7
- package/dist/chunk-AW7QM2QH.js +0 -6
- package/dist/chunk-BBO2X73Y.js +0 -9
- package/dist/chunk-CNHIOCUU.js +0 -5
- package/dist/chunk-LHALMQW3.js +0 -13
- package/dist/chunk-OMR5UY5H.js +0 -7
- package/dist/chunk-S24BZWVR.js +0 -3
- package/dist/chunk-S2OOEDJS.js +0 -3
package/dist/idv/cross-device.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { registerCrossDeviceOpener, createChecktivErrorEvent } from '../chunk-
|
|
2
|
-
import
|
|
3
|
-
import { withTokenRetry } from '../chunk-
|
|
1
|
+
import { registerCrossDeviceOpener, createChecktivErrorEvent } from '../chunk-KYV5BPCD.js';
|
|
2
|
+
import '../chunk-ZU4L3NDZ.js';
|
|
3
|
+
import { withTokenRetry, createChecktivError, CREDENTIAL_UNVERIFIABLE_STATUS } from '../chunk-C7GRMEYT.js';
|
|
4
4
|
import { SESSIONS_ME_PATH, dataPlaneHeaders, SESSIONS_CROSS_DEVICE_STATUS_PATH } from '../chunk-HFQJYEGZ.js';
|
|
5
5
|
import '../chunk-QFA3K5ZV.js';
|
|
6
6
|
import '../chunk-AIK7CDV6.js';
|
|
7
7
|
|
|
8
|
-
var SESSIONS_HANDOFF_MINT_PATH=`${SESSIONS_ME_PATH}/handoff`;var CROSS_DEVICE_POLL_INTERVAL_MS=2500;var CROSS_DEVICE_POLL_TOTAL_CAP_MS=15*60*1e3;var CROSS_DEVICE_REMINT_CAP=3;var defaultChunkImporter=()=>import('../cross-device.js');function preloadCrossDeviceChunk(importer=defaultChunkImporter){try{void importer().catch(()=>{});}catch{}}function openCrossDeviceOverlay(opts){const{target,onOpenCrossDevice,copy,isMobile,emit,onClose,chunkImporter=defaultChunkImporter,poll}=opts;const childContainer=document.createElement("div");target.appendChild(childContainer);let destroyed=false;let remintCount=0;let capped=false;let onCloseFired=false;const invokeOnClose=()=>{if(onCloseFired)return;onCloseFired=true;onClose?.();};const dismissOverlay=()=>{if(!onCloseFired){emit({type:"checktiv.idv.cross_device_closed"});}invokeOnClose();};const panelOnClose=onClose?dismissOverlay:void 0;let chunkHandle=null;let isCompleting=false;let currentUrl=null;let pollGen=0;let pollTimeout=null;let pollAbort=null;let capTimeout=null;const markCompleting=()=>{isCompleting=true;if(chunkHandle!==null&¤tUrl!==null){chunkHandle.update({url:currentUrl,copy,isMobile,completing:true,onBack:panelOnClose,onRefreshLink:void 0,onRetry:panelOnClose});}};const stopPoll=()=>{pollGen+=1;if(pollTimeout!==null){clearTimeout(pollTimeout);pollTimeout=null;}if(capTimeout!==null){clearTimeout(capTimeout);capTimeout=null;}if(pollAbort!==null){pollAbort.abort();pollAbort=null;}};const startPoll=()=>{if(poll===void 0)return;const intervalMs=poll.intervalMs??CROSS_DEVICE_POLL_INTERVAL_MS;const totalCapMs=poll.totalCapMs??CROSS_DEVICE_POLL_TOTAL_CAP_MS;stopPoll();const gen=pollGen;capTimeout=setTimeout(()=>{if(gen!==pollGen||destroyed)return;stopPoll();capped=true;poll.onCapped?.();},totalCapMs);const scheduleNext=()=>{if(gen!==pollGen||destroyed)return;pollTimeout=setTimeout(runTick,intervalMs);};const runTick=()=>{void(async()=>{const controller=new AbortController;pollAbort=controller;let outcome;try{outcome=await poll.checkCompletion(controller.signal);}catch{scheduleNext();return}if(gen!==pollGen||destroyed)return;if(outcome==="advanced"){stopPoll();markCompleting();poll.onComplete();return}if(outcome==="terminal"){stopPoll();poll.onTerminal?.();return}scheduleNext();})();};pollTimeout=setTimeout(runTick,intervalMs);};const renderUnavailable=()=>{emit({type:"checktiv.idv.cross_device_unavailable"});chunkHandle?.update({url:"",copy,isMobile,completing:false,onBack:panelOnClose,onRetry:panelOnClose});};const rerender=url=>{if(typeof url!=="string"||url.length===0){renderUnavailable();return}currentUrl=url;chunkHandle?.update({url,copy,isMobile,completing:isCompleting,onBack:panelOnClose,onRefreshLink:makeRefreshHandler(),onRetry:panelOnClose});};function makeRefreshHandler(currentUrl2){if(remintCount>=CROSS_DEVICE_REMINT_CAP){return void 0}return ()=>{if(destroyed)return;if(remintCount>=CROSS_DEVICE_REMINT_CAP)return;void(async()=>{remintCount+=1;let result;try{result=await onOpenCrossDevice();}catch(err){console.warn("[Checktiv] cross-device: refresh hook rejected unexpectedly.",err);if(destroyed)return;renderUnavailable();return}if(destroyed)return;if(result.kind==="unavailable"){renderUnavailable();return}rerender(result.url);})();}}function mountPanel(chunkModule,mintResult){if(destroyed)return;const okUrl=mintResult.kind==="ok"?mintResult.url:void 0;if(mintResult.kind==="unavailable"||typeof okUrl!=="string"||okUrl.length===0){emit({type:"checktiv.idv.cross_device_unavailable"});chunkHandle=chunkModule.mountCrossDevice(childContainer,{url:"",copy,isMobile,completing:false,onBack:panelOnClose,onRetry:panelOnClose});return}emit({type:"checktiv.idv.cross_device_opened"});currentUrl=okUrl;chunkHandle=chunkModule.mountCrossDevice(childContainer,{url:okUrl,copy,isMobile,completing:isCompleting,onBack:panelOnClose,onRefreshLink:makeRefreshHandler(),onRetry:panelOnClose});}function renderDoubleFaultFallback(){if(destroyed)return;childContainer.textContent="";const msg=document.createElement("div");msg.setAttribute("data-testid","cross-device-double-fault");const text=copy.unavailableMessage;if(text){const p=document.createElement("p");p.textContent=text;msg.appendChild(p);}if(onClose){const btn=document.createElement("button");btn.type="button";btn.setAttribute("data-testid","cross-device-double-fault-retry");const retryLabel=copy.mobileTryAgainLabel??"Try again";btn.textContent=retryLabel;btn.addEventListener("click",dismissOverlay);msg.appendChild(btn);}childContainer.appendChild(msg);}startPoll();void(async()=>{let chunkResult;try{chunkResult=await chunkImporter();}catch(err){console.warn("[Checktiv] cross-device: failed to load the cross-device chunk.",err);emit(createErrorEvent("sdk_load_failed"));renderDoubleFaultFallback();return}if(destroyed)return;const mintResult=await onOpenCrossDevice().catch(err=>{console.warn("[Checktiv] cross-device: onOpenCrossDevice hook threw unexpectedly.",err);return {kind:"unavailable"}});if(destroyed)return;try{mountPanel(chunkResult,mintResult);}catch(err){console.warn("[Checktiv] cross-device: failed to mount the cross-device panel.",err);emit(createErrorEvent("sdk_load_failed"));renderDoubleFaultFallback();}})();return {setCompleting(){if(destroyed)return;markCompleting();},isCapped(){return destroyed?false:capped},restartPoll(){if(destroyed)return;capped=false;startPoll();},destroy(){if(destroyed)return;destroyed=true;stopPoll();invokeOnClose();if(chunkHandle!==null){chunkHandle.destroy();chunkHandle=null;}childContainer.remove();}}}function isRecord(v){return typeof v==="object"&&v!==null}function isHttpsUrl(value){if(typeof value!=="string"||value.length===0)return false;try{return new URL(value).protocol==="https:"}catch{return false}}function parseHandoffMintUrl(body){if(!isRecord(body))return null;const handoffUrl=body.handoffUrl;return isHttpsUrl(handoffUrl)?handoffUrl:null}function createHandoffMintHook(ctx,fetchImpl){const origin=ctx.apiBaseOrigin;return async()=>{let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(origin+SESSIONS_HANDOFF_MINT_PATH,{method:"POST",headers:dataPlaneHeaders(ctx,token,{withJsonBody:true}),body:"{}"})
|
|
8
|
+
var SESSIONS_HANDOFF_MINT_PATH=`${SESSIONS_ME_PATH}/handoff`;var CROSS_DEVICE_POLL_INTERVAL_MS=2500;var CROSS_DEVICE_POLL_TOTAL_CAP_MS=15*60*1e3;var CROSS_DEVICE_REMINT_CAP=3;var defaultChunkImporter=()=>import('../cross-device.js');function preloadCrossDeviceChunk(importer=defaultChunkImporter){try{void importer().catch(()=>{});}catch{}}function openCrossDeviceOverlay(opts){const{target,onOpenCrossDevice,copy,isMobile,emit,onClose,chunkImporter=defaultChunkImporter,poll}=opts;const childContainer=document.createElement("div");target.appendChild(childContainer);let destroyed=false;let remintCount=0;let capped=false;let onCloseFired=false;const invokeOnClose=()=>{if(onCloseFired)return;onCloseFired=true;onClose?.();};const dismissOverlay=()=>{if(!onCloseFired){emit({type:"checktiv.idv.cross_device_closed"});}invokeOnClose();};const panelOnClose=onClose?dismissOverlay:void 0;let chunkHandle=null;let isCompleting=false;let currentUrl=null;let pollGen=0;let pollTimeout=null;let pollAbort=null;let capTimeout=null;const markCompleting=()=>{isCompleting=true;if(chunkHandle!==null&¤tUrl!==null){chunkHandle.update({url:currentUrl,copy,isMobile,completing:true,onBack:panelOnClose,onRefreshLink:void 0,onRetry:panelOnClose});}};const stopPoll=()=>{pollGen+=1;if(pollTimeout!==null){clearTimeout(pollTimeout);pollTimeout=null;}if(capTimeout!==null){clearTimeout(capTimeout);capTimeout=null;}if(pollAbort!==null){pollAbort.abort();pollAbort=null;}};const startPoll=()=>{if(poll===void 0)return;const intervalMs=poll.intervalMs??CROSS_DEVICE_POLL_INTERVAL_MS;const totalCapMs=poll.totalCapMs??CROSS_DEVICE_POLL_TOTAL_CAP_MS;stopPoll();const gen=pollGen;capTimeout=setTimeout(()=>{if(gen!==pollGen||destroyed)return;stopPoll();capped=true;poll.onCapped?.();},totalCapMs);const scheduleNext=()=>{if(gen!==pollGen||destroyed)return;pollTimeout=setTimeout(runTick,intervalMs);};const runTick=()=>{void(async()=>{const controller=new AbortController;pollAbort=controller;let outcome;try{outcome=await poll.checkCompletion(controller.signal);}catch{scheduleNext();return}if(gen!==pollGen||destroyed)return;if(outcome==="advanced"){stopPoll();markCompleting();poll.onComplete();return}if(outcome==="terminal"){stopPoll();poll.onTerminal?.();return}scheduleNext();})();};pollTimeout=setTimeout(runTick,intervalMs);};const renderUnavailable=()=>{emit({type:"checktiv.idv.cross_device_unavailable"});chunkHandle?.update({url:"",copy,isMobile,completing:false,onBack:panelOnClose,onRetry:panelOnClose});};const rerender=url=>{if(typeof url!=="string"||url.length===0){renderUnavailable();return}currentUrl=url;chunkHandle?.update({url,copy,isMobile,completing:isCompleting,onBack:panelOnClose,onRefreshLink:makeRefreshHandler(),onRetry:panelOnClose});};function makeRefreshHandler(currentUrl2){if(remintCount>=CROSS_DEVICE_REMINT_CAP){return void 0}return ()=>{if(destroyed)return;if(remintCount>=CROSS_DEVICE_REMINT_CAP)return;void(async()=>{remintCount+=1;let result;try{result=await onOpenCrossDevice();}catch(err){console.warn("[Checktiv] cross-device: refresh hook rejected unexpectedly.",err);if(destroyed)return;renderUnavailable();return}if(destroyed)return;if(result.kind==="unavailable"){renderUnavailable();return}rerender(result.url);})();}}function mountPanel(chunkModule,mintResult){if(destroyed)return;const okUrl=mintResult.kind==="ok"?mintResult.url:void 0;if(mintResult.kind==="unavailable"||typeof okUrl!=="string"||okUrl.length===0){emit({type:"checktiv.idv.cross_device_unavailable"});chunkHandle=chunkModule.mountCrossDevice(childContainer,{url:"",copy,isMobile,completing:false,onBack:panelOnClose,onRetry:panelOnClose});return}emit({type:"checktiv.idv.cross_device_opened"});currentUrl=okUrl;chunkHandle=chunkModule.mountCrossDevice(childContainer,{url:okUrl,copy,isMobile,completing:isCompleting,onBack:panelOnClose,onRefreshLink:makeRefreshHandler(),onRetry:panelOnClose});}function renderDoubleFaultFallback(){if(destroyed)return;childContainer.textContent="";const msg=document.createElement("div");msg.setAttribute("data-testid","cross-device-double-fault");const text=copy.unavailableMessage;if(text){const p=document.createElement("p");p.textContent=text;msg.appendChild(p);}if(onClose){const btn=document.createElement("button");btn.type="button";btn.setAttribute("data-testid","cross-device-double-fault-retry");const retryLabel=copy.mobileTryAgainLabel??"Try again";btn.textContent=retryLabel;btn.addEventListener("click",dismissOverlay);msg.appendChild(btn);}childContainer.appendChild(msg);}startPoll();void(async()=>{let chunkResult;try{chunkResult=await chunkImporter();}catch(err){console.warn("[Checktiv] cross-device: failed to load the cross-device chunk.",err);emit(createErrorEvent("sdk_load_failed"));renderDoubleFaultFallback();return}if(destroyed)return;const mintResult=await onOpenCrossDevice().catch(err=>{console.warn("[Checktiv] cross-device: onOpenCrossDevice hook threw unexpectedly.",err);return {kind:"unavailable"}});if(destroyed)return;try{mountPanel(chunkResult,mintResult);}catch(err){console.warn("[Checktiv] cross-device: failed to mount the cross-device panel.",err);emit(createErrorEvent("sdk_load_failed"));renderDoubleFaultFallback();}})();return {setCompleting(){if(destroyed)return;markCompleting();},isCapped(){return destroyed?false:capped},restartPoll(){if(destroyed)return;capped=false;startPoll();},destroy(){if(destroyed)return;destroyed=true;stopPoll();invokeOnClose();if(chunkHandle!==null){chunkHandle.destroy();chunkHandle=null;}childContainer.remove();}}}function isRecord(v){return typeof v==="object"&&v!==null}function isHttpsUrl(value){if(typeof value!=="string"||value.length===0)return false;try{return new URL(value).protocol==="https:"}catch{return false}}function parseHandoffMintUrl(body){if(!isRecord(body))return null;const handoffUrl=body.handoffUrl;return isHttpsUrl(handoffUrl)?handoffUrl:null}function createHandoffMintHook(ctx,fetchImpl){const origin=ctx.apiBaseOrigin;return async()=>{let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(origin+SESSIONS_HANDOFF_MINT_PATH,{method:"POST",headers:dataPlaneHeaders(ctx,token,{withJsonBody:true}),body:"{}"}));}catch{return {kind:"unavailable"}}if(!res.ok)return {kind:"unavailable"};let body;try{body=await res.json();}catch{return {kind:"unavailable"}}const url=parseHandoffMintUrl(body);return url===null?{kind:"unavailable"}:{kind:"ok",url}}}function parseCrossDeviceStatus(body){if(typeof body!=="object"||body===null)return null;const b=body;if(typeof b.advanced!=="boolean")return null;if(b.currentStepId!==null&&typeof b.currentStepId!=="string")return null;return {advanced:b.advanced,currentStepId:b.currentStepId}}function classifyCrossDeviceCompletion(status,originalStepId){if(status===null)return "pending";if(status.advanced===true)return "advanced";if(status.currentStepId!==null&&status.currentStepId!==originalStepId)return "advanced";return "pending"}async function checkSessionCompletion(ctx,fetchImpl,originalStepId,signal){const origin=ctx.apiBaseOrigin;let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(origin+SESSIONS_CROSS_DEVICE_STATUS_PATH,{method:"GET",headers:dataPlaneHeaders(ctx,token),signal}));}catch{return "pending"}if(res.status===CREDENTIAL_UNVERIFIABLE_STATUS)return "terminal";if(!res.ok)return "pending";let parsed;try{parsed=parseCrossDeviceStatus(await res.json());}catch{return "pending"}return classifyCrossDeviceCompletion(parsed,originalStepId)}function openManagedCrossDevice(params){const{ctx,fetchImpl,target,stepId,sessionId,copy,isMobile,emit,onClose,chunkImporter}=params;const onOpenCrossDevice=params.onOpenCrossDevice??createHandoffMintHook(ctx,fetchImpl);return openCrossDeviceOverlay({target,onOpenCrossDevice,copy,isMobile,emit,onClose,...chunkImporter!==void 0?{chunkImporter}:{},poll:{checkCompletion:signal=>checkSessionCompletion(ctx,fetchImpl,stepId,signal),onComplete:()=>emit({type:"checktiv.idv.submitted",sessionId}),onCapped:()=>emit({type:"checktiv.idv.cross_device_capped"}),onTerminal:()=>emit(createChecktivErrorEvent("session_expired"))}})}registerCrossDeviceOpener(openManagedCrossDevice);function createErrorEvent(code){return {type:"checktiv.idv.error",error:createChecktivError(code)}}
|
|
9
9
|
|
|
10
10
|
export { CROSS_DEVICE_POLL_INTERVAL_MS, CROSS_DEVICE_POLL_TOTAL_CAP_MS, CROSS_DEVICE_REMINT_CAP, checkSessionCompletion, classifyCrossDeviceCompletion, createHandoffMintHook, openCrossDeviceOverlay, openManagedCrossDevice, parseHandoffMintUrl, preloadCrossDeviceChunk };
|
package/dist/idv.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import './machine-
|
|
2
|
-
import './copy-
|
|
3
|
-
export {
|
|
1
|
+
import './machine-DXxarDcC.js';
|
|
2
|
+
import './copy-D6Sd0BIe.js';
|
|
3
|
+
export { l as CrossDeviceHandoffHook, s as IdvHandle, t as IdvMountOptions, U as REMINT_READY_TIMEOUT_MS, V as createIdv } from './api-EY_fOZm-.js';
|
|
4
4
|
import './copy-DCeQ4JKx.js';
|
package/dist/idv.js
CHANGED
|
@@ -1,19 +1,20 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
6
|
-
import { withTokenRetry } from './chunk-S2OOEDJS.js';
|
|
7
|
-
import { stepSubmitPath, dataPlaneHeaders, CAPTURE_TOKEN_MINT_PATH, isCanonicalOrigin } from './chunk-HFQJYEGZ.js';
|
|
8
|
-
import { mount } from './chunk-OMR5UY5H.js';
|
|
1
|
+
import { mount } from './chunk-YRM5SYRT.js';
|
|
2
|
+
import { IDV_ACQUISITION_WHEN_ABSENT, CURRENT_PROTOCOL_VERSION } from './chunk-T6NMRTFB.js';
|
|
3
|
+
import './chunk-NHNGQ5BB.js';
|
|
4
|
+
import { createChecktivErrorEvent, mapStateToEvent, getCrossDeviceOpener } from './chunk-KYV5BPCD.js';
|
|
5
|
+
import './chunk-ZU4L3NDZ.js';
|
|
9
6
|
import './chunk-HV2QKVJX.js';
|
|
7
|
+
import { resolveCaptureTheme } from './chunk-4HIQN4KL.js';
|
|
10
8
|
import './chunk-XOGHMNBX.js';
|
|
11
|
-
import {
|
|
12
|
-
import './chunk-
|
|
9
|
+
import { registerModule } from './chunk-GFHNOZVO.js';
|
|
10
|
+
import { resolveSession, warnWrongTokenPlane } from './chunk-YK4WW4LX.js';
|
|
13
11
|
import './chunk-IQKHRPJR.js';
|
|
12
|
+
import { assertNever } from './chunk-UBQTPS5J.js';
|
|
13
|
+
import { createChecktivError, withTokenRetry, CREDENTIAL_UNVERIFIABLE_STATUS, mapHttpStatusToError } from './chunk-C7GRMEYT.js';
|
|
14
|
+
import { stepSubmitPath, dataPlaneHeaders, CAPTURE_TOKEN_MINT_PATH, isCanonicalOrigin } from './chunk-HFQJYEGZ.js';
|
|
14
15
|
import './chunk-QFA3K5ZV.js';
|
|
15
16
|
import './chunk-AIK7CDV6.js';
|
|
16
17
|
|
|
17
|
-
var PLATFORM_BRAND_DEFAULT={primaryColor:"#2563eb",secondaryColor:"#ff5e4d",colorMode:"auto"};var SURFACE={light:{bg:"#fafaf7",surface1:"#ffffff"},dark:{bg:"#0b0c0f",surface1:"#15171c"}};var WHITE="#ffffff";var NEAR_BLACK="#0b0c0f";var ACCENT_TARGET=3;var ADAPT_STEP=.04;var ADAPT_MAX_ITERS=24;var HOVER_DELTA=.08;var SECONDARY_HUE_SHIFT=150;var HEX_RE=/^#[0-9a-fA-F]{6}$/;function toHex(r,g,b){const ch=v=>Math.max(0,Math.min(255,Math.round(v))).toString(16).padStart(2,"0");return `#${ch(r)}${ch(g)}${ch(b)}`}function parseHex(hex){if(typeof hex!=="string"||!HEX_RE.test(hex))return null;const n=Number.parseInt(hex.slice(1),16);return {r:n>>16&255,g:n>>8&255,b:n&255}}function linearize(channel){const s=channel/255;return s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4)}function relativeLuminance(rgb){return .2126*linearize(rgb.r)+.7152*linearize(rgb.g)+.0722*linearize(rgb.b)}function assessContrast(fg,bg){const f=parseHex(fg);const b=parseHex(bg);if(!f||!b)return 1;const l1=relativeLuminance(f);const l2=relativeLuminance(b);const hi=Math.max(l1,l2);const lo=Math.min(l1,l2);return (hi+.05)/(lo+.05)}function rgbToHsl({r,g,b}){const rn=r/255;const gn=g/255;const bn=b/255;const max=Math.max(rn,gn,bn);const min=Math.min(rn,gn,bn);const l=(max+min)/2;let h=0;let s=0;if(max!==min){const d=max-min;s=l>.5?d/(2-max-min):d/(max+min);switch(max){case rn:h=(gn-bn)/d+(gn<bn?6:0);break;case gn:h=(bn-rn)/d+2;break;default:h=(rn-gn)/d+4;break}h/=6;}return {h:h*360,s,l}}function hueToRgb(p,q,tRaw){let t=tRaw;if(t<0)t+=1;if(t>1)t-=1;if(t<1/6)return p+(q-p)*6*t;if(t<1/2)return q;if(t<2/3)return p+(q-p)*(2/3-t)*6;return p}function hslToRgb({h,s,l}){const hn=(h%360+360)%360/360;let r;let g;let b;if(s===0){r=g=b=l;}else {const q=l<.5?l*(1+s):l+s-l*s;const p=2*l-q;r=hueToRgb(p,q,hn+1/3);g=hueToRgb(p,q,hn);b=hueToRgb(p,q,hn-1/3);}return {r:Math.round(r*255),g:Math.round(g*255),b:Math.round(b*255)}}function deriveSecondaryHue(hex){const rgb=parseHex(hex);if(!rgb)return PLATFORM_BRAND_DEFAULT.secondaryColor;const hsl=rgbToHsl(rgb);const out=hslToRgb({...hsl,h:(hsl.h+SECONDARY_HUE_SHIFT)%360});return toHex(out.r,out.g,out.b)}function shiftLightness(hex,delta){const rgb=parseHex(hex);if(!rgb)return toHex(0,0,0);const hsl=rgbToHsl(rgb);const out=hslToRgb({...hsl,l:Math.max(0,Math.min(1,hsl.l+delta))});return toHex(out.r,out.g,out.b)}function onColorFor(bg){const white=assessContrast(WHITE,bg);const dark=assessContrast(NEAR_BLACK,bg);return white>=dark?WHITE:NEAR_BLACK}function adaptAccent(hex,surface,target,warnings,field,mode){const rgb=parseHex(hex);if(!rgb){return toHex(0,0,0)}const hsl=rgbToHsl(rgb);const lighten=relativeLuminance(parseHex(surface)??{r:255,g:255,b:255})<.5;const rawRatio=assessContrast(hex,surface);let l=hsl.l;let out=toHex(rgb.r,rgb.g,rgb.b);for(let i=0;i<ADAPT_MAX_ITERS;i+=1){if(assessContrast(out,surface)>=target)break;l=Math.max(0,Math.min(1,l+(lighten?ADAPT_STEP:-ADAPT_STEP)));const o=hslToRgb({h:hsl.h,s:hsl.s,l});out=toHex(o.r,o.g,o.b);}const finalRatio=assessContrast(out,surface);if(rawRatio<target||finalRatio<target){warnings.push({field,mode,ratio:Number(rawRatio.toFixed(2))});}return out}function deriveMode(input,mode,warnings){const surf=SURFACE[mode];const primary=adaptAccent(input.primaryColor,surf.bg,ACCENT_TARGET,warnings,"primary",mode);const rawSecondary=input.secondaryColor??deriveSecondaryHue(input.primaryColor);const secondary=adaptAccent(rawSecondary,surf.bg,ACCENT_TARGET,warnings,"secondary",mode);const primaryHover=shiftLightness(primary,mode==="light"?-HOVER_DELTA:HOVER_DELTA);const onPrimary=onColorFor(primary);const onSecondary=onColorFor(secondary);const ring=primary;return {primary,primaryHover,onPrimary,secondary,onSecondary,ring}}function toSafeBrandColors(input){if(!input||parseHex(input.primaryColor)===null){return {primaryColor:PLATFORM_BRAND_DEFAULT.primaryColor,secondaryColor:PLATFORM_BRAND_DEFAULT.secondaryColor,colorMode:PLATFORM_BRAND_DEFAULT.colorMode}}const secondaryColor=typeof input.secondaryColor==="string"&&parseHex(input.secondaryColor)!==null?input.secondaryColor:null;const colorMode="auto";return {primaryColor:input.primaryColor,secondaryColor,colorMode}}function deriveBrandTokens(input){const safe=toSafeBrandColors(input);const warnings=[];return {light:deriveMode(safe,"light",warnings),dark:deriveMode(safe,"dark",warnings),warnings}}function defaultPrefersDark(){if(typeof window==="undefined"||typeof window.matchMedia!=="function"){return false}try{return window.matchMedia("(prefers-color-scheme: dark)").matches}catch{return false}}function defaultForcedMode(){if(typeof document==="undefined")return null;const dataTheme=document.documentElement.dataset.theme;return dataTheme==="light"||dataTheme==="dark"?dataTheme:null}function brandColorsFrom(primaryColor){return {primaryColor,secondaryColor:PLATFORM_BRAND_DEFAULT.secondaryColor,colorMode:"auto"}}function resolveCaptureTheme(ctxTheme,opts={}){const prefersDark=opts.prefersDark??defaultPrefersDark;const forcedMode=opts.forcedMode??defaultForcedMode;const colorMode=forcedMode()??(prefersDark()?"dark":"light");const primaryColor=ctxTheme?.primaryColor;if(typeof primaryColor!=="string"||primaryColor.length===0){return {colorMode,brandTokens:null}}const brandTokens=deriveBrandTokens(brandColorsFrom(primaryColor))[colorMode];return {colorMode,brandTokens}}var LEASE_STORAGE_KEY_PREFIX="checktiv.idv.lease.";function isRecord(v){return typeof v==="object"&&v!==null}function storageKey(sessionId){return LEASE_STORAGE_KEY_PREFIX+sessionId}function safeLocalStorage(){try{return globalThis.localStorage??null}catch{return null}}function generateHolderDeviceId(){const c=globalThis.crypto;if(c&&typeof c.randomUUID==="function"){return c.randomUUID()}const bytes=new Uint8Array(16);c.getRandomValues(bytes);let hex="";for(const b of bytes)hex+=b.toString(16).padStart(2,"0");return hex}function loadPersistedLease(sessionId){const ls=safeLocalStorage();if(ls===null)return null;let raw;try{raw=ls.getItem(storageKey(sessionId));}catch{return null}if(raw===null)return null;let parsed;try{parsed=JSON.parse(raw);}catch{return null}if(!isRecord(parsed))return null;const{holderDeviceId,leaseGeneration}=parsed;if(typeof holderDeviceId!=="string"||holderDeviceId.length===0)return null;const gen=typeof leaseGeneration==="number"&&Number.isInteger(leaseGeneration)&&leaseGeneration>=0?leaseGeneration:void 0;return gen===void 0?{holderDeviceId}:{holderDeviceId,leaseGeneration:gen}}function persistLease(sessionId,record){const ls=safeLocalStorage();if(ls===null)return;try{ls.setItem(storageKey(sessionId),JSON.stringify(record));}catch{}}function loadOrCreatePersistedLease(sessionId){const persisted=loadPersistedLease(sessionId);if(persisted!==null)return persisted;const record={holderDeviceId:generateHolderDeviceId()};persistLease(sessionId,record);return record}var MAX_REMINTS=3;function isRecord2(v){return typeof v==="object"&&v!==null}function asMode(value){return value==="live"||value==="test"?value:null}var TEST_HINTS=["pass","review","fail","doc_quality"];function asTestHint(value){return TEST_HINTS.find(hint=>hint===value)??null}function parseMintBody(body){if(!isRecord2(body)||!isRecord2(body.data))return null;const d=body.data;const captureToken=d.capture_token;const embedOrigin=d.embed_origin;const runIndex=d.run_index;const embedContextToken=d.embed_context_token;if(typeof captureToken!=="string"||captureToken.length===0)return null;if(!isCanonicalOrigin(embedOrigin))return null;if(typeof runIndex!=="number"||!Number.isInteger(runIndex)||runIndex<0)return null;if(typeof embedContextToken!=="string"||embedContextToken.length===0)return null;const mode=asMode(d.mode);const testHint=asTestHint(d.test_hint);return {captureToken,embedOrigin,runIndex,embedContextToken,...mode!==null?{mode}:{},...testHint!==null?{testHint}:{}}}function buildCaptureSubmitBody(input){return {runIndex:input.runIndex,r2Keys:input.r2Keys,holderDeviceId:input.holderDeviceId,...input.leaseGeneration!==void 0?{leaseGeneration:input.leaseGeneration}:{}}}function createIdvTransport(ctx,opts){const fetchImpl=opts.fetchImpl??fetch;const origin=ctx.apiBaseOrigin;let embedContextToken=null;let remintCount=0;const persistedLease=loadOrCreatePersistedLease(opts.sessionId);const holderDeviceId=persistedLease.holderDeviceId;const leaseGeneration=persistedLease.leaseGeneration;async function mintToken(){const res=await withTokenRetry(ctx.tokens,token=>fetchImpl(origin+CAPTURE_TOKEN_MINT_PATH,{method:"POST",headers:dataPlaneHeaders(ctx,token,{withJsonBody:true}),body:JSON.stringify({stepId:opts.stepId})}),result=>result?.status===401);if(!res.ok){throw createChecktivError(mapHttpStatusToError(res.status))}let body;try{body=await res.json();}catch{opts.onError?.(createChecktivErrorEvent("sdk_load_failed"));throw createChecktivError("sdk_load_failed")}const parsed=parseMintBody(body);if(parsed===null){opts.onError?.(createChecktivErrorEvent("sdk_load_failed"));throw createChecktivError("sdk_load_failed")}embedContextToken=parsed.embedContextToken;return {captureToken:parsed.captureToken,embedOrigin:parsed.embedOrigin,runIndex:parsed.runIndex,...parsed.mode!==void 0?{mode:parsed.mode}:{},...parsed.testHint!==void 0?{testHint:parsed.testHint}:{}}}function getEmbedSrc(embedOrigin){if(embedContextToken===null){opts.onError?.(createChecktivErrorEvent("sdk_load_failed"));throw createChecktivError("sdk_load_failed")}return `${embedOrigin}/idv/capture?ctx=${encodeURIComponent(embedContextToken)}`}async function submit(runIndex,r2Keys){let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(origin+stepSubmitPath(opts.sessionId,opts.stepId??""),{method:"POST",headers:dataPlaneHeaders(ctx,token,{withJsonBody:true}),body:JSON.stringify(buildCaptureSubmitBody({runIndex,r2Keys,holderDeviceId,leaseGeneration}))}),result=>result?.status===401);}catch{return {ok:false,reason:"failed"}}if(res.ok)return {ok:true};if(res.status===401)return {ok:false,reason:"token_expired"};if(res.status===409)return {ok:false,reason:"capture_superseded"};if(res.status===503&&res.headers.has("Retry-After")){return {ok:false,reason:"signal_pending"}}return {ok:false,reason:"failed"}}function initPayload(){return {config:opts.config(),locale:ctx.locale,theme:resolveCaptureTheme(ctx.theme),protocolVersion:CURRENT_PROTOCOL_VERSION,...ctx.selfiePromptMap!==void 0?{selfiePromptMap:ctx.selfiePromptMap}:{},...ctx.selfieChromeCopy!==void 0?{selfieChromeCopy:ctx.selfieChromeCopy}:{}}}async function remint(){if(remintCount>=MAX_REMINTS){opts.onError?.(createChecktivErrorEvent("session_expired"));return null}remintCount+=1;try{return await mintToken()}catch{return null}}function failProtocolMismatch(){opts.onError?.(createChecktivErrorEvent("protocol_mismatch"));}return {mintToken,submit,getEmbedSrc,initPayload,remint,failProtocolMismatch}}function after(delayMs,fn){return setTimeout(fn,delayMs)}function createSyntheticIdv(opts,config,sessionId,script){const emit=e=>opts.onEvent?.(e);const delayMs=script?.stepDelayMs??0;const timers=[];let destroyed=false;function step(offsetMs,fn){timers.push(after(offsetMs,()=>{if(!destroyed)fn();}));}step(delayMs*0,()=>{emit({type:"checktiv.idv.ready",config});});if(script?.injectError!==void 0){const code=script.injectError;step(delayMs*1,()=>{emit(createChecktivErrorEvent(code));});}else {step(delayMs*1,()=>{emit({type:"checktiv.idv.phase",phase:"document_front"});});step(delayMs*2,()=>{emit({type:"checktiv.idv.submitted",sessionId});});}const destroy=()=>{if(destroyed)return;destroyed=true;for(const id of timers)clearTimeout(id);};return {destroy,unmount:destroy}}function resolveTarget(target){if(typeof target!=="string")return target;if(typeof document==="undefined")return null;return document.querySelector(target)}function toCaptureConfig(config){return {documentTypes:config.documentTypes,biometricMode:config.biometricMode,requireMrzMatch:false,requireExpiryValid:false,requireNameMatch:false,documentAuthenticity:false,...config.minAge!==void 0?{minAge:config.minAge}:{}}}var REMINT_READY_TIMEOUT_MS=15e3;function noopHandle(){return {destroy(){},unmount(){},openCrossDevice(){}}}function isCoarsePointerViewport(){return typeof window!=="undefined"&&typeof window.matchMedia==="function"&&window.matchMedia("(pointer: coarse)").matches}function createIdv(ctx,opts){const element=resolveTarget(opts.target);if(element===null){console.warn('[Checktiv] mount("idv"): no target element found. Pass an element or a selector that resolves.');return noopHandle()}const emit=e=>opts.onEvent?.(e);const fetchImpl=opts.fetchImpl??fetch;let teardown=null;let cancelled=false;let crossDeviceSession=null;let crossDeviceOverlay=null;const closeCrossDevice=()=>{if(crossDeviceOverlay!==null){crossDeviceOverlay.destroy();crossDeviceOverlay=null;}};const openCrossDevice=()=>{if(cancelled)return;if(crossDeviceOverlay!==null){if(crossDeviceOverlay.isCapped())crossDeviceOverlay.restartPoll();return}if(isCoarsePointerViewport()){console.warn('[Checktiv] mount("idv"): openCrossDevice() is a desktop affordance; ignoring the call on a touch device (the immersive capture layout already owns the phone).');return}const sess=crossDeviceSession;if(sess===null){console.warn('[Checktiv] mount("idv"): openCrossDevice() called before the session resolved.');return}const copy=opts.crossDeviceCopy;if(copy===void 0){console.warn('[Checktiv] mount("idv"): openCrossDevice() requires `crossDeviceCopy` (with `unavailableMessage`).');return}const openOverlay=getCrossDeviceOpener();if(openOverlay===null){console.warn(`[Checktiv] mount("idv"): cross-device is not enabled. Import '@checktiv/sdk-web/idv/cross-device' in your app.`);return}crossDeviceOverlay=openOverlay({ctx,fetchImpl,target:sess.element,stepId:sess.stepId,sessionId:sess.sessionId,copy,isMobile:isCoarsePointerViewport(),onOpenCrossDevice:opts.onOpenCrossDevice,emit,onClose:closeCrossDevice});};void(async()=>{try{await setupCapture(element);}catch(err){if(cancelled)return;console.warn('[Checktiv] mount("idv") setup failed.',err);emit(createChecktivErrorEvent("sdk_load_failed"));}})();async function setupCapture(element2){const resolution=await resolveSession(ctx,fetchImpl);if(cancelled)return;let session;switch(resolution.kind){case "ok":session=resolution.session;break;case "wrong_token":warnWrongTokenPlane();emit(createChecktivErrorEvent("wrong_token_type"));return;case "unresolved":emit(createChecktivErrorEvent("session_expired"));return;case "nothing_to_render":emit({type:"checktiv.idv.processing",reason:"no_renderable_step"});return;default:return assertNever(resolution)}const idvConfig=session.config;if(idvConfig===null){emit(createChecktivErrorEvent("session_expired"));return}const readyConfig={documentTypes:idvConfig.documentTypes,biometricMode:idvConfig.biometricMode};if(ctx.mode==="test"&&opts.synthetic!==void 0){const synthHandle=createSyntheticIdv(opts,readyConfig,session.sessionId,opts.synthetic);teardown=()=>synthHandle.destroy();return}const captureConfig=toCaptureConfig(idvConfig);crossDeviceSession={sessionId:session.sessionId,stepId:session.stepId,element:element2};const transport=createIdvTransport(ctx,{fetchImpl,sessionId:session.sessionId,stepId:session.stepId,config:()=>captureConfig,onError:emit});let pinnedOrigin=null;let everReady=false;const onState=state=>{if(state.kind==="ready"){pinnedOrigin=state.embedOrigin;everReady=true;}if(state.kind==="capture_error"&&state.errorKind==="protocol_mismatch"){transport.failProtocolMismatch();return}const event=mapStateToEvent(state,{config:readyConfig,sessionId:session.sessionId});if(event!==null)emit(event);};const onControllerEvent=event=>{if(event.type==="all-complete"){emit({type:"checktiv.idv.submitted",sessionId:session.sessionId});}};const handle=mount(element2,{mintToken:transport.mintToken,submit:transport.submit,getEmbedSrc:transport.getEmbedSrc,initPayload:transport.initPayload,copy:opts.copy??{},layout:opts.layout,maxWidth:opts.maxWidth,onBeforeSubmit:opts.onBeforeSubmit,onBehaviorSegment:opts.onBehaviorSegment,onState,onControllerEvent});let reminting=false;let awaitingRemintReady=false;let remintReadyTimeoutHandle=null;const clearRemintReadyTimeout=()=>{if(remintReadyTimeoutHandle!==null){clearTimeout(remintReadyTimeoutHandle);remintReadyTimeoutHandle=null;}};const armRemintReadyTimeout=()=>{clearRemintReadyTimeout();remintReadyTimeoutHandle=setTimeout(()=>{remintReadyTimeoutHandle=null;if(!awaitingRemintReady)return;if(cancelled)return;void(async()=>{const minted=await transport.remint();if(cancelled||minted===null){awaitingRemintReady=false;reminting=false;return}if(!awaitingRemintReady){reminting=false;return}const frame=element2.querySelector("iframe.idv-capture-frame");if(frame===null){awaitingRemintReady=false;reminting=false;return}armRemintReadyTimeout();frame.src=transport.getEmbedSrc(minted.embedOrigin);})();},REMINT_READY_TIMEOUT_MS);};const isCaptureReady=data=>typeof data==="object"&&data!==null&&"type"in data&&data.type==="capture:ready";const onReloadMessage=mev=>{if(pinnedOrigin===null||mev.origin!==pinnedOrigin)return;if(!everReady)return;if(!isCaptureReady(mev.data))return;const pinnedFrame=element2.querySelector("iframe.idv-capture-frame");if(pinnedFrame===null)return;if(mev.source!==null&&mev.source!==pinnedFrame.contentWindow)return;if(reminting){if(awaitingRemintReady){clearRemintReadyTimeout();awaitingRemintReady=false;reminting=false;}return}reminting=true;void(async()=>{const minted=await transport.remint();if(cancelled||minted===null){reminting=false;return}const frame=element2.querySelector("iframe.idv-capture-frame");if(frame===null){reminting=false;return}awaitingRemintReady=true;armRemintReadyTimeout();frame.src=transport.getEmbedSrc(minted.embedOrigin);})();};if(typeof window!=="undefined"){window.addEventListener("message",onReloadMessage);}teardown=()=>{clearRemintReadyTimeout();if(typeof window!=="undefined"){window.removeEventListener("message",onReloadMessage);}handle.destroy();};}const destroy=()=>{cancelled=true;closeCrossDevice();if(teardown!==null){teardown();teardown=null;}};return {destroy,unmount:destroy,openCrossDevice}}registerModule("idv",createIdv);
|
|
18
|
+
var LEASE_STORAGE_KEY_PREFIX="checktiv.idv.lease.";function isRecord(v){return typeof v==="object"&&v!==null}function storageKey(sessionId){return LEASE_STORAGE_KEY_PREFIX+sessionId}function safeLocalStorage(){try{return globalThis.localStorage??null}catch{return null}}function generateHolderDeviceId(){const c=globalThis.crypto;if(c&&typeof c.randomUUID==="function"){return c.randomUUID()}const bytes=new Uint8Array(16);c.getRandomValues(bytes);let hex="";for(const b of bytes)hex+=b.toString(16).padStart(2,"0");return hex}function loadPersistedLease(sessionId){const ls=safeLocalStorage();if(ls===null)return null;let raw;try{raw=ls.getItem(storageKey(sessionId));}catch{return null}if(raw===null)return null;let parsed;try{parsed=JSON.parse(raw);}catch{return null}if(!isRecord(parsed))return null;const{holderDeviceId,leaseGeneration}=parsed;if(typeof holderDeviceId!=="string"||holderDeviceId.length===0)return null;const gen=typeof leaseGeneration==="number"&&Number.isInteger(leaseGeneration)&&leaseGeneration>=0?leaseGeneration:void 0;return gen===void 0?{holderDeviceId}:{holderDeviceId,leaseGeneration:gen}}function persistLease(sessionId,record){const ls=safeLocalStorage();if(ls===null)return;try{ls.setItem(storageKey(sessionId),JSON.stringify(record));}catch{}}function loadOrCreatePersistedLease(sessionId){const persisted=loadPersistedLease(sessionId);if(persisted!==null)return persisted;const record={holderDeviceId:generateHolderDeviceId()};persistLease(sessionId,record);return record}var MAX_REMINTS=3;var CTX_FORWARDED_KEYS=["selfiePromptMap","selfieChromeCopy","beginScanCopy"];function pickDefined(source,keys){const out={};for(const key of keys){const value=source[key];if(value!==void 0)out[key]=value;}return out}function isRecord2(v){return typeof v==="object"&&v!==null}function asMode(value){return value==="live"||value==="test"?value:null}var TEST_HINTS=["pass","review","fail","doc_quality"];function asTestHint(value){return TEST_HINTS.find(hint=>hint===value)??null}function parseMintBody(body){if(!isRecord2(body)||!isRecord2(body.data))return null;const d=body.data;const captureToken=d.capture_token;const embedOrigin=d.embed_origin;const runIndex=d.run_index;const embedContextToken=d.embed_context_token;if(typeof captureToken!=="string"||captureToken.length===0)return null;if(!isCanonicalOrigin(embedOrigin))return null;if(typeof runIndex!=="number"||!Number.isInteger(runIndex)||runIndex<0)return null;if(typeof embedContextToken!=="string"||embedContextToken.length===0)return null;const mode=asMode(d.mode);const testHint=asTestHint(d.test_hint);return {captureToken,embedOrigin,runIndex,embedContextToken,...mode!==null?{mode}:{},...testHint!==null?{testHint}:{}}}function buildCaptureSubmitBody(input){return {runIndex:input.runIndex,r2Keys:input.r2Keys,...input.acquisition!==IDV_ACQUISITION_WHEN_ABSENT?{acquisition:input.acquisition}:{},holderDeviceId:input.holderDeviceId,...input.leaseGeneration!==void 0?{leaseGeneration:input.leaseGeneration}:{}}}function createIdvTransport(ctx,opts){const fetchImpl=opts.fetchImpl??fetch;const origin=ctx.apiBaseOrigin;let embedContextToken=null;let remintCount=0;const persistedLease=loadOrCreatePersistedLease(opts.sessionId);const holderDeviceId=persistedLease.holderDeviceId;const leaseGeneration=persistedLease.leaseGeneration;async function mintToken(){const res=await withTokenRetry(ctx.tokens,token=>fetchImpl(origin+CAPTURE_TOKEN_MINT_PATH,{method:"POST",headers:dataPlaneHeaders(ctx,token,{withJsonBody:true}),body:JSON.stringify({stepId:opts.stepId})}));if(!res.ok){throw createChecktivError(mapHttpStatusToError(res.status))}let body;try{body=await res.json();}catch{opts.onError?.(createChecktivErrorEvent("sdk_load_failed"));throw createChecktivError("sdk_load_failed")}const parsed=parseMintBody(body);if(parsed===null){opts.onError?.(createChecktivErrorEvent("sdk_load_failed"));throw createChecktivError("sdk_load_failed")}embedContextToken=parsed.embedContextToken;return {captureToken:parsed.captureToken,embedOrigin:parsed.embedOrigin,runIndex:parsed.runIndex,...parsed.mode!==void 0?{mode:parsed.mode}:{},...parsed.testHint!==void 0?{testHint:parsed.testHint}:{}}}function getEmbedSrc(embedOrigin){if(embedContextToken===null){opts.onError?.(createChecktivErrorEvent("sdk_load_failed"));throw createChecktivError("sdk_load_failed")}return `${embedOrigin}/idv/capture?ctx=${encodeURIComponent(embedContextToken)}`}async function submit(runIndex,r2Keys,acquisition=IDV_ACQUISITION_WHEN_ABSENT){let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(origin+stepSubmitPath(opts.sessionId,opts.stepId??""),{method:"POST",headers:dataPlaneHeaders(ctx,token,{withJsonBody:true}),body:JSON.stringify(buildCaptureSubmitBody({runIndex,r2Keys,acquisition,holderDeviceId,leaseGeneration}))}));}catch{return {ok:false,reason:"failed"}}if(res.ok)return {ok:true};if(res.status===CREDENTIAL_UNVERIFIABLE_STATUS)return {ok:false,reason:"token_expired"};if(res.status===409)return {ok:false,reason:"capture_superseded"};if(res.status===503&&res.headers.has("Retry-After")){return {ok:false,reason:"signal_pending"}}return {ok:false,reason:"failed"}}function initPayload(){return {config:opts.config(),locale:ctx.locale,theme:resolveCaptureTheme(ctx.theme),protocolVersion:CURRENT_PROTOCOL_VERSION,...pickDefined(ctx,CTX_FORWARDED_KEYS)}}async function remint(){if(remintCount>=MAX_REMINTS){opts.onError?.(createChecktivErrorEvent("session_expired"));return null}remintCount+=1;try{return await mintToken()}catch{return null}}function failProtocolMismatch(){opts.onError?.(createChecktivErrorEvent("protocol_mismatch"));}return {mintToken,submit,getEmbedSrc,initPayload,remint,failProtocolMismatch}}function after(delayMs,fn){return setTimeout(fn,delayMs)}function createSyntheticIdv(opts,config,sessionId,script){const emit=e=>opts.onEvent?.(e);const delayMs=script?.stepDelayMs??0;const timers=[];let destroyed=false;function step(offsetMs,fn){timers.push(after(offsetMs,()=>{if(!destroyed)fn();}));}step(delayMs*0,()=>{emit({type:"checktiv.idv.ready",config});});if(script?.injectError!==void 0){const code=script.injectError;step(delayMs*1,()=>{emit(createChecktivErrorEvent(code));});}else {step(delayMs*1,()=>{emit({type:"checktiv.idv.phase",phase:"document_front"});});step(delayMs*2,()=>{emit({type:"checktiv.idv.submitted",sessionId});});}const destroy=()=>{if(destroyed)return;destroyed=true;for(const id of timers)clearTimeout(id);};return {destroy,unmount:destroy}}function resolveTarget(target){if(typeof target!=="string")return target;if(typeof document==="undefined")return null;return document.querySelector(target)}function toCaptureConfig(config){return {documentTypes:config.documentTypes,biometricMode:config.biometricMode,allowDocumentUpload:config.allowDocumentUpload,requireMrzMatch:false,requireExpiryValid:false,requireNameMatch:false,documentAuthenticity:false,...config.minAge!==void 0?{minAge:config.minAge}:{}}}function toReadyConfig(config){const{documentTypes,biometricMode,allowDocumentUpload}=config;return {documentTypes,biometricMode,allowDocumentUpload}}var REMINT_READY_TIMEOUT_MS=15e3;function noopHandle(){return {destroy(){},unmount(){},openCrossDevice(){}}}function isCoarsePointerViewport(){return typeof window!=="undefined"&&typeof window.matchMedia==="function"&&window.matchMedia("(pointer: coarse)").matches}function createIdv(ctx,opts){const element=resolveTarget(opts.target);if(element===null){console.warn('[Checktiv] mount("idv"): no target element found. Pass an element or a selector that resolves.');return noopHandle()}const emit=e=>opts.onEvent?.(e);const fetchImpl=opts.fetchImpl??fetch;let teardown=null;let cancelled=false;let crossDeviceSession=null;let crossDeviceOverlay=null;const closeCrossDevice=()=>{if(crossDeviceOverlay!==null){crossDeviceOverlay.destroy();crossDeviceOverlay=null;}};const openCrossDevice=()=>{if(cancelled)return;if(crossDeviceOverlay!==null){if(crossDeviceOverlay.isCapped())crossDeviceOverlay.restartPoll();return}if(isCoarsePointerViewport()){console.warn('[Checktiv] mount("idv"): openCrossDevice() is a desktop affordance; ignoring the call on a touch device (the immersive capture layout already owns the phone).');return}const sess=crossDeviceSession;if(sess===null){console.warn('[Checktiv] mount("idv"): openCrossDevice() called before the session resolved.');return}const copy=opts.crossDeviceCopy;if(copy===void 0){console.warn('[Checktiv] mount("idv"): openCrossDevice() requires `crossDeviceCopy` (with `unavailableMessage`).');return}const openOverlay=getCrossDeviceOpener();if(openOverlay===null){console.warn(`[Checktiv] mount("idv"): cross-device is not enabled. Import '@checktiv/sdk-web/idv/cross-device' in your app.`);return}crossDeviceOverlay=openOverlay({ctx,fetchImpl,target:sess.element,stepId:sess.stepId,sessionId:sess.sessionId,copy,isMobile:isCoarsePointerViewport(),onOpenCrossDevice:opts.onOpenCrossDevice,emit,onClose:closeCrossDevice});};void(async()=>{try{await setupCapture(element);}catch(err){if(cancelled)return;console.warn('[Checktiv] mount("idv") setup failed.',err);emit(createChecktivErrorEvent("sdk_load_failed"));}})();async function setupCapture(element2){const resolution=await resolveSession(ctx,fetchImpl);if(cancelled)return;let session;switch(resolution.kind){case "ok":session=resolution.session;break;case "wrong_token":warnWrongTokenPlane();emit(createChecktivErrorEvent("wrong_token_type"));return;case "unresolved":emit(createChecktivErrorEvent("session_expired"));return;case "parked":emit(createChecktivErrorEvent("session_parked"));return;case "nothing_to_render":emit({type:"checktiv.idv.processing",reason:"no_renderable_step"});return;default:return assertNever(resolution)}const idvConfig=session.config;if(idvConfig===null){emit(createChecktivErrorEvent("session_expired"));return}const captureConfig=toCaptureConfig(idvConfig);const readyConfig=toReadyConfig(captureConfig);if(ctx.mode==="test"&&opts.synthetic!==void 0){const synthHandle=createSyntheticIdv(opts,readyConfig,session.sessionId,opts.synthetic);teardown=()=>synthHandle.destroy();return}crossDeviceSession={sessionId:session.sessionId,stepId:session.stepId,element:element2};const transport=createIdvTransport(ctx,{fetchImpl,sessionId:session.sessionId,stepId:session.stepId,config:()=>captureConfig,onError:emit});let pinnedOrigin=null;let everReady=false;const onState=state=>{if(state.kind==="ready"){pinnedOrigin=state.embedOrigin;everReady=true;}if(state.kind==="capture_error"&&state.errorKind==="protocol_mismatch"){transport.failProtocolMismatch();return}const event=mapStateToEvent(state,{config:readyConfig,sessionId:session.sessionId});if(event!==null)emit(event);};const onControllerEvent=event=>{if(event.type==="all-complete"){emit({type:"checktiv.idv.submitted",sessionId:session.sessionId});}};const handle=mount(element2,{mintToken:transport.mintToken,submit:transport.submit,getEmbedSrc:transport.getEmbedSrc,initPayload:transport.initPayload,copy:opts.copy??{},layout:opts.layout,maxWidth:opts.maxWidth,onBeforeSubmit:opts.onBeforeSubmit,onBehaviorSegment:opts.onBehaviorSegment,onState,onControllerEvent});let reminting=false;let awaitingRemintReady=false;let remintReadyTimeoutHandle=null;const clearRemintReadyTimeout=()=>{if(remintReadyTimeoutHandle!==null){clearTimeout(remintReadyTimeoutHandle);remintReadyTimeoutHandle=null;}};const armRemintReadyTimeout=()=>{clearRemintReadyTimeout();remintReadyTimeoutHandle=setTimeout(()=>{remintReadyTimeoutHandle=null;if(!awaitingRemintReady)return;if(cancelled)return;void(async()=>{const minted=await transport.remint();if(cancelled||minted===null){awaitingRemintReady=false;reminting=false;return}if(!awaitingRemintReady){reminting=false;return}const frame=element2.querySelector("iframe.idv-capture-frame");if(frame===null){awaitingRemintReady=false;reminting=false;return}armRemintReadyTimeout();frame.src=transport.getEmbedSrc(minted.embedOrigin);})();},REMINT_READY_TIMEOUT_MS);};const isCaptureReady=data=>typeof data==="object"&&data!==null&&"type"in data&&data.type==="capture:ready";const onReloadMessage=mev=>{if(pinnedOrigin===null||mev.origin!==pinnedOrigin)return;if(!everReady)return;if(!isCaptureReady(mev.data))return;const pinnedFrame=element2.querySelector("iframe.idv-capture-frame");if(pinnedFrame===null)return;if(mev.source!==null&&mev.source!==pinnedFrame.contentWindow)return;if(reminting){if(awaitingRemintReady){clearRemintReadyTimeout();awaitingRemintReady=false;reminting=false;}return}reminting=true;void(async()=>{const minted=await transport.remint();if(cancelled||minted===null){reminting=false;return}const frame=element2.querySelector("iframe.idv-capture-frame");if(frame===null){reminting=false;return}awaitingRemintReady=true;armRemintReadyTimeout();frame.src=transport.getEmbedSrc(minted.embedOrigin);})();};if(typeof window!=="undefined"){window.addEventListener("message",onReloadMessage);}teardown=()=>{clearRemintReadyTimeout();if(typeof window!=="undefined"){window.removeEventListener("message",onReloadMessage);}handle.destroy();};}const destroy=()=>{cancelled=true;closeCrossDevice();if(teardown!==null){teardown();teardown=null;}};return {destroy,unmount:destroy,openCrossDevice}}registerModule("idv",createIdv);
|
|
18
19
|
|
|
19
20
|
export { REMINT_READY_TIMEOUT_MS, createIdv };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ReactNode, ReactElement } from 'react';
|
|
3
3
|
import { CollectUserInfoSession, CollectUserInfoCollector } from './collect-user-info.js';
|
|
4
|
-
import {
|
|
5
|
-
import { C as CaptureLayout, a as CaptureBehaviorMessage } from './machine-
|
|
6
|
-
import { M as MountCopy } from './copy-
|
|
4
|
+
import { i as ChecktivIdvEvent, M as MountOptions, C as ChecktivInitOptions, O as ChecktivInitScope, a as ChecktivClient } from './api-EY_fOZm-.js';
|
|
5
|
+
import { C as CaptureLayout, a as CaptureBehaviorMessage } from './machine-DXxarDcC.js';
|
|
6
|
+
import { M as MountCopy } from './copy-D6Sd0BIe.js';
|
|
7
7
|
|
|
8
8
|
interface SelfServiceResendResult {
|
|
9
9
|
readonly requested: boolean;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { C as ChecktivInitOptions, T as TokenManager, a as ChecktivClient, S as SdkRegion, P as ProvisionedHandle, M as MountOptions, I as InitOptions, b as ChecktivSessions } from './api-
|
|
2
|
-
export { c as CHECKTIV_ERROR_CODES, d as ChecktivError, e as ChecktivErrorCode, f as
|
|
3
|
-
import { S as SelfServiceResendResult } from './index-
|
|
4
|
-
export { C as ChecktivIdvProps, a as ChecktivJourneyHandle, b as ChecktivJourneyProps, c as ChecktivProviderProps } from './index-
|
|
1
|
+
import { C as ChecktivInitOptions, T as TokenManager, a as ChecktivClient, S as SdkRegion, P as ProvisionedHandle, M as MountOptions, I as InitOptions, b as ChecktivSessions } from './api-EY_fOZm-.js';
|
|
2
|
+
export { c as CHECKTIV_ERROR_CODES, d as ChecktivError, e as ChecktivErrorCode, f as ChecktivEsignEvent, g as ChecktivEvent, h as ChecktivFraudEvent, i as ChecktivIdvEvent, j as ChecktivKnownErrorCode, k as ChecktivRecovery, l as CrossDeviceHandoffHook, E as EsignCopy, m as EsignHandle, n as EsignMountOptions, o as EsignState, F as FraudHandle, p as FraudMountOptions, G as GetSessionToken, q as GetSessionTokenContext, r as IdvCoachingHint, s as IdvHandle, t as IdvMountOptions, u as InvalidPublishableKeyError, v as MountCompleteResult, w as MountProvisionedOptions, x as MountScope, y as ParsedPublishableKey, R as ResolvedIdvConfig, z as SdkMode, A as SessionsCreateApplicant, B as SessionsCreateApplicantAddress, D as SessionsCreateInput, H as SessionsCreateOptions, J as SessionsCreateResult, K as SyntheticIdvScript, L as createChecktivError, N as parsePublishableKey } from './api-EY_fOZm-.js';
|
|
3
|
+
import { S as SelfServiceResendResult } from './index-iyKwn5_z.js';
|
|
4
|
+
export { C as ChecktivIdvProps, a as ChecktivJourneyHandle, b as ChecktivJourneyProps, c as ChecktivProviderProps } from './index-iyKwn5_z.js';
|
|
5
5
|
export { C as CrossDeviceCopy } from './copy-DCeQ4JKx.js';
|
|
6
|
-
import './machine-
|
|
7
|
-
import './copy-
|
|
6
|
+
import './machine-DXxarDcC.js';
|
|
7
|
+
import './copy-D6Sd0BIe.js';
|
|
8
8
|
import 'react';
|
|
9
9
|
import './collect-user-info.js';
|
|
10
10
|
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
export { init, isSessionsCreateError, mount, mountButton, sessions, version } from './chunk-
|
|
1
|
+
export { init, isSessionsCreateError, mount, mountButton, sessions, version } from './chunk-SU6RE6UR.js';
|
|
2
|
+
import './chunk-XOGHMNBX.js';
|
|
3
|
+
export { InvalidPublishableKeyError, parsePublishableKey } from './chunk-WALPQ6TH.js';
|
|
2
4
|
import './chunk-GFHNOZVO.js';
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
import './chunk-523TT3PD.js';
|
|
5
|
+
import './chunk-YK4WW4LX.js';
|
|
6
|
+
import './chunk-IQKHRPJR.js';
|
|
6
7
|
import './chunk-UBQTPS5J.js';
|
|
7
|
-
|
|
8
|
+
export { CHECKTIV_ERROR_CODES, createChecktivError } from './chunk-C7GRMEYT.js';
|
|
8
9
|
export { regionToApiBase } from './chunk-HFQJYEGZ.js';
|
|
9
|
-
import './chunk-XOGHMNBX.js';
|
|
10
|
-
import './chunk-IQKHRPJR.js';
|
|
11
10
|
import './chunk-QFA3K5ZV.js';
|
|
12
11
|
import './chunk-AIK7CDV6.js';
|
|
@@ -15,8 +15,41 @@ interface SelfieChromeCopy {
|
|
|
15
15
|
confirm?: string;
|
|
16
16
|
retake?: string;
|
|
17
17
|
}
|
|
18
|
+
interface BeginScanCopyOverrides {
|
|
19
|
+
prompt?: string;
|
|
20
|
+
label?: string;
|
|
21
|
+
cameraStartingLabel?: string;
|
|
22
|
+
cameraUnavailableNotice?: string;
|
|
23
|
+
uploadPrompt?: string;
|
|
24
|
+
uploadLabel?: string;
|
|
25
|
+
uploadSingleSideLabel?: string;
|
|
26
|
+
uploadFrontLabel?: string;
|
|
27
|
+
uploadBackLabel?: string;
|
|
28
|
+
uploadEntryLabel?: string;
|
|
29
|
+
uploadBackAction?: string;
|
|
30
|
+
uploadChangeDocumentAction?: string;
|
|
31
|
+
uploadChooseDocumentPrompt?: string;
|
|
32
|
+
documentTypePassport?: string;
|
|
33
|
+
documentTypeDriversLicense?: string;
|
|
34
|
+
documentTypeIdCard?: string;
|
|
35
|
+
documentTypeResidencePermit?: string;
|
|
36
|
+
documentTypeVisa?: string;
|
|
37
|
+
documentTypeWorkPermit?: string;
|
|
38
|
+
uploadPickAction?: string;
|
|
39
|
+
uploadReplaceAction?: string;
|
|
40
|
+
uploadKeepAction?: string;
|
|
41
|
+
uploadPreparingLabel?: string;
|
|
42
|
+
uploadAddedNotice?: string;
|
|
43
|
+
uploadBusyLabel?: string;
|
|
44
|
+
uploadIncompleteNotice?: string;
|
|
45
|
+
uploadIncompleteSingleNotice?: string;
|
|
46
|
+
uploadTooLargeNotice?: string;
|
|
47
|
+
uploadUnsupportedNotice?: string;
|
|
48
|
+
uploadUnreadableNotice?: string;
|
|
49
|
+
}
|
|
18
50
|
type DataMode = 'live' | 'test';
|
|
19
51
|
type TestHint = 'pass' | 'review' | 'fail' | 'doc_quality';
|
|
52
|
+
type IdvAcquisition = 'camera' | 'upload';
|
|
20
53
|
type CaptureLayout = 'inline' | 'immersive';
|
|
21
54
|
interface CaptureBrandTokens {
|
|
22
55
|
primary: string;
|
|
@@ -38,6 +71,7 @@ interface IdVerificationConfig {
|
|
|
38
71
|
requireExpiryValid: boolean;
|
|
39
72
|
requireNameMatch: boolean;
|
|
40
73
|
documentAuthenticity: boolean;
|
|
74
|
+
allowDocumentUpload?: boolean;
|
|
41
75
|
minAge?: number;
|
|
42
76
|
}
|
|
43
77
|
interface CaptureInitMessage {
|
|
@@ -49,12 +83,13 @@ interface CaptureInitMessage {
|
|
|
49
83
|
mode?: DataMode;
|
|
50
84
|
testHint?: TestHint;
|
|
51
85
|
protocolVersion?: number;
|
|
86
|
+
beginScanCopy?: BeginScanCopyOverrides;
|
|
52
87
|
beginScanPrompt?: string;
|
|
53
88
|
beginScanLabel?: string;
|
|
54
89
|
selfiePromptMap?: SelfiePromptMap;
|
|
55
90
|
selfieChromeCopy?: SelfieChromeCopy;
|
|
56
91
|
}
|
|
57
|
-
type CaptureInitStaticKey = 'config' | 'locale' | 'theme' | 'protocolVersion' | 'beginScanPrompt' | 'beginScanLabel' | 'selfiePromptMap' | 'selfieChromeCopy';
|
|
92
|
+
type CaptureInitStaticKey = 'config' | 'locale' | 'theme' | 'protocolVersion' | 'beginScanCopy' | 'beginScanPrompt' | 'beginScanLabel' | 'selfiePromptMap' | 'selfieChromeCopy';
|
|
58
93
|
interface IdvR2Keys {
|
|
59
94
|
front: string;
|
|
60
95
|
back?: string;
|
|
@@ -118,6 +153,7 @@ type CaptureState = {
|
|
|
118
153
|
} | {
|
|
119
154
|
kind: 'capture_error';
|
|
120
155
|
errorKind: CaptureErrorKind;
|
|
156
|
+
cameraPolicyBlocked?: true;
|
|
121
157
|
};
|
|
122
158
|
type CaptureErrorKind = Exclude<CaptureErrorCode, 'token_expired'>;
|
|
123
159
|
type CaptureAction = {
|
|
@@ -153,9 +189,10 @@ type CaptureAction = {
|
|
|
153
189
|
} | {
|
|
154
190
|
type: 'capture_error';
|
|
155
191
|
errorKind: CaptureErrorKind;
|
|
192
|
+
cameraPolicyBlocked?: true;
|
|
156
193
|
};
|
|
157
194
|
declare function reducer(state: CaptureState, action: CaptureAction): CaptureState;
|
|
158
195
|
declare function nextCapturePhaseAfterDocument(side: CaptureDocumentSide, documentTypes: IdVerificationConfig['documentTypes'], biometricMode: IdVerificationConfig['biometricMode']): CapturePhase;
|
|
159
196
|
declare function isBiometricPhase(phase: CapturePhase): boolean;
|
|
160
197
|
|
|
161
|
-
export { type CaptureLayout as C, type DataMode as D, type IdvR2Keys as I, type SdkCrossDeviceStatusResponse as S, type TestHint as T, type CaptureBehaviorMessage as a, type CoachingKind as b, type CaptureAction as c, type CaptureErrorKind as d, type CapturePhase as e, type CaptureState as f, type
|
|
198
|
+
export { type BeginScanCopyOverrides as B, type CaptureLayout as C, type DataMode as D, type IdvR2Keys as I, type SdkCrossDeviceStatusResponse as S, type TestHint as T, type CaptureBehaviorMessage as a, type CoachingKind as b, type CaptureAction as c, type CaptureErrorKind as d, type CapturePhase as e, type CaptureState as f, type IdvAcquisition as g, type CaptureInitMessage as h, isBiometricPhase as i, type CaptureInitStaticKey as j, type SelfiePromptMap as k, type SelfieChromeCopy as l, nextCapturePhaseAfterDocument as n, reducer as r };
|
package/dist/react.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import 'react';
|
|
2
2
|
import './collect-user-info.js';
|
|
3
|
-
import './api-
|
|
4
|
-
import './machine-
|
|
5
|
-
import './copy-
|
|
6
|
-
export { d as ChecktivIdv, C as ChecktivIdvProps, e as ChecktivJourney, a as ChecktivJourneyHandle, b as ChecktivJourneyProps, f as ChecktivProvider, c as ChecktivProviderProps, g as ChecktivProviderPropsBase, u as useChecktiv, h as useCollectUserInfo } from './index-
|
|
3
|
+
import './api-EY_fOZm-.js';
|
|
4
|
+
import './machine-DXxarDcC.js';
|
|
5
|
+
import './copy-D6Sd0BIe.js';
|
|
6
|
+
export { d as ChecktivIdv, C as ChecktivIdvProps, e as ChecktivJourney, a as ChecktivJourneyHandle, b as ChecktivJourneyProps, f as ChecktivProvider, c as ChecktivProviderProps, g as ChecktivProviderPropsBase, u as useChecktiv, h as useCollectUserInfo } from './index-iyKwn5_z.js';
|
|
7
7
|
import './copy-DCeQ4JKx.js';
|
package/dist/react.js
CHANGED
|
@@ -1,14 +1,13 @@
|
|
|
1
|
-
import { mount, init } from './chunk-
|
|
1
|
+
import { mount, init } from './chunk-SU6RE6UR.js';
|
|
2
|
+
import './chunk-XOGHMNBX.js';
|
|
3
|
+
import { collectUserInfo } from './chunk-LRKS6JEP.js';
|
|
4
|
+
import './chunk-WALPQ6TH.js';
|
|
2
5
|
import './chunk-GFHNOZVO.js';
|
|
3
|
-
import './chunk-
|
|
4
|
-
import
|
|
5
|
-
import './chunk-WC6TLR42.js';
|
|
6
|
-
import './chunk-523TT3PD.js';
|
|
6
|
+
import './chunk-YK4WW4LX.js';
|
|
7
|
+
import './chunk-IQKHRPJR.js';
|
|
7
8
|
import './chunk-UBQTPS5J.js';
|
|
8
|
-
import './chunk-
|
|
9
|
+
import './chunk-C7GRMEYT.js';
|
|
9
10
|
import './chunk-HFQJYEGZ.js';
|
|
10
|
-
import './chunk-XOGHMNBX.js';
|
|
11
|
-
import './chunk-IQKHRPJR.js';
|
|
12
11
|
import './chunk-QFA3K5ZV.js';
|
|
13
12
|
import './chunk-AIK7CDV6.js';
|
|
14
13
|
import { createContext, forwardRef, useRef, useImperativeHandle, useEffect, useMemo, useContext } from 'react';
|
package/dist/workspace.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { S as SdkRegion } from './api-
|
|
2
|
-
import './machine-
|
|
3
|
-
import './copy-
|
|
1
|
+
import { S as SdkRegion } from './api-EY_fOZm-.js';
|
|
2
|
+
import './machine-DXxarDcC.js';
|
|
3
|
+
import './copy-D6Sd0BIe.js';
|
|
4
4
|
import './copy-DCeQ4JKx.js';
|
|
5
5
|
|
|
6
6
|
interface WorkspaceTokenBundle {
|
package/dist/workspace.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { initTransport } from './chunk-UVTAPUGQ.js';
|
|
1
2
|
import { isCanonicalOrigin, sdkPublicSettings } from './chunk-HFQJYEGZ.js';
|
|
2
3
|
import { getServiceOrigin } from './chunk-QFA3K5ZV.js';
|
|
3
4
|
import './chunk-AIK7CDV6.js';
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
var REVIEWER_COMPONENT="reviewer";var LOADER_PROTOCOL_VERSION=1;var NAVIGATION_EVENTS=new Set(["session_complete","navigate_away"]);function parseWorkspaceInbound(data){if(typeof data!=="object"||data===null)return null;const record=data;const type=record.type;if(type==="wk:ready"){if(record.component!==REVIEWER_COMPONENT)return null;if(typeof record.sessionId!=="string"||record.sessionId.length===0)return null;if(typeof record.nonce!=="string"||record.nonce.length===0)return null;return {type:"wk:ready",component:REVIEWER_COMPONENT,sessionId:record.sessionId,nonce:record.nonce,...typeof record.protocolVersion==="number"?{protocolVersion:record.protocolVersion}:{}}}if(type==="wk:token_refresh"){return {type:"wk:token_refresh",...typeof record.protocolVersion==="number"?{protocolVersion:record.protocolVersion}:{}}}if(type==="wk:event"){if(record.component!==REVIEWER_COMPONENT)return null;const event=record.event;if(typeof event!=="string"||!NAVIGATION_EVENTS.has(event)){return null}return {type:"wk:event",component:REVIEWER_COMPONENT,event,...typeof record.protocolVersion==="number"?{protocolVersion:record.protocolVersion}:{}}}if(type==="wk:error"){const code=record.code;if(code!=="session_expired"&&code!=="protocol_mismatch"&&code!=="origin_rejected"&&code!=="nonce_mismatch"){return null}return {type:"wk:error",code,...typeof record.protocolVersion==="number"?{protocolVersion:record.protocolVersion}:{}}}return null}function makeNonce(){const c=globalThis.crypto;if(c&&typeof c.randomUUID==="function")return c.randomUUID();return `wkn_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}function buildInitMessage(dataToken,nonce){return {type:"wk:init",component:REVIEWER_COMPONENT,dataToken,nonce,protocolVersion:LOADER_PROTOCOL_VERSION}}function buildErrorMessage(code){return {type:"wk:error",code,protocolVersion:LOADER_PROTOCOL_VERSION}}function wireWorkspaceTransport(options){const{win,workspaceOrigin,currentNonce,handlers}=options;return initTransport({win,allowedOrigins:[workspaceOrigin],parse:parseWorkspaceInbound,accept:message=>{if(message.type!=="wk:ready")return true;const current=currentNonce();if(current===null)return true;return message.nonce===current},onMessage:(message,post,origin)=>{switch(message.type){case "wk:ready":handlers.onReady(message,post,origin);return;case "wk:token_refresh":handlers.onTokenRefresh(post,origin);return;case "wk:event":handlers.onNavigation(message.event,origin);return;case "wk:error":handlers.onError(message,origin);return;default:return assertNeverInbound(message)}}})}function assertNeverInbound(message){throw new Error(`Unhandled workspace inbound message: ${JSON.stringify(message)}`)}function createWorkspaceTokenPair(getToken,sessionId){let cached=null;let pending=null;let liveDataToken=null;const mint=reason=>{const p=getToken({sessionId:sessionId(),reason});void p.then(bundle=>{liveDataToken=bundle.dataToken;},()=>{});return p};const initialBundle=()=>{if(cached!==null)return cached;const p=mint("initial");cached=p;void p.catch(()=>{if(cached===p)cached=null;});return p};return {framingToken(){return initialBundle().then(b=>b.framingToken)},currentDataToken(){return liveDataToken},dataToken(){return initialBundle().then(b=>b.dataToken)},refreshDataToken(){if(pending!==null)return pending.then(b=>b.dataToken);const p=mint("refresh");pending=p;cached=p;void p.then(()=>{if(pending===p)pending=null;},()=>{if(pending===p)pending=null;if(cached===p)cached=null;});return p.then(b=>b.dataToken)}}}function resolveWorkspaceOrigin(region){return getServiceOrigin(sdkPublicSettings.apps["workspace-embed"].subdomain,"prod",region,sdkPublicSettings)}function resolveWorkspaceBaseOrigin(workspaceBaseUrl,region){if(isCanonicalOrigin(workspaceBaseUrl))return workspaceBaseUrl;return resolveWorkspaceOrigin(region)}var REVIEWER_PATH_PREFIX="/reviewer";function buildReviewerSrc(origin,sessionId,framingToken,theme){const path=`${REVIEWER_PATH_PREFIX}/${encodeURIComponent(sessionId)}`;const url=new URL(path,`${origin}/`);url.searchParams.set("ctx",framingToken);if(theme?.primaryColor!==void 0&&theme.primaryColor.length>0){url.searchParams.set("primary",theme.primaryColor);}if(theme?.colorMode!==void 0){url.searchParams.set("mode",theme.colorMode);}if(theme?.logoUrl!==void 0&&theme.logoUrl.length>0){url.searchParams.set("logo",theme.logoUrl);}if(theme?.brandName!==void 0&&theme.brandName.length>0){url.searchParams.set("brand",theme.brandName);}return url.toString()}var IFRAME_SANDBOX="allow-scripts allow-same-origin allow-downloads";function createReviewerController(deps){return {mount(options){return mountReviewer(deps,options)}}}function mountReviewer(deps,options){const doc=deps.doc??deps.win.document;const{sessionId,target,onEvent}=options;const tokens=createWorkspaceTokenPair(deps.getToken,()=>sessionId);const workspaceOrigin=resolveWorkspaceBaseOrigin(deps.workspaceBaseUrl,deps.region);let currentNonce=null;let consecutiveRefreshRejects=0;const container=doc.createElement("div");container.style.width="100%";container.style.height="100%";target.appendChild(container);const iframe=doc.createElement("iframe");iframe.setAttribute("title","Identity review");iframe.setAttribute("sandbox",IFRAME_SANDBOX);iframe.setAttribute("referrerpolicy","no-referrer");Object.assign(iframe.style,{width:"100%",height:"100%",border:"0",display:"block"});container.appendChild(iframe);let destroyed=false;let transport=null;const emit=event=>{if(destroyed)return;try{onEvent?.(event);}catch{}};const deliverInit=(dataToken,post)=>{if(destroyed)return;currentNonce=makeNonce();post(buildInitMessage(dataToken,currentNonce));};transport=wireWorkspaceTransport({win:deps.win,workspaceOrigin,currentNonce:()=>currentNonce,handlers:{onReady:(_message,post)=>{consecutiveRefreshRejects=0;if(currentNonce!==null)return;void tokens.dataToken().then(dataToken=>{if(destroyed)return;deliverInit(dataToken,post);}).catch(()=>{emit({type:"checktiv.workspace.error",code:"session_expired",recoverable:true,recovery:"retry_review"});});},onTokenRefresh:post=>{void tokens.refreshDataToken().then(fresh=>{consecutiveRefreshRejects=0;deliverInit(fresh,post);}).catch(()=>{if(destroyed)return;consecutiveRefreshRejects+=1;if(consecutiveRefreshRejects>=2){post(buildErrorMessage("session_expired"));emit({type:"checktiv.workspace.error",code:"session_expired",recoverable:true,recovery:"retry_review"});}});},onNavigation:intent=>{emit({type:"checktiv.workspace.navigate",intent});},onError:message=>{const recoverable=message.code==="session_expired";emit({type:"checktiv.workspace.error",code:message.code,recoverable,recovery:recoverable?"retry_review":"reload_host"});}}});void tokens.framingToken().then(framingToken=>{if(destroyed)return;iframe.src=buildReviewerSrc(workspaceOrigin,sessionId,framingToken,deps.theme);}).catch(()=>{emit({type:"checktiv.workspace.error",code:"session_expired",recoverable:true,recovery:"retry_review"});});return {destroy(){if(destroyed)return;destroyed=true;transport?.teardown();transport=null;container.remove();}}}function workspace(config){const controller=createReviewerController({getToken:config.getToken,region:config.region,workspaceBaseUrl:config.workspaceBaseUrl,theme:config.theme,win:window});return {mount(_component,options){return controller.mount(options)}}}
|
|
6
7
|
|
|
7
8
|
export { workspace };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@checktiv/sdk-web",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.10.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"publishConfig": {
|
|
@@ -30,6 +30,10 @@
|
|
|
30
30
|
"types": "./dist/collect-user-info.d.ts",
|
|
31
31
|
"import": "./dist/collect-user-info.js"
|
|
32
32
|
},
|
|
33
|
+
"./esign": {
|
|
34
|
+
"types": "./dist/esign.d.ts",
|
|
35
|
+
"import": "./dist/esign.js"
|
|
36
|
+
},
|
|
33
37
|
"./react": {
|
|
34
38
|
"types": "./dist/react.d.ts",
|
|
35
39
|
"import": "./dist/react.js"
|
|
@@ -64,11 +68,13 @@
|
|
|
64
68
|
"./src/idv/cross-device-cdn.ts",
|
|
65
69
|
"./src/fraud/index.ts",
|
|
66
70
|
"./src/custom-form/index.ts",
|
|
71
|
+
"./src/esign/index.ts",
|
|
67
72
|
"./src/cdn.ts",
|
|
68
73
|
"./dist/idv.js",
|
|
69
74
|
"./dist/idv/cross-device.js",
|
|
70
75
|
"./dist/fraud.js",
|
|
71
76
|
"./dist/custom-form.js",
|
|
77
|
+
"./dist/esign.js",
|
|
72
78
|
"*.css"
|
|
73
79
|
],
|
|
74
80
|
"files": [
|
|
@@ -90,15 +96,16 @@
|
|
|
90
96
|
}
|
|
91
97
|
},
|
|
92
98
|
"scripts": {
|
|
93
|
-
"build": "tsup && node scripts/generate-agent-steering.mjs && pnpm run build:embed-capture && pnpm run build:embed-challenge && pnpm run build:host-capture && pnpm run build:cross-device",
|
|
99
|
+
"build": "NODE_OPTIONS=--max-old-space-size=4096 tsup && node scripts/generate-agent-steering.mjs && pnpm run build:embed-capture && pnpm run build:embed-challenge && pnpm run build:embed-esign && pnpm run build:host-capture && pnpm run build:cross-device",
|
|
94
100
|
"build:embed-capture": "node scripts/build-embed-capture.mjs",
|
|
95
101
|
"build:embed-challenge": "node scripts/build-embed-challenge.mjs",
|
|
102
|
+
"build:embed-esign": "node scripts/build-embed-esign.mjs",
|
|
96
103
|
"build:host-capture": "node scripts/build-host-capture.mjs",
|
|
97
104
|
"build:cross-device": "node scripts/build-cross-device.mjs",
|
|
98
105
|
"test": "vitest run",
|
|
99
106
|
"typecheck": "tsc --noEmit",
|
|
100
107
|
"lint": "echo 'lint via tsc'",
|
|
101
|
-
"size": "node ../../scripts/audit-bundle-size.mjs ../../services/sdk-cdn/public/v1/sdk.js
|
|
108
|
+
"size": "node ../../scripts/audit-bundle-size.mjs ../../services/sdk-cdn/public/v1/sdk.js 119808",
|
|
102
109
|
"size:host-capture": "node ../../scripts/audit-bundle-size.mjs ../../services/sdk-cdn/public/v1/capture.js 82944",
|
|
103
110
|
"size:host-capture-ui": "node ../../scripts/audit-bundle-size.mjs ../../services/sdk-cdn/public/v1/capture-ui.js 89088",
|
|
104
111
|
"size:cross-device": "node ../../scripts/audit-bundle-size.mjs ../../services/sdk-cdn/public/v1/cross-device.js 20480",
|