@checktiv/sdk-web 1.5.0 → 1.6.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/README.md +81 -0
- package/dist/agents/AGENTS.md +2 -1
- package/dist/agents/manifest.json +1 -1
- package/dist/{api-gE16d66n.d.ts → api-DWWQGjxL.d.ts} +22 -3
- package/dist/capture-ui.css +1 -1
- package/dist/capture-ui.d.ts +5 -4
- package/dist/capture-ui.js +3 -3
- package/dist/capture.d.ts +3 -3
- package/dist/capture.js +2 -2
- package/dist/challenge.js +2 -4
- package/dist/chunk-7F7ZMYB7.js +7 -0
- package/dist/{chunk-ZXE45FN5.js → chunk-CGSNIVQF.js} +2 -2
- package/dist/chunk-D23CFGJB.js +13 -0
- package/dist/chunk-EYSE7JJ4.js +5 -0
- package/dist/chunk-JRJRXR7Q.js +7 -0
- package/dist/{chunk-ACQKQLL2.js → chunk-KK66RKPI.js} +2 -2
- package/dist/{chunk-6U53T32A.js → chunk-NHNGQ5BB.js} +3 -4
- package/dist/chunk-OC5N6W7T.js +3 -0
- package/dist/chunk-S2OOEDJS.js +3 -0
- package/dist/chunk-TORKYG3K.js +6 -0
- package/dist/chunk-YPYFPHOH.js +9 -0
- package/dist/collect-user-info.d.ts +64 -0
- package/dist/collect-user-info.js +9 -0
- package/dist/{controller-CFL3mA5e.d.ts → controller-e63nkNGE.d.ts} +1 -1
- package/dist/{copy-Dfmk11S_.d.ts → copy-CC_mrlVV.d.ts} +1 -1
- package/dist/custom-form.d.ts +3 -3
- package/dist/custom-form.js +5 -3
- package/dist/fraud.d.ts +3 -3
- package/dist/fraud.js +5 -3
- package/dist/idv/cross-device.d.ts +6 -4
- package/dist/idv/cross-device.js +5 -5
- package/dist/idv.css +1 -1
- package/dist/idv.d.ts +3 -3
- package/dist/idv.js +9 -7
- package/dist/{index-CLPKNcV9.d.ts → index-B9Gc_xWl.d.ts} +6 -4
- package/dist/index.d.ts +7 -6
- package/dist/index.js +6 -3
- package/dist/{machine-CuZalPFX.d.ts → machine-DZPN-A44.d.ts} +5 -1
- package/dist/react.d.ts +5 -4
- package/dist/react.js +9 -5
- package/dist/workspace.d.ts +3 -3
- package/dist/workspace.js +1 -1
- package/package.json +7 -3
- package/dist/chunk-3CSUYGFY.js +0 -7
- package/dist/chunk-5AQCMTZV.js +0 -6
- package/dist/chunk-7NIKMJFJ.js +0 -6
- package/dist/chunk-PZFDDSXB.js +0 -10
package/dist/idv.js
CHANGED
|
@@ -1,17 +1,19 @@
|
|
|
1
|
-
import { createChecktivErrorEvent, mapStateToEvent, getCrossDeviceOpener } from './chunk-
|
|
1
|
+
import { createChecktivErrorEvent, mapStateToEvent, getCrossDeviceOpener } from './chunk-CGSNIVQF.js';
|
|
2
2
|
import { registerModule } from './chunk-GFHNOZVO.js';
|
|
3
|
+
import { createChecktivError, mapHttpStatusToError } from './chunk-OC5N6W7T.js';
|
|
4
|
+
import { resolveSession, warnWrongTokenPlane } from './chunk-7F7ZMYB7.js';
|
|
3
5
|
import { assertNever } from './chunk-UBQTPS5J.js';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
+
import { withTokenRetry } from './chunk-S2OOEDJS.js';
|
|
7
|
+
import { stepSubmitPath, dataPlaneHeaders, CAPTURE_TOKEN_MINT_PATH, isCanonicalOrigin } from './chunk-KK66RKPI.js';
|
|
8
|
+
import { mount } from './chunk-JRJRXR7Q.js';
|
|
6
9
|
import './chunk-HV2QKVJX.js';
|
|
7
10
|
import './chunk-XOGHMNBX.js';
|
|
8
|
-
import './chunk-
|
|
9
|
-
import
|
|
11
|
+
import { CURRENT_PROTOCOL_VERSION } from './chunk-TORKYG3K.js';
|
|
12
|
+
import './chunk-NHNGQ5BB.js';
|
|
10
13
|
import './chunk-IQKHRPJR.js';
|
|
11
|
-
import { stepSubmitPath, dataPlaneHeaders, CAPTURE_TOKEN_MINT_PATH, isCanonicalOrigin } from './chunk-ACQKQLL2.js';
|
|
12
14
|
import './chunk-QFA3K5ZV.js';
|
|
13
15
|
import './chunk-AIK7CDV6.js';
|
|
14
16
|
|
|
15
|
-
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}function asTestHint(value){return value==="pass"||value==="review"||value==="fail"?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 mintMode;let mintTestHint;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;mintMode=parsed.mode;mintTestHint=parsed.testHint;return {captureToken:parsed.captureToken,embedOrigin:parsed.embedOrigin,runIndex:parsed.runIndex}}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,...mintMode!==void 0?{mode:mintMode}:{},...mintTestHint!==void 0?{testHint:mintTestHint}:{},...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)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;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,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);
|
|
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}function asTestHint(value){return value==="pass"||value==="review"||value==="fail"?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 mintMode;let mintTestHint;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;mintMode=parsed.mode;mintTestHint=parsed.testHint;return {captureToken:parsed.captureToken,embedOrigin:parsed.embedOrigin,runIndex:parsed.runIndex}}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,...mintMode!==void 0?{mode:mintMode}:{},...mintTestHint!==void 0?{testHint:mintTestHint}:{},...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);
|
|
16
18
|
|
|
17
19
|
export { REMINT_READY_TIMEOUT_MS, createIdv };
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ReactNode, ReactElement } from 'react';
|
|
3
|
-
import {
|
|
4
|
-
import { C as
|
|
5
|
-
import {
|
|
3
|
+
import { CollectUserInfoSession, CollectUserInfoCollector } from './collect-user-info.js';
|
|
4
|
+
import { g as ChecktivIdvEvent, M as MountOptions, C as ChecktivInitOptions, A as ChecktivInitScope, a as ChecktivClient } from './api-DWWQGjxL.js';
|
|
5
|
+
import { C as CaptureLayout, a as CaptureBehaviorMessage } from './machine-DZPN-A44.js';
|
|
6
|
+
import { M as MountCopy } from './copy-CC_mrlVV.js';
|
|
6
7
|
|
|
7
8
|
interface SelfServiceResendResult {
|
|
8
9
|
readonly requested: boolean;
|
|
@@ -31,5 +32,6 @@ interface ChecktivJourneyHandle {
|
|
|
31
32
|
openCrossDevice(): void;
|
|
32
33
|
}
|
|
33
34
|
declare const ChecktivJourney: react.ForwardRefExoticComponent<MountOptions & react.RefAttributes<ChecktivJourneyHandle>>;
|
|
35
|
+
declare function useCollectUserInfo(session: CollectUserInfoSession): CollectUserInfoCollector;
|
|
34
36
|
|
|
35
|
-
export { type ChecktivIdvProps as C, type SelfServiceResendResult as S, type ChecktivJourneyHandle as a, type ChecktivJourneyProps as b, type ChecktivProviderProps as c, ChecktivIdv as d, ChecktivJourney as e, ChecktivProvider as f, type ChecktivProviderPropsBase as g, useChecktiv as u };
|
|
37
|
+
export { type ChecktivIdvProps as C, type SelfServiceResendResult as S, type ChecktivJourneyHandle as a, type ChecktivJourneyProps as b, type ChecktivProviderProps as c, ChecktivIdv as d, ChecktivJourney as e, ChecktivProvider as f, type ChecktivProviderPropsBase as g, useCollectUserInfo as h, useChecktiv as u };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import { C as ChecktivInitOptions, T as TokenManager, a as ChecktivClient, P as ProvisionedHandle, M as MountOptions, I as InitOptions, b as ChecktivSessions } from './api-
|
|
2
|
-
export { c as ChecktivError, d as ChecktivErrorCode, e as ChecktivEvent, f as ChecktivFraudEvent, g as ChecktivIdvEvent, h as CrossDeviceHandoffHook, F as FraudHandle, i as FraudMountOptions, G as GetSessionToken, j as GetSessionTokenContext, k as IdvCoachingHint, l as IdvHandle, m as IdvMountOptions, n as InvalidPublishableKeyError, o as MountCompleteResult, p as MountProvisionedOptions, q as MountScope, r as ParsedPublishableKey, R as ResolvedIdvConfig, S as SdkMode, s as SdkRegion, t as SessionsCreateApplicant, u 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, P as ProvisionedHandle, M as MountOptions, I as InitOptions, b as ChecktivSessions } from './api-DWWQGjxL.js';
|
|
2
|
+
export { c as ChecktivError, d as ChecktivErrorCode, e as ChecktivEvent, f as ChecktivFraudEvent, g as ChecktivIdvEvent, h as CrossDeviceHandoffHook, F as FraudHandle, i as FraudMountOptions, G as GetSessionToken, j as GetSessionTokenContext, k as IdvCoachingHint, l as IdvHandle, m as IdvMountOptions, n as InvalidPublishableKeyError, o as MountCompleteResult, p as MountProvisionedOptions, q as MountScope, r as ParsedPublishableKey, R as ResolvedIdvConfig, S as SdkMode, s as SdkRegion, t as SessionsCreateApplicant, u as SessionsCreateApplicantAddress, v as SessionsCreateInput, w as SessionsCreateOptions, x as SessionsCreateResult, y as SyntheticIdvScript, z as parsePublishableKey } from './api-DWWQGjxL.js';
|
|
3
|
+
import { S as SelfServiceResendResult } from './index-B9Gc_xWl.js';
|
|
4
|
+
export { C as ChecktivIdvProps, a as ChecktivJourneyHandle, b as ChecktivJourneyProps, c as ChecktivProviderProps } from './index-B9Gc_xWl.js';
|
|
5
5
|
export { C as CrossDeviceCopy } from './copy-DCeQ4JKx.js';
|
|
6
|
-
import './machine-
|
|
7
|
-
import './copy-
|
|
6
|
+
import './machine-DZPN-A44.js';
|
|
7
|
+
import './copy-CC_mrlVV.js';
|
|
8
8
|
import 'react';
|
|
9
|
+
import './collect-user-info.js';
|
|
9
10
|
|
|
10
11
|
interface InitDeps {
|
|
11
12
|
tokens?: TokenManager;
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { init, mount, mountButton, sessions, version } from './chunk-D23CFGJB.js';
|
|
2
2
|
import './chunk-GFHNOZVO.js';
|
|
3
|
+
import './chunk-OC5N6W7T.js';
|
|
4
|
+
export { InvalidPublishableKeyError, parsePublishableKey } from './chunk-EYSE7JJ4.js';
|
|
5
|
+
import './chunk-7F7ZMYB7.js';
|
|
3
6
|
import './chunk-UBQTPS5J.js';
|
|
4
|
-
import './chunk-
|
|
7
|
+
import './chunk-S2OOEDJS.js';
|
|
8
|
+
import './chunk-KK66RKPI.js';
|
|
5
9
|
import './chunk-XOGHMNBX.js';
|
|
6
10
|
import './chunk-IQKHRPJR.js';
|
|
7
|
-
import './chunk-ACQKQLL2.js';
|
|
8
11
|
import './chunk-QFA3K5ZV.js';
|
|
9
12
|
import './chunk-AIK7CDV6.js';
|
|
@@ -76,6 +76,10 @@ interface CaptureBehaviorMessage {
|
|
|
76
76
|
steps: CaptureBehaviorStep[];
|
|
77
77
|
traits: CaptureBehaviorTraits;
|
|
78
78
|
}
|
|
79
|
+
interface SdkCrossDeviceStatusResponse {
|
|
80
|
+
advanced: boolean;
|
|
81
|
+
currentStepId: string | null;
|
|
82
|
+
}
|
|
79
83
|
|
|
80
84
|
type CapturePhase = 'ready' | 'document_front' | 'document_back' | 'selfie' | 'liveness' | 'uploading' | 'coaching';
|
|
81
85
|
type CoachingKind = 'move_closer' | 'move_farther' | 'reduce_glare' | 'too_dark' | 'wrong_side' | 'hold_steady';
|
|
@@ -153,4 +157,4 @@ declare function reducer(state: CaptureState, action: CaptureAction): CaptureSta
|
|
|
153
157
|
declare function nextCapturePhaseAfterDocument(side: CaptureDocumentSide, documentTypes: IdVerificationConfig['documentTypes'], biometricMode: IdVerificationConfig['biometricMode']): CapturePhase;
|
|
154
158
|
declare function isBiometricPhase(phase: CapturePhase): boolean;
|
|
155
159
|
|
|
156
|
-
export { type CaptureLayout as C, type IdvR2Keys as I, type
|
|
160
|
+
export { type CaptureLayout as C, type IdvR2Keys as I, type SdkCrossDeviceStatusResponse as S, 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 CaptureInitMessage as g, type SelfiePromptMap as h, isBiometricPhase as i, type SelfieChromeCopy as j, nextCapturePhaseAfterDocument as n, reducer as r };
|
package/dist/react.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import 'react';
|
|
2
|
-
import './
|
|
3
|
-
import './
|
|
4
|
-
import './
|
|
5
|
-
|
|
2
|
+
import './collect-user-info.js';
|
|
3
|
+
import './api-DWWQGjxL.js';
|
|
4
|
+
import './machine-DZPN-A44.js';
|
|
5
|
+
import './copy-CC_mrlVV.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-B9Gc_xWl.js';
|
|
6
7
|
import './copy-DCeQ4JKx.js';
|
package/dist/react.js
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
|
-
import { mount, init } from './chunk-
|
|
1
|
+
import { mount, init } from './chunk-D23CFGJB.js';
|
|
2
2
|
import './chunk-GFHNOZVO.js';
|
|
3
|
+
import './chunk-OC5N6W7T.js';
|
|
4
|
+
import { collectUserInfo } from './chunk-YPYFPHOH.js';
|
|
5
|
+
import './chunk-EYSE7JJ4.js';
|
|
6
|
+
import './chunk-7F7ZMYB7.js';
|
|
3
7
|
import './chunk-UBQTPS5J.js';
|
|
4
|
-
import './chunk-
|
|
8
|
+
import './chunk-S2OOEDJS.js';
|
|
9
|
+
import './chunk-KK66RKPI.js';
|
|
5
10
|
import './chunk-XOGHMNBX.js';
|
|
6
11
|
import './chunk-IQKHRPJR.js';
|
|
7
|
-
import './chunk-ACQKQLL2.js';
|
|
8
12
|
import './chunk-QFA3K5ZV.js';
|
|
9
13
|
import './chunk-AIK7CDV6.js';
|
|
10
14
|
import { createContext, forwardRef, useRef, useImperativeHandle, useEffect, useMemo, useContext } from 'react';
|
|
11
15
|
import { jsx } from 'react/jsx-runtime';
|
|
12
16
|
|
|
13
|
-
var ChecktivContext=createContext(null);function ChecktivProvider(props){if(typeof window==="undefined")return null;return jsx(ProviderImpl,{...props})}function ProviderImpl(props){const{getSessionToken,theme,locale,children}=props;const scope="publishableKey"in props?{publishableKey:props.publishableKey}:{region:props.region,mode:props.mode};const pk="publishableKey"in props?props.publishableKey:void 0;const region="publishableKey"in props?void 0:props.region;const mode="publishableKey"in props?void 0:props.mode;const themeKey=JSON.stringify(theme??null);const client=useMemo(()=>init({...scope,getSessionToken,theme,locale}),[pk,region,mode,getSessionToken,themeKey,locale]);return jsx(ChecktivContext.Provider,{value:client,children})}function useChecktiv(){const client=useContext(ChecktivContext);if(client===null){throw new Error("useChecktiv must be used within a <ChecktivProvider>. Wrap the component tree that needs the Checktiv client with <ChecktivProvider>.")}return client}function ChecktivIdv({onEvent,copy,layout,onBeforeSubmit,onBehaviorSegment}){const client=useChecktiv();const containerRef=useRef(null);const handleRef=useRef(null);const mountConfigRef=useRef({copy,layout,onBeforeSubmit,onBehaviorSegment});const onEventRef=useRef(onEvent);onEventRef.current=onEvent;useEffect(()=>{if(typeof window==="undefined")return;if(containerRef.current===null)return;if(handleRef.current!==null)return;const mountConfig=mountConfigRef.current;handleRef.current=client.mount("idv",{target:containerRef.current,onEvent:e=>onEventRef.current(e),...mountConfig.copy!==void 0?{copy:mountConfig.copy}:{},...mountConfig.layout!==void 0?{layout:mountConfig.layout}:{},...mountConfig.onBeforeSubmit!==void 0?{onBeforeSubmit:mountConfig.onBeforeSubmit}:{},...mountConfig.onBehaviorSegment!==void 0?{onBehaviorSegment:mountConfig.onBehaviorSegment}:{}});return ()=>{handleRef.current?.destroy();handleRef.current=null;}},[client]);if(typeof window==="undefined")return null;return jsx("div",{ref:containerRef})}var ChecktivJourneyImpl=(props,ref)=>{const containerRef=useRef(null);const handleRef=useRef(null);const scope="publishableKey"in props?{publishableKey:props.publishableKey}:{region:props.region,mode:props.mode};const pk="publishableKey"in props?props.publishableKey:void 0;const region="publishableKey"in props?void 0:props.region;const mode="publishableKey"in props?void 0:props.mode;const journeyConfig={fetchToken:props.fetchToken,onConsent:props.onConsent,layout:props.layout,theme:props.theme,copy:props.copy,resumeKey:props.resumeKey,shortCode:props.shortCode,apiBase:props.apiBase,fetchImpl:props.fetchImpl,crossDeviceCopy:props.crossDeviceCopy,onOpenCrossDevice:props.onOpenCrossDevice};const mountConfigRef=useRef(journeyConfig);mountConfigRef.current=journeyConfig;const onEventRef=useRef(props.onEvent);onEventRef.current=props.onEvent;const onCompleteRef=useRef(props.onComplete);onCompleteRef.current=props.onComplete;useImperativeHandle(ref,()=>({requestResend:confirmEmail=>handleRef.current?.requestResend(confirmEmail)??Promise.resolve({requested:false}),openCrossDevice:()=>handleRef.current?.openCrossDevice?.()}),[]);useEffect(()=>{if(typeof window==="undefined")return;if(containerRef.current===null)return;if(handleRef.current!==null)return;const cfg=mountConfigRef.current;const opts={...scope,fetchToken:cfg.fetchToken,onEvent:e=>onEventRef.current?.(e),onComplete:r=>onCompleteRef.current?.(r),...cfg.onConsent!==void 0?{onConsent:cfg.onConsent}:{},...cfg.layout!==void 0?{layout:cfg.layout}:{},...cfg.theme!==void 0?{theme:cfg.theme}:{},...cfg.copy!==void 0?{copy:cfg.copy}:{},...cfg.resumeKey!==void 0?{resumeKey:cfg.resumeKey}:{},...cfg.shortCode!==void 0?{shortCode:cfg.shortCode}:{},...cfg.apiBase!==void 0?{apiBase:cfg.apiBase}:{},...cfg.fetchImpl!==void 0?{fetchImpl:cfg.fetchImpl}:{},...cfg.crossDeviceCopy!==void 0?{crossDeviceCopy:cfg.crossDeviceCopy}:{},...cfg.onOpenCrossDevice!==void 0?{onOpenCrossDevice:cfg.onOpenCrossDevice}:{}};handleRef.current=mount(containerRef.current,opts);return ()=>{handleRef.current?.destroy();handleRef.current=null;}},[pk,region,mode]);if(typeof window==="undefined")return null;return jsx("div",{ref:containerRef})};var ChecktivJourney=forwardRef(ChecktivJourneyImpl);
|
|
17
|
+
var ChecktivContext=createContext(null);function ChecktivProvider(props){if(typeof window==="undefined")return null;return jsx(ProviderImpl,{...props})}function ProviderImpl(props){const{getSessionToken,theme,locale,children}=props;const scope="publishableKey"in props?{publishableKey:props.publishableKey}:{region:props.region,mode:props.mode};const pk="publishableKey"in props?props.publishableKey:void 0;const region="publishableKey"in props?void 0:props.region;const mode="publishableKey"in props?void 0:props.mode;const themeKey=JSON.stringify(theme??null);const client=useMemo(()=>init({...scope,getSessionToken,theme,locale}),[pk,region,mode,getSessionToken,themeKey,locale]);return jsx(ChecktivContext.Provider,{value:client,children})}function useChecktiv(){const client=useContext(ChecktivContext);if(client===null){throw new Error("useChecktiv must be used within a <ChecktivProvider>. Wrap the component tree that needs the Checktiv client with <ChecktivProvider>.")}return client}function ChecktivIdv({onEvent,copy,layout,onBeforeSubmit,onBehaviorSegment}){const client=useChecktiv();const containerRef=useRef(null);const handleRef=useRef(null);const mountConfigRef=useRef({copy,layout,onBeforeSubmit,onBehaviorSegment});const onEventRef=useRef(onEvent);onEventRef.current=onEvent;useEffect(()=>{if(typeof window==="undefined")return;if(containerRef.current===null)return;if(handleRef.current!==null)return;const mountConfig=mountConfigRef.current;handleRef.current=client.mount("idv",{target:containerRef.current,onEvent:e=>onEventRef.current(e),...mountConfig.copy!==void 0?{copy:mountConfig.copy}:{},...mountConfig.layout!==void 0?{layout:mountConfig.layout}:{},...mountConfig.onBeforeSubmit!==void 0?{onBeforeSubmit:mountConfig.onBeforeSubmit}:{},...mountConfig.onBehaviorSegment!==void 0?{onBehaviorSegment:mountConfig.onBehaviorSegment}:{}});return ()=>{handleRef.current?.destroy();handleRef.current=null;}},[client]);if(typeof window==="undefined")return null;return jsx("div",{ref:containerRef})}var ChecktivJourneyImpl=(props,ref)=>{const containerRef=useRef(null);const handleRef=useRef(null);const scope="publishableKey"in props?{publishableKey:props.publishableKey}:{region:props.region,mode:props.mode};const pk="publishableKey"in props?props.publishableKey:void 0;const region="publishableKey"in props?void 0:props.region;const mode="publishableKey"in props?void 0:props.mode;const journeyConfig={fetchToken:props.fetchToken,onConsent:props.onConsent,layout:props.layout,theme:props.theme,copy:props.copy,resumeKey:props.resumeKey,shortCode:props.shortCode,apiBase:props.apiBase,fetchImpl:props.fetchImpl,crossDeviceCopy:props.crossDeviceCopy,onOpenCrossDevice:props.onOpenCrossDevice,maxWidth:props.maxWidth};const mountConfigRef=useRef(journeyConfig);mountConfigRef.current=journeyConfig;const onEventRef=useRef(props.onEvent);onEventRef.current=props.onEvent;const onCompleteRef=useRef(props.onComplete);onCompleteRef.current=props.onComplete;useImperativeHandle(ref,()=>({requestResend:confirmEmail=>handleRef.current?.requestResend(confirmEmail)??Promise.resolve({requested:false}),openCrossDevice:()=>handleRef.current?.openCrossDevice?.()}),[]);useEffect(()=>{if(typeof window==="undefined")return;if(containerRef.current===null)return;if(handleRef.current!==null)return;const cfg=mountConfigRef.current;const opts={...scope,fetchToken:cfg.fetchToken,onEvent:e=>onEventRef.current?.(e),onComplete:r=>onCompleteRef.current?.(r),...cfg.onConsent!==void 0?{onConsent:cfg.onConsent}:{},...cfg.layout!==void 0?{layout:cfg.layout}:{},...cfg.theme!==void 0?{theme:cfg.theme}:{},...cfg.copy!==void 0?{copy:cfg.copy}:{},...cfg.resumeKey!==void 0?{resumeKey:cfg.resumeKey}:{},...cfg.shortCode!==void 0?{shortCode:cfg.shortCode}:{},...cfg.apiBase!==void 0?{apiBase:cfg.apiBase}:{},...cfg.fetchImpl!==void 0?{fetchImpl:cfg.fetchImpl}:{},...cfg.crossDeviceCopy!==void 0?{crossDeviceCopy:cfg.crossDeviceCopy}:{},...cfg.onOpenCrossDevice!==void 0?{onOpenCrossDevice:cfg.onOpenCrossDevice}:{},...cfg.maxWidth!==void 0?{maxWidth:cfg.maxWidth}:{}};handleRef.current=mount(containerRef.current,opts);return ()=>{handleRef.current?.destroy();handleRef.current=null;}},[pk,region,mode]);if(typeof window==="undefined")return null;return jsx("div",{ref:containerRef})};var ChecktivJourney=forwardRef(ChecktivJourneyImpl);function useCollectUserInfo(session){const sessionRef=useRef(session);return useMemo(()=>collectUserInfo({session:sessionRef.current}),[])}
|
|
14
18
|
|
|
15
|
-
export { ChecktivIdv, ChecktivJourney, ChecktivProvider, useChecktiv };
|
|
19
|
+
export { ChecktivIdv, ChecktivJourney, ChecktivProvider, useChecktiv, useCollectUserInfo };
|
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-DWWQGjxL.js';
|
|
2
|
+
import './machine-DZPN-A44.js';
|
|
3
|
+
import './copy-CC_mrlVV.js';
|
|
4
4
|
import './copy-DCeQ4JKx.js';
|
|
5
5
|
|
|
6
6
|
interface WorkspaceTokenBundle {
|
package/dist/workspace.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@checktiv/sdk-web",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"//publishConfigNameNote": "pnpm does NOT apply `publishConfig.name` (the publishConfig override list at https://pnpm.io/package_json#publishconfig excludes `name`; `pnpm pack` leaves the tarball `name` as the workspace name). The published `name` rewrite to `@checktiv/sdk-web` happens in the root `.pnpmfile.cjs` `beforePacking` hook (pnpm >= 10.28) instead — see that file's header. This field is retained ONLY as documentation of intent; the hook deletes it from the packed manifest. The packed-name gate in __tests__/dist-shape.test.ts reads the REAL extracted tarball, not this field.",
|
|
@@ -31,6 +31,10 @@
|
|
|
31
31
|
"import": "./dist/custom-form.js"
|
|
32
32
|
},
|
|
33
33
|
"./custom-form/style.css": "./dist/custom-form.css",
|
|
34
|
+
"./collect-user-info": {
|
|
35
|
+
"types": "./dist/collect-user-info.d.ts",
|
|
36
|
+
"import": "./dist/collect-user-info.js"
|
|
37
|
+
},
|
|
34
38
|
"./react": {
|
|
35
39
|
"types": "./dist/react.d.ts",
|
|
36
40
|
"import": "./dist/react.js"
|
|
@@ -115,8 +119,8 @@
|
|
|
115
119
|
"vitest": "^4.1.9",
|
|
116
120
|
"@rf/config": "0.0.0",
|
|
117
121
|
"@rf/iam-core": "0.0.1",
|
|
118
|
-
"@rf/
|
|
119
|
-
"@rf/
|
|
122
|
+
"@rf/theme": "0.1.0",
|
|
123
|
+
"@rf/schemas": "0.1.0"
|
|
120
124
|
},
|
|
121
125
|
"scripts": {
|
|
122
126
|
"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",
|
package/dist/chunk-3CSUYGFY.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { u } from './chunk-HV2QKVJX.js';
|
|
2
|
-
import { R, k } from './chunk-XOGHMNBX.js';
|
|
3
|
-
import { createCaptureController, isBiometricPhase, coachingKindForState } from './chunk-5AQCMTZV.js';
|
|
4
|
-
|
|
5
|
-
function coachingFallback(kind){switch(kind){case "move_closer":return "Move a little closer.";case "move_farther":return "Move a little farther away.";case "reduce_glare":return "Reduce glare: tilt away from bright light.";case "too_dark":return "Find a brighter, well-lit spot.";case "wrong_side":return "Show the other side of your document.";case "hold_steady":return "Hold steady and keep everything in frame."}}function statusFallback(phase){switch(phase){case "ready":return "Getting the camera ready.";case "document_front":return "Position the front of your document in the frame.";case "document_back":return "Now show the back of your document.";case "selfie":return "Center your face in the frame.";case "liveness":return "Follow the on-screen prompts to confirm it is you.";case "uploading":return "Uploading. This takes a few seconds.";case "coaching":return "Hold steady and keep everything in frame."}}function errorFallback(kind){switch(kind){case "cv_gate_failed":return "We could not read that capture. Please try again in good lighting.";case "upload_failed":return "The upload did not finish. Check your connection and try again.";case "sdk_load_failed":return "The capture tools could not load. Refresh, or continue on your phone.";case "biometric_unsupported":return "This device cannot run the selfie check. Please continue on your phone.";case "camera_unsupported":return "Your camera does not meet the minimum resolution for capture. Please continue on your phone.";case "selfie_camera_denied":return "Camera access was blocked. Allow the camera, or continue on your phone.";case "liveness_camera_denied":return "Camera access was blocked. Allow the camera, or continue on your phone.";case "liveness_timeout":return "The check timed out. Please try again.";case "liveness_server_error":return "Something went wrong on our side. Please try again.";case "liveness_runtime_error":return "The check could not run. Refresh and try again.";case "liveness_cancelled":return "The check was canceled. Please try again when you are ready.";case "protocol_mismatch":return "This version of the verification tool is no longer supported. Please contact the operator to continue.";default:{const _exhaustive=kind;return _exhaustive}}}function terminalFallback(kind){switch(kind){case "mint_error":return "We could not start verification. Please try again.";case "submit_error":return "We could not submit your capture. Please try again.";case "token_expired":return "This step expired for your security. Please refresh to start again.";case "capture_superseded":return "Verification is active on another device. Finish there, or select Try again to continue here.";default:{const _exhaustive=kind;return _exhaustive}}}var fallbackCopy={cvReject:(_attemptIndex,kind)=>`We could not use that photo. ${coachingFallback(kind)}`,error:errorFallback,status:statusFallback,coaching:coachingFallback,terminal:terminalFallback,tryAgain:()=>"Try again",frameTitle:()=>"Identity verification capture"};var IFRAME_SANDBOX="allow-scripts allow-same-origin";function phaseOf(state){if(state.kind==="capturing")return state.phase;return "ready"}function statusLine(state,copy){if(state.kind==="capturing"&&state.phase==="coaching"&&state.coaching!==null){return (copy.coaching??fallbackCopy.coaching)(state.coaching)}return (copy.status??fallbackCopy.status)(phaseOf(state))}function CvRejectAlert({reason,attemptIndex,copy}){const kind=coachingKindForState(reason);const text=(copy.cvReject??fallbackCopy.cvReject)(attemptIndex,kind);return u("div",{role:"status","data-testid":"idv-cv-reject-alert",className:"idv-capture-cv-reject",style:"margin-bottom: 0.75rem;",children:text})}function CaptureFrame(props){const{colorMode="light"}=props;return u("div",{className:"idv-capture-root","data-color-mode":colorMode,children:renderCaptureArm(props)})}function renderCaptureArm({state,attemptIndex,getEmbedSrc,onTryAgain,copy,layout="inline",immersiveActive=false,colorMode="light"}){switch(state.kind){case "minting":return u("div",{children:[u("div",{"data-testid":"idv-capture-skeleton","data-color-mode":colorMode,className:"idv-capture-skeleton idv-capture-skeleton--document idv-capture-skeleton--standalone","aria-hidden":"true"}),u("p",{className:"idv-capture-status","aria-live":"polite",children:(copy.status??fallbackCopy.status)("ready")})]});case "mint_error":case "submit_error":case "token_expired":case "capture_superseded":return u("div",{className:"idv-capture-error",role:"alert",children:[u("p",{children:(copy.terminal??fallbackCopy.terminal)(state.kind)}),u("button",{type:"button",onClick:onTryAgain,className:"idv-capture-retry",children:copy.tryAgain??fallbackCopy.tryAgain()})]});case "capture_error":{const errorKind=state.errorKind;const terminal=errorKind==="protocol_mismatch";return u("div",{className:"idv-capture-error",role:"alert",children:[u("p",{children:(copy.error??fallbackCopy.error)(errorKind)}),!terminal&&u("button",{type:"button",onClick:onTryAgain,className:"idv-capture-retry",children:copy.tryAgain??fallbackCopy.tryAgain()})]})}case "submitting":case "submit_pending":return u("p",{className:"idv-capture-status",children:(copy.status??fallbackCopy.status)("uploading")});case "waiting_for_init":case "ready":case "capturing":{const phase=phaseOf(state);const biometric=isBiometricPhase(phase);const frameClass=biometric?"idv-capture-frame idv-capture-frame--biometric":"idv-capture-frame";const reason=state.kind==="capturing"?state.lastCvRejectReason:null;const biometricLoading=biometric&&state.kind==="capturing"&&state.biometricLoading;const initialLoading=state.kind==="waiting_for_init";const showSkeleton=biometricLoading||initialLoading;const skeletonClass=initialLoading?"idv-capture-skeleton idv-capture-skeleton--document":"idv-capture-skeleton";const embedSrc=getEmbedSrc(state.embedOrigin);const immersive=layout==="immersive";const wrapperClass=immersive?"idv-capture-active idv-capture-immersive":"idv-capture-active";const frameTitle=copy.frameTitle??fallbackCopy.frameTitle();let iframeEl=null;const focusFrame=()=>iframeEl?.focus();return u("div",{className:wrapperClass,"data-color-mode":colorMode,role:immersiveActive?"dialog":void 0,"aria-modal":immersiveActive?"true":void 0,"aria-label":immersiveActive?frameTitle:void 0,children:[reason!==null&&u(CvRejectAlert,{reason,attemptIndex,copy}),showSkeleton&&u("div",{"data-testid":"idv-capture-skeleton","data-color-mode":colorMode,className:skeletonClass,"aria-hidden":"true"}),immersiveActive&&u("div",{className:"idv-capture-sentinel",tabIndex:0,onFocus:focusFrame}),u("iframe",{ref:el=>{iframeEl=el;},className:frameClass,title:frameTitle,src:embedSrc,allow:"camera",sandbox:IFRAME_SANDBOX}),immersiveActive&&u("div",{className:"idv-capture-sentinel",tabIndex:0,onFocus:focusFrame}),u("p",{className:"idv-capture-status","aria-live":"polite",children:statusLine(state,copy)})]})}default:{const _exhaustive=state;return _exhaustive}}}var IMMERSIVE_MEDIA="(pointer: coarse) and (max-width: 640px), (pointer: coarse) and (max-height: 640px)";function matchesImmersive(){return typeof window!=="undefined"&&typeof window.matchMedia==="function"&&window.matchMedia(IMMERSIVE_MEDIA).matches}function subscribeImmersive(cb){if(typeof window==="undefined"||typeof window.matchMedia!=="function"){return ()=>{}}const mql=window.matchMedia(IMMERSIVE_MEDIA);mql.addEventListener("change",cb);return ()=>{mql.removeEventListener("change",cb);}}function mount(element,options){const{copy,layout,onState,onControllerEvent,...deps}=options;const resolvedInitPayload=deps.initPayload();const controller=createCaptureController({...deps,initPayload:()=>resolvedInitPayload,getIframe:()=>element.querySelector("iframe.idv-capture-frame")});let destroyed=false;let state={kind:"minting"};let attemptIndex=0;const computeImmersiveActive=()=>layout==="immersive"&&matchesImmersive();let immersiveActive=computeImmersiveActive();let prevFocusable=false;let prevStateKind=state.kind;const IMMERSIVE_FILL_TOLERANCE_PX=2;let selfCheckRaf;let selfCheckWarned=false;const scheduleImmersiveSelfCheck=()=>{if(typeof requestAnimationFrame!=="function")return;if(selfCheckRaf!==void 0&&typeof cancelAnimationFrame==="function"){cancelAnimationFrame(selfCheckRaf);}selfCheckRaf=requestAnimationFrame(()=>{selfCheckRaf=void 0;if(destroyed||selfCheckWarned||typeof window==="undefined")return;const overlay=element.querySelector(".idv-capture-immersive");if(overlay===null)return;const rect=overlay.getBoundingClientRect();const vw=window.innerWidth;const vh=window.innerHeight;if(Math.abs(rect.width-vw)>IMMERSIVE_FILL_TOLERANCE_PX||Math.abs(rect.height-vh)>IMMERSIVE_FILL_TOLERANCE_PX){selfCheckWarned=true;console.warn("[Checktiv] immersive capture overlay does not fill the viewport",rect.width,rect.height,vw,vh);}});};const ERROR_ARM_KINDS={minting:false,mint_error:true,waiting_for_init:false,ready:false,capturing:false,submitting:false,submit_error:true,submit_pending:false,capture_superseded:true,token_expired:true,capture_error:true};const isErrorArm=kind=>ERROR_ARM_KINDS[kind];const onTryAgain=()=>{if(typeof window!=="undefined")window.location.reload();};const paint=()=>{if(destroyed)return;R(k(CaptureFrame,{state,attemptIndex,getEmbedSrc:deps.getEmbedSrc,onTryAgain,copy,layout,immersiveActive,colorMode:resolvedInitPayload.theme.colorMode}),element);const iframeEl=element.querySelector("iframe.idv-capture-frame");const iframePresent=iframeEl!==null;const focusable=immersiveActive&&iframePresent;if(focusable&&!prevFocusable&&!destroyed){iframeEl?.focus();scheduleImmersiveSelfCheck();}if(isErrorArm(state.kind)&&state.kind!==prevStateKind){element.querySelector(".idv-capture-retry")?.focus();}prevFocusable=focusable;prevStateKind=state.kind;};const rerender=()=>{if(destroyed)return;immersiveActive=computeImmersiveActive();paint();};const unsubImmersive=layout==="immersive"?subscribeImmersive(rerender):void 0;const safeObserve=(fn,arg)=>{if(fn===void 0)return;try{fn(arg);}catch(err){console.warn("[Checktiv] capture observer threw; ignoring (observational only).",err);}};const unsubState=controller.subscribe(next=>{state=next;paint();safeObserve(onState,next);});const offReject=controller.on("selfie-cv-reject",event=>{if(event.type==="selfie-cv-reject"){attemptIndex=event.attemptIndex;paint();}safeObserve(onControllerEvent,event);});const offComplete=controller.on("all-complete",event=>{safeObserve(onControllerEvent,event);});controller.start();return {destroy(){if(destroyed)return;destroyed=true;unsubState();offReject();offComplete();if(unsubImmersive!==void 0)unsubImmersive();if(selfCheckRaf!==void 0&&typeof cancelAnimationFrame==="function"){cancelAnimationFrame(selfCheckRaf);}R(null,element);controller.destroy();}}}
|
|
6
|
-
|
|
7
|
-
export { fallbackCopy, mount };
|
package/dist/chunk-5AQCMTZV.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { idvCvGateRetryReasonEnum, captureFromIframeMessageSchema } from './chunk-6U53T32A.js';
|
|
2
|
-
import { isTwoSidedDocumentType } from './chunk-IQKHRPJR.js';
|
|
3
|
-
|
|
4
|
-
function reducer(state,action){switch(action.type){case "mint_ok":return {kind:"waiting_for_init",captureToken:action.captureToken,embedOrigin:action.embedOrigin,runIndex:action.runIndex};case "mint_failed":return {kind:"mint_error"};case "iframe_ready":if(state.kind==="waiting_for_init"){return {kind:"ready",embedOrigin:state.embedOrigin,runIndex:state.runIndex}}return state;case "phase":if(state.kind==="ready"||state.kind==="capturing"){return {kind:"capturing",embedOrigin:state.embedOrigin,runIndex:state.runIndex,phase:action.phase,coaching:null,lastCvRejectReason:action.phase==="selfie"&&state.kind==="capturing"?state.lastCvRejectReason:null,biometricLoading:isBiometricPhase(action.phase)}}return state;case "coaching":if(state.kind==="ready"||state.kind==="capturing"){return {kind:"capturing",embedOrigin:state.embedOrigin,runIndex:state.runIndex,phase:"coaching",coaching:action.coaching,lastCvRejectReason:state.kind==="capturing"?state.lastCvRejectReason:null,biometricLoading:state.kind==="capturing"?state.biometricLoading:false}}return state;case "selfie_cv_reject":if(state.kind==="ready"||state.kind==="capturing"){return {kind:"capturing",embedOrigin:state.embedOrigin,runIndex:state.runIndex,phase:state.kind==="capturing"?state.phase:"selfie",coaching:state.kind==="capturing"?state.coaching:null,lastCvRejectReason:action.reason,biometricLoading:false}}return state;case "biometric_camera_live":if(state.kind==="capturing"){return {...state,biometricLoading:false}}return state;case "submitting":return {kind:"submitting"};case "submit_failed":return {kind:"submit_error"};case "submit_pending":return {kind:"submit_pending"};case "capture_superseded":return {kind:"capture_superseded"};case "token_expired":return {kind:"token_expired"};case "capture_error":return {kind:"capture_error",errorKind:action.errorKind};default:return state}}function nextCapturePhaseAfterDocument(side,documentTypes,biometricMode){if(side==="front"&&documentTypes.some(isTwoSidedDocumentType))return "document_back";if(biometricMode==="liveness")return "liveness";if(biometricMode==="selfie")return "selfie";return "uploading"}function isBiometricPhase(phase){return phase==="selfie"||phase==="liveness"}var RETRY_REASON_COACHING={no_face_detected:"hold_steady",multiple_faces:"hold_steady",low_confidence:"move_closer",no_id_document:"hold_steady",image_read_failed:"hold_steady"};function coachingKindForState(state){const retryParsed=idvCvGateRetryReasonEnum.safeParse(state);if(retryParsed.success)return RETRY_REASON_COACHING[retryParsed.data];switch(state){case "camera-too-far":return "move_closer";case "camera-too-close":case "document-too-close-to-frame-edge":return "move_farther";case "glare-detected":return "reduce_glare";case "too-dark":case "lighting-too-dark":return "too_dark";case "wrong-side":return "wrong_side";case "selfie_move_closer":return "move_closer";case "selfie_too_dark":return "too_dark";case "selfie_no_face":case "selfie_multiple_faces":case "selfie_not_centered":return "hold_steady";default:return "hold_steady"}}function createCaptureController(deps){let state={kind:"minting"};const stateListeners=new Set;const eventListeners=new Map;let captureToken=null;let pinnedOrigin=null;let runIndex=null;let started=false;let destroyed=false;let cancelled=false;let submitStarted=false;let messageListener=null;function setState(next){state=next;for(const listener of stateListeners)listener(state);}function dispatch(action){setState(reducer(state,action));}function emit(event){const listeners=eventListeners.get(event.type);if(listeners===void 0)return;for(const listener of listeners)listener(event);}function postInit(){if(destroyed||captureToken===null||pinnedOrigin===null)return false;const iframe=deps.getIframe();if(iframe===null||iframe.contentWindow===null)return false;const init={type:"capture:init",captureToken,...deps.initPayload()};iframe.contentWindow.postMessage(init,pinnedOrigin);return true}function handleMessage(msg){switch(msg.type){case "capture:ready":{const posted=postInit();if(posted&&state.kind==="waiting_for_init"){dispatch({type:"iframe_ready"});}return}case "capture:coaching":{dispatch({type:"coaching",coaching:coachingKindForState(msg.state)});deps.onCoaching?.(msg.state,msg.attemptIndex);return}case "capture:selfie-cv-reject":{const reason=msg.retryReason??null;dispatch({type:"selfie_cv_reject",reason});emit({type:"selfie-cv-reject",attemptIndex:msg.attemptIndex,reason});return}case "capture:document-complete":{const{config}=deps.initPayload();dispatch({type:"phase",phase:nextCapturePhaseAfterDocument(msg.side,config.documentTypes,config.biometricMode)});return}case "capture:selfie-complete":{dispatch({type:"phase",phase:"uploading"});return}case "capture:error":{if(msg.code==="token_expired"){dispatch({type:"token_expired"});return}dispatch({type:"capture_error",errorKind:msg.code});return}case "capture:all-complete":{void submitCapture(msg.r2Keys);return}case "capture:behavior":{deps.onBehaviorSegment?.({steps:msg.steps,traits:msg.traits});return}case "capture:biometric_camera_live":{dispatch({type:"biometric_camera_live"});return}default:{const _exhaustive=msg;return _exhaustive}}}async function submitCapture(r2Keys){if(submitStarted)return;submitStarted=true;if(runIndex===null){dispatch({type:"submit_failed"});return}if(deps.onBeforeSubmit){try{await deps.onBeforeSubmit();}catch{if(!destroyed)dispatch({type:"submit_failed"});return}if(destroyed)return}dispatch({type:"submitting"});let result;try{result=await deps.submit(runIndex,r2Keys);}catch{if(!destroyed)dispatch({type:"submit_failed"});return}if(destroyed)return;if(result.ok){emit({type:"all-complete",runIndex});return}if(result.reason==="token_expired"){dispatch({type:"token_expired"});return}if(result.reason==="signal_pending"){dispatch({type:"submit_pending"});return}if(result.reason==="capture_superseded"){dispatch({type:"capture_superseded"});return}dispatch({type:"submit_failed"});}function onWindowMessage(event){if(destroyed||pinnedOrigin===null)return;if(event.origin!==pinnedOrigin)return;if(event.source!==null&&event.source!==deps.getIframe()?.contentWindow)return;const parsed=captureFromIframeMessageSchema.safeParse(event.data);if(!parsed.success)return;handleMessage(parsed.data);}return {start(){if(destroyed||started)return;started=true;void(async()=>{try{const minted=await deps.mintToken();if(cancelled||destroyed)return;captureToken=minted.captureToken;pinnedOrigin=minted.embedOrigin;runIndex=minted.runIndex;messageListener=onWindowMessage;window.addEventListener("message",messageListener);dispatch({type:"mint_ok",...minted});}catch{if(cancelled||destroyed)return;dispatch({type:"mint_failed"});}})();},on(type,cb){let listeners=eventListeners.get(type);if(listeners===void 0){listeners=new Set;eventListeners.set(type,listeners);}listeners.add(cb);return ()=>{listeners?.delete(cb);}},subscribe(cb){stateListeners.add(cb);cb(state);return ()=>{stateListeners.delete(cb);}},handleReady(){if(destroyed)return;postInit();},destroy(){if(destroyed)return;destroyed=true;cancelled=true;if(messageListener!==null){window.removeEventListener("message",messageListener);messageListener=null;}}}}
|
|
5
|
-
|
|
6
|
-
export { coachingKindForState, createCaptureController, isBiometricPhase, nextCapturePhaseAfterDocument, reducer };
|
package/dist/chunk-7NIKMJFJ.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { IDV_DOCUMENT_TYPES } from './chunk-IQKHRPJR.js';
|
|
2
|
-
import { sdkPublicSettings, SESSIONS_ME_PATH, dataPlaneHeaders } from './chunk-ACQKQLL2.js';
|
|
3
|
-
|
|
4
|
-
function createTokenManager(source,sessionId){const mint=reason=>typeof source==="string"?Promise.resolve(source):source({sessionId:sessionId(),reason});let cached=null;let pending=null;return {get(){if(cached!==null)return cached;const p=mint("initial");cached=p;void p.catch(()=>{if(cached===p)cached=null;});return p},refresh(reason){if(pending!==null)return pending;const p=mint(reason);pending=p;cached=p;void p.then(()=>{if(pending===p)pending=null;},()=>{if(pending===p)pending=null;if(cached===p)cached=null;});return p}}}async function withTokenRetry(tokens,fn,isUnauthorized){const first=await tokens.get();let result;let error;try{result=await fn(first);}catch(err){error=err;}if(error===void 0&&result!==void 0&&!isUnauthorized(result,void 0)){return result}if(error!==void 0&&!isUnauthorized(void 0,error)){throw error}const fresh=await tokens.refresh("401");return fn(fresh)}var SDK_MODULES=["idv","fraud","custom_form"];var BIOMETRIC_MODES=["none","selfie","liveness"];var DOCUMENT_TYPES=IDV_DOCUMENT_TYPES;var SDK_MODES=["live","test"];var DATA_REGIONS=Object.keys(sdkPublicSettings.regions);function isRecord(v){return typeof v==="object"&&v!==null}function isNonEmptyString(v){return typeof v==="string"&&v.length>0}function isSdkModule(v){return typeof v==="string"&&SDK_MODULES.includes(v)}function isBiometricMode(v){return typeof v==="string"&&BIOMETRIC_MODES.includes(v)}function isSdkMode(v){return typeof v==="string"&&SDK_MODES.includes(v)}function isSdkRegion(v){return typeof v==="string"&&DATA_REGIONS.includes(v)}function isDocumentType(v){return typeof v==="string"&&DOCUMENT_TYPES.includes(v)}function parseIdvConfig(value){if(!isRecord(value))return null;const documentTypes=value.document_types;const biometricMode=value.biometric_mode;const minAge=value.min_age;if(!Array.isArray(documentTypes)||documentTypes.length<1)return null;const types=[];for(const t of documentTypes){if(!isDocumentType(t))return null;types.push(t);}if(!isBiometricMode(biometricMode))return null;if(minAge!==void 0&&typeof minAge!=="number")return null;const config={documentTypes:types,biometricMode};if(typeof minAge==="number")config.minAge=minAge;return config}function parseSessionData(body){if(!isRecord(body)||!isRecord(body.data))return null;const d=body.data;const sessionId=d.session_id;const stepId=d.step_id;const stepType=d.step_type;if(!isNonEmptyString(sessionId)||!isNonEmptyString(stepId)||!isNonEmptyString(stepType)||!isSdkMode(d.mode)||!isSdkRegion(d.region)){return null}if(!Array.isArray(d.modules)||!d.modules.every(isSdkModule))return null;const modules=d.modules;const wantsIdv=stepType==="id_verification";let config=null;if(wantsIdv){config=parseIdvConfig(d.config);if(config===null)return null}return {sessionId,stepId,stepType,config,mode:d.mode,region:d.region,modules}}function isJourneyPlaneBody(body){if(!isRecord(body)||!isRecord(body.data))return false;const d=body.data;if("session_id"in d)return false;return isRecord(d.session)||isRecord(d.snapshot)}function warnWrongTokenPlane(){console.warn("[Checktiv] getSessionToken returned a non-browser token. Pass a browser token (bt_*) to getSessionToken, or use Checktiv.mount() with a client token.");}async function resolveSession(ctx,fetchImpl){const origin=ctx.apiBaseOrigin;let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(origin+SESSIONS_ME_PATH,{method:"GET",headers:dataPlaneHeaders(ctx,token)}),result=>result?.status===401);}catch{return {kind:"unresolved"}}if(!res.ok)return {kind:"unresolved"};let body;try{body=await res.json();}catch{return {kind:"unresolved"}}const data=parseSessionData(body);if(data!==null){ctx.setSessionId(data.sessionId);return {kind:"ok",session:data}}if(isJourneyPlaneBody(body))return {kind:"wrong_token"};return {kind:"unresolved"}}var ERROR_TABLE={origin_not_allowed:{recoverable:false,recovery:"contact_operator",message:"This origin is not allowed for the publishable key. Add it to the allowed origins list in the Checktiv console."},token_expired:{recoverable:true,recovery:"retry",message:"The session token expired. The SDK is refreshing it; if this persists, mint a new token from your backend."},session_expired:{recoverable:false,recovery:"refresh_session",message:"The verification session is no longer valid. Start a new verification from your backend."},wrong_token_type:{recoverable:false,recovery:"contact_operator",message:"This verification could not start. Contact the site operator."},protocol_mismatch:{recoverable:false,recovery:"contact_operator",message:"The SDK version is out of date. Update to the latest published version."},camera_denied:{recoverable:true,recovery:"cross_device",message:"Camera access was blocked. Allow camera access, or continue on another device."},camera_unsupported:{recoverable:true,recovery:"cross_device",message:"Your camera does not meet the minimum resolution needed for capture. Try another device, or continue on your phone."},cv_gate_failed:{recoverable:true,recovery:"retry",message:"We could not read the image clearly. Try again with better lighting and a steady hand."},upload_failed:{recoverable:true,recovery:"retry",message:"The upload did not complete. Check the connection and try again."},sdk_load_failed:{recoverable:true,recovery:"cross_device",message:"Verification could not start on this device. Try again, or continue on another device."},biometric_unsupported:{recoverable:false,recovery:"contact_operator",message:"This capture is not supported on this page. Contact the site operator."},isolation_required:{recoverable:false,recovery:"contact_operator",message:"This page configuration is not supported. Contact the site operator."}};Object.keys(ERROR_TABLE).filter(key=>key in ERROR_TABLE);function createChecktivError(code){const entry=ERROR_TABLE[code];return {code,...entry}}function mapHttpStatusToError(status){if(status===401)return "token_expired";if(status===403)return "origin_not_allowed";if(status===429)return "upload_failed";if(status>=500)return "upload_failed";return "session_expired"}
|
|
5
|
-
|
|
6
|
-
export { createChecktivError, createTokenManager, isJourneyPlaneBody, isRecord, mapHttpStatusToError, parseSessionData, resolveSession, warnWrongTokenPlane, withTokenRetry };
|
package/dist/chunk-PZFDDSXB.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { getModule } from './chunk-GFHNOZVO.js';
|
|
2
|
-
import { assertNever } from './chunk-UBQTPS5J.js';
|
|
3
|
-
import { createTokenManager, resolveSession, warnWrongTokenPlane, createChecktivError } from './chunk-7NIKMJFJ.js';
|
|
4
|
-
import { R, k } from './chunk-XOGHMNBX.js';
|
|
5
|
-
import { resolveApiBaseOrigin, sdkPublicSettings, shortCodeRefreshPath, PUBLISHABLE_KEY_HEADER, SESSIONS_ME_REFRESH_LINK_PATH, WORKING_TOKEN_MINT_PATH } from './chunk-ACQKQLL2.js';
|
|
6
|
-
import { getServiceOrigin } from './chunk-QFA3K5ZV.js';
|
|
7
|
-
|
|
8
|
-
var PUBLISHABLE_KEY_REGEX=/^ah_pk_(us|eu)_(live|test)_[A-Za-z0-9_-]{8,}$/;var InvalidPublishableKeyError=class extends Error{constructor(message){super(message);this.name="InvalidPublishableKeyError";}};function parsePublishableKey(key){const match=PUBLISHABLE_KEY_REGEX.exec(key);if(!match){throw new InvalidPublishableKeyError(`Invalid publishable key format. Expected ah_pk_<us|eu>_<live|test>_<token>, got: ${maskKey(key)}`)}const region=match[1];const mode=match[2];if(region!=="us"&®ion!=="eu"){throw new InvalidPublishableKeyError(`Invalid region in publishable key: ${maskKey(key)}`)}if(mode!=="test"&&mode!=="live"){throw new InvalidPublishableKeyError(`Invalid mode in publishable key: ${maskKey(key)}`)}return {region,mode}}function maskKey(key){if(key.length<=8)return "***";return `${key.slice(0,6)}...${key.slice(-2)}`}var HOST_TAG="checktiv-root";var MOUNTED_FLAG="__checktivMounted";var LEGACY_HOST_ATTR="data-autohost-kyc-host";var HOST_ATTR="data-checktiv-host";var shadowCache=new WeakMap;function mountShadowHost(target){const existing=findExistingHost(target);if(existing){const cached=shadowCache.get(existing);if(cached)return cached}const host=document.createElement("div");host.setAttribute(HOST_ATTR,HOST_TAG);host.setAttribute(LEGACY_HOST_ATTR,HOST_TAG);host[MOUNTED_FLAG]=true;target.appendChild(host);const shadow=host.attachShadow({mode:"closed"});shadowCache.set(host,shadow);return shadow}function findExistingHost(target){for(const child of Array.from(target.children)){if(!(child instanceof HTMLElement))continue;const candidate=child;if(candidate[MOUNTED_FLAG]===true)return candidate}return null}function moduleErrorEvent(name,error){switch(name){case "idv":return {type:"checktiv.idv.error",error};case "fraud":return {type:"checktiv.fraud.error",error};case "custom_form":return {type:"checktiv.custom_form.error",error}}}function missingModuleMessage(name){return `This session requires the '${name}' module. Import '@checktiv/sdk-web/${name}' in your app.`}function missingModuleError(name){const base=createChecktivError("sdk_load_failed");return moduleErrorEvent(name,{...base,message:missingModuleMessage(name)})}function consentGateRequiredError(){const base=createChecktivError("sdk_load_failed");return moduleErrorEvent("fraud",{...base,message:"This session includes the 'fraud' module, which needs a consent gate. Pass onConsent to mountProvisioned() to enable it."})}function customFormConfigRequiredError(){const base=createChecktivError("sdk_load_failed");return moduleErrorEvent("custom_form",{...base,message:"This session includes the 'custom_form' module, which needs its form config. Pass customFormConfig to mountProvisioned() to enable it."})}function unmappedStepTypeError(stepType){const base=createChecktivError("sdk_load_failed");return moduleErrorEvent("idv",{...base,message:`This session's current step ('${stepType}') has no matching visual module in this SDK build. Upgrade '@checktiv/sdk-web' to a version that renders this step.`})}var MODULE_IS_VISUAL={idv:true,fraud:false,custom_form:true};var STEP_TYPE_TO_VISUAL_MODULE={id_verification:"idv",custom_form:"custom_form"};var stepTypeToVisualModuleView=STEP_TYPE_TO_VISUAL_MODULE;function resolveCurrentStepVisualModule(stepType){return stepTypeToVisualModuleView[stepType]}function defaultLoadModule(name){if(name==="idv"){const factory2=getModule("idv");if(factory2===void 0)return Promise.resolve(null);return Promise.resolve({mount:(ctx,opts)=>factory2(ctx,{target:opts.target,onEvent:opts.onEvent,copy:opts.copy,layout:opts.layout,onBeforeSubmit:opts.onBeforeSubmit,onBehaviorSegment:opts.onBehaviorSegment,synthetic:opts.synthetic,crossDeviceCopy:opts.crossDeviceCopy,onOpenCrossDevice:opts.onOpenCrossDevice})})}if(name==="custom_form"){const factory2=getModule("custom_form");if(factory2===void 0)return Promise.resolve(null);return Promise.resolve({mount:(ctx,opts)=>{if(opts.customFormConfig===void 0){opts.onEvent?.(customFormConfigRequiredError());return {destroy:()=>void 0}}return factory2(ctx,{target:opts.target,config:opts.customFormConfig,copy:opts.customFormCopy,onEvent:opts.onEvent,session:opts.session})}})}const factory=getModule("fraud");if(factory===void 0)return Promise.resolve(null);return Promise.resolve({mount:(ctx,opts)=>{const onConsent=opts.onConsent;if(onConsent===void 0){opts.onEvent?.(consentGateRequiredError());return {destroy:()=>void 0}}return factory(ctx,{onConsent,onEvent:opts.onEvent})}})}function moduleErrorFor(name,code){return moduleErrorEvent(name,createChecktivError(code))}function createMountProvisioned(ctx,opts,deps={}){const emit=e=>opts.onEvent?.(e);const fetchImpl=opts.fetchImpl??fetch;const resolveSession2=deps.resolveSession??(()=>resolveSession(ctx,fetchImpl));const loadModule=deps.loadModule??defaultLoadModule;const handles=[];let destroyed=false;let idvOpenCrossDevice=null;void(async()=>{try{await composeModules();}catch(err){if(destroyed)return;console.warn("[Checktiv] mountProvisioned composition failed.",err);emit(moduleErrorFor("idv","sdk_load_failed"));}})();async function composeModules(){const resolution=await resolveSession2();if(destroyed)return;let session;switch(resolution.kind){case "ok":session=resolution.session;break;case "wrong_token":warnWrongTokenPlane();emit(moduleErrorFor("idv","wrong_token_type"));return;case "unresolved":emit(moduleErrorFor("idv","session_expired"));return;default:return assertNever(resolution)}const currentStepVisualModule=resolveCurrentStepVisualModule(session.stepType);if(currentStepVisualModule===void 0&&session.modules.some(m=>MODULE_IS_VISUAL[m])){emit(unmappedStepTypeError(session.stepType));return}for(const name of session.modules){if(destroyed)return;if(MODULE_IS_VISUAL[name]&&name!==currentStepVisualModule){continue}if(name==="fraud"&&opts.onConsent===void 0){emit(consentGateRequiredError());continue}const mod=await loadModule(name);if(destroyed)return;if(mod===null){emit(missingModuleError(name));continue}let moduleTarget;let containerToRemove=null;if(MODULE_IS_VISUAL[name]){const resolvedParent=typeof opts.target==="string"?typeof document!=="undefined"?document.querySelector(opts.target):null:opts.target;if(resolvedParent!==null){const container=document.createElement("div");resolvedParent.appendChild(container);containerToRemove=container;moduleTarget=container;}else {moduleTarget=opts.target;}}else {moduleTarget=opts.target;}let innerHandle;try{innerHandle=mod.mount(ctx,{target:moduleTarget,onEvent:opts.onEvent,onConsent:opts.onConsent,copy:opts.copy,layout:opts.layout,onBeforeSubmit:opts.onBeforeSubmit,onBehaviorSegment:opts.onBehaviorSegment,synthetic:opts.synthetic,crossDeviceCopy:opts.crossDeviceCopy,onOpenCrossDevice:opts.onOpenCrossDevice,customFormConfig:opts.customFormConfig,customFormCopy:opts.customFormCopy,session:{sessionId:session.sessionId,stepId:session.stepId}});}catch(err){containerToRemove?.remove();throw err}if(name==="idv"){idvOpenCrossDevice=innerHandle.openCrossDevice??null;}const capturedContainer=containerToRemove;const handle={destroy(){try{innerHandle.destroy();}finally{capturedContainer?.remove();}}};if(destroyed){handle.destroy();return}handles.push(handle);}}return {destroy(){destroyed=true;while(handles.length>0){const handle=handles.pop();handle?.destroy();}},openCrossDevice(){idvOpenCrossDevice?.();}}}function init(opts,deps={}){const scope="publishableKey"in opts?{...parsePublishableKey(opts.publishableKey),publishableKey:opts.publishableKey}:{region:opts.region,mode:opts.mode,publishableKey:void 0};let sessionId="";const apiBaseOrigin=resolveApiBaseOrigin(opts.apiBase,scope.region,scope.mode);const ctx={region:scope.region,mode:scope.mode,publishableKey:scope.publishableKey,apiBaseOrigin,theme:opts.theme,locale:opts.locale??"en",betas:opts.betas??[],...opts.selfiePromptMap!==void 0?{selfiePromptMap:opts.selfiePromptMap}:{},...opts.selfieChromeCopy!==void 0?{selfieChromeCopy:opts.selfieChromeCopy}:{},tokens:deps.tokens??createTokenManager(opts.getSessionToken,()=>sessionId),getSessionId:()=>sessionId,setSessionId:id=>{sessionId=id;}};function mount2(...args){if(args[0]==="idv"){const factory2=getModule("idv");if(factory2===void 0)return missingIdvHandle(args[1]);return factory2(ctx,args[1])}if(args[0]==="custom_form"){const factory2=getModule("custom_form");if(factory2===void 0)return missingCustomFormHandle(args[1]);return factory2(ctx,args[1])}const factory=getModule("fraud");if(factory===void 0)return missingFraudHandle(args[1]);return factory(ctx,args[1])}return {mountProvisioned:provOpts=>createMountProvisioned(ctx,provOpts),mount:mount2}}function missingIdvHandle(opts){const base=createChecktivError("sdk_load_failed");opts.onEvent?.({type:"checktiv.idv.error",error:{...base,message:missingModuleMessage("idv")}});return {destroy:()=>void 0,unmount:()=>void 0}}function missingFraudHandle(opts){const base=createChecktivError("sdk_load_failed");opts.onEvent?.({type:"checktiv.fraud.error",error:{...base,message:missingModuleMessage("fraud")}});return {destroy:()=>void 0}}function missingCustomFormHandle(opts){const base=createChecktivError("sdk_load_failed");const error={type:"checktiv.custom_form.error",error:{...base,message:missingModuleMessage("custom_form")}};opts.onEvent?.(error);return {destroy:()=>void 0}}var DEFAULT_REFRESH_MARGIN_MS=6e4;function createWorkingTokenManager(source,deps={}){const now=deps.now??(()=>Date.now());const setTimer=deps.setTimer??((fn,ms)=>setTimeout(fn,ms));const clearTimer=deps.clearTimer??(handle=>clearTimeout(handle));const marginMs=deps.marginMs??DEFAULT_REFRESH_MARGIN_MS;const onProactiveError=deps.onProactiveError;let cached=null;let pending=null;let timer=null;let stopped=false;const clearScheduled=()=>{if(timer!==null){clearTimer(timer);timer=null;}};const scheduleProactive=expiresAt=>{clearScheduled();if(stopped)return;const expiryMs=Date.parse(expiresAt);if(Number.isNaN(expiryMs))return;const delay=expiryMs-now()-marginMs;if(delay<=0)return;timer=setTimer(()=>{timer=null;void doRefresh("expired").catch(err=>onProactiveError?.(err));},delay);};const mintOnce=reason=>source(reason).then(minted=>{scheduleProactive(minted.expiresAt);return minted.token});const doRefresh=reason=>{if(pending!==null)return pending;const p=mintOnce(reason);pending=p;cached=p;void p.then(()=>{if(pending===p)pending=null;},()=>{if(pending===p)pending=null;if(cached===p)cached=null;});return p};return {get(){if(cached!==null)return cached;const p=mintOnce("initial");cached=p;void p.catch(()=>{if(cached===p)cached=null;});return p},refresh(reason){return doRefresh(reason)},stop(){stopped=true;clearScheduled();}}}var RESUME_CLIENT_TOKEN_KEY_PREFIX="checktiv.rct.";function safeLocalStorage(){try{return globalThis.localStorage??null}catch{return null}}function createClientTokenStore(resumeKey,storage=safeLocalStorage()){const key=RESUME_CLIENT_TOKEN_KEY_PREFIX+resumeKey;return {read(){if(storage===null)return null;try{const raw=storage.getItem(key);return raw!==null&&raw.length>0?raw:null}catch{return null}},write(token){if(storage===null)return;try{storage.setItem(key,token);}catch{}},clear(){if(storage===null)return;try{storage.removeItem(key);}catch{}}}}async function requestSelfServiceResend(params){const fetchImpl=params.fetchImpl??fetch;const body=JSON.stringify({confirmEmail:params.confirmEmail});try{let res;if(params.mode==="short_code"){res=await fetchImpl(params.origin+shortCodeRefreshPath(params.shortCode),{method:"POST",headers:{"content-type":"application/json"},body});}return {requested:res.ok}}catch{return {requested:false}}}var version="1.5.0";var initialised=new WeakSet;function resolveVerifyOrigin(parsed){return getServiceOrigin(sdkPublicSettings.apps.verify.subdomain,"prod",parsed.region,sdkPublicSettings)}function buildPopupUrl(parsed,opts){const origin=resolveVerifyOrigin(parsed);if(opts.applicantLinkToken){return `${origin}/start?lt=${encodeURIComponent(opts.applicantLinkToken)}`}return `${origin}/`}function launchPopup(url){const w=460;const h=760;const left=Math.max(0,Math.floor((window.screen.width-w)/2));const top=Math.max(0,Math.floor((window.screen.height-h)/2));const features=`popup=yes,width=${w},height=${h},left=${left},top=${top}`;const popup=window.open(url,"checktiv",features);if(!popup){window.location.href=url;return null}return popup}var COMPLETE_EVENT_TYPE="autohost.kyc.complete";function isCompletionMessage(data){if(typeof data!=="object"||data===null)return false;if(!("type"in data))return false;return data.type===COMPLETE_EVENT_TYPE}function listenForCompletion(expectedOrigin,onComplete){if(!onComplete)return;const handler=event=>{if(event.origin!==expectedOrigin)return;const data=event.data;if(!isCompletionMessage(data))return;onComplete(data);};window.addEventListener("message",handler);}function buildButton(onClick){const children="Start verification";return k("button",{type:"button",onClick,style:'display: inline-flex; align-items: center; justify-content: center; padding: 10px 20px; font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif; font-size: 14px; font-weight: 600; color: #fff; background: #0b5fff; border: none; border-radius: 6px; cursor: pointer;'},children)}function resolveTarget(opts){if(opts.target)return opts.target;return document.querySelector("[data-checktiv]")??document.querySelector("[data-autohost-kyc]")}function mountButton(opts){const parsed=parsePublishableKey(opts.publishableKey);const target=resolveTarget(opts);if(!target){console.warn("[Checktiv] No mount target found. Either pass `target` explicitly or add `<div data-checktiv>` to your page.");return}if(initialised.has(target))return;initialised.add(target);const shadow=mountShadowHost(target);const verifyOrigin=resolveVerifyOrigin(parsed);listenForCompletion(verifyOrigin,opts.onComplete);const onClick=()=>{const popupUrl=buildPopupUrl(parsed,opts);launchPopup(popupUrl);};R(buildButton(onClick),shadow);}function parseWorkingTokenMintResponse(body){if(typeof body!=="object"||body===null)return null;if(!("workingToken"in body)||!("expiresAt"in body))return null;const workingToken=body.workingToken;const expiresAt=body.expiresAt;if(typeof workingToken!=="string"||workingToken.length===0)return null;if(typeof expiresAt!=="string"||expiresAt.length===0)return null;return {workingToken,expiresAt}}async function mintWorkingTokenFacet(origin,clientToken,publishableKey,fetchImpl){const headers={Authorization:`Bearer ${clientToken}`};if(publishableKey!==void 0)headers[PUBLISHABLE_KEY_HEADER]=publishableKey;const res=await fetchImpl(origin+WORKING_TOKEN_MINT_PATH,{method:"POST",headers});if(!res.ok){throw new Error(`Checktiv working-token mint failed (status ${res.status}).`)}let body;try{body=await res.json();}catch{throw new Error("Checktiv working-token mint returned a non-JSON body.")}const parsed=parseWorkingTokenMintResponse(body);if(parsed===null)throw new Error("Checktiv working-token mint returned a malformed body.");return parsed}function completionSessionId(e){if(e.type!=="checktiv.idv.submitted"&&e.type!=="checktiv.custom_form.submitted"){return null}const sid="sessionId"in e?e.sessionId:void 0;return typeof sid==="string"&&sid.length>0?sid:null}function isSessionExpiredEvent(e){if(!e.type.endsWith(".error")||!("error"in e))return false;const err=e.error;if(typeof err!=="object"||err===null||!("code"in err))return false;return err.code==="session_expired"}function mount(target,opts){const fetchImpl=opts.fetchImpl??fetch;const scope="publishableKey"in opts?{...parsePublishableKey(opts.publishableKey),publishableKey:opts.publishableKey}:{region:opts.region,mode:opts.mode,publishableKey:void 0};const mintOrigin=resolveApiBaseOrigin(opts.apiBase,scope.region,scope.mode);const store=opts.resumeKey!==void 0?createClientTokenStore(opts.resumeKey):null;let clientTokenPromise=null;const getClientToken=()=>{if(clientTokenPromise!==null)return clientTokenPromise;const persisted=store?.read()??null;if(persisted!==null){clientTokenPromise=Promise.resolve(persisted);return clientTokenPromise}const p=opts.fetchToken();clientTokenPromise=p;void p.then(tok=>store?.write(tok),()=>{if(clientTokenPromise===p)clientTokenPromise=null;});return p};const mintWorkingToken=async()=>{const clientToken=await getClientToken();const minted=await mintWorkingTokenFacet(mintOrigin,clientToken,scope.publishableKey,fetchImpl);return {token:minted.workingToken,expiresAt:minted.expiresAt}};const tokens=createWorkingTokenManager(mintWorkingToken);const base={getSessionToken:()=>tokens.get(),...opts.apiBase!==void 0?{apiBase:opts.apiBase}:{},...opts.theme!==void 0?{theme:opts.theme}:{}};const initOptions=scope.publishableKey!==void 0?{...base,publishableKey:scope.publishableKey}:{...base,region:scope.region,mode:scope.mode};const needsChannel=opts.onEvent!==void 0||opts.onComplete!==void 0||store!==null;const onEvent=needsChannel?e=>{opts.onEvent?.(e);const sessionId=completionSessionId(e);if(sessionId!==null){store?.clear();opts.onComplete?.({sessionId});}else if(isSessionExpiredEvent(e)){store?.clear();}}:void 0;const client=init(initOptions,{tokens});const handle=client.mountProvisioned({target,fetchImpl,onEvent,onConsent:opts.onConsent,...opts.layout!==void 0?{layout:opts.layout}:{},...opts.copy!==void 0?{copy:opts.copy}:{},...opts.crossDeviceCopy!==void 0?{crossDeviceCopy:opts.crossDeviceCopy}:{},...opts.onOpenCrossDevice!==void 0?{onOpenCrossDevice:opts.onOpenCrossDevice}:{}});const requestResend=confirmEmail=>{if(opts.shortCode===void 0)return Promise.resolve({requested:false});return requestSelfServiceResend({mode:"short_code",origin:mintOrigin,shortCode:opts.shortCode,confirmEmail,fetchImpl})};return {destroy(){handle.destroy();tokens.stop();},openCrossDevice:()=>handle.openCrossDevice?.(),requestResend}}function applicantToWire(a){const wire={};if(a.externalId!==void 0)wire.external_id=a.externalId;if(a.email!==void 0)wire.email=a.email;if(a.phone!==void 0)wire.phone=a.phone;if(a.firstName!==void 0)wire.first_name=a.firstName;if(a.lastName!==void 0)wire.last_name=a.lastName;if(a.dateOfBirth!==void 0)wire.date_of_birth=a.dateOfBirth;if(a.referenceName!==void 0)wire.reference_name=a.referenceName;return wire}function readCreatedClientToken(body){if(typeof body!=="object"||body===null||!("data"in body))return null;const data=body.data;if(typeof data!=="object"||data===null||!("client_token"in data))return null;const clientToken=data.client_token;return typeof clientToken==="string"&&clientToken.length>0?clientToken:null}var sessions={async create(input,options){if(typeof window!=="undefined"||typeof document!=="undefined"){throw new Error("checktiv.sessions.create must run on your server: it needs your secret key. Never call it in the browser.")}const fetchImpl=options.fetchImpl??fetch;const headers={Authorization:`Bearer ${options.secretKey}`,"content-type":"application/json"};if(options.idempotencyKey!==void 0)headers["Idempotency-Key"]=options.idempotencyKey;const body=JSON.stringify({workflow_template_id:input.templateId,applicant:applicantToWire(input.applicant)});const res=await fetchImpl(`${options.apiBase}/v1/sessions`,{method:"POST",headers,body});if(!res.ok){throw new Error(`Checktiv sessions.create failed (status ${res.status}). Verify the apiBase origin and secret key.`)}let parsed;try{parsed=await res.json();}catch{throw new Error("Checktiv sessions.create returned a non-JSON response.")}const clientToken=readCreatedClientToken(parsed);if(clientToken===null){throw new Error("Checktiv sessions.create response carried no client token. Enable the working-token capability for this environment, then retry.")}return {clientToken}}};
|
|
9
|
-
|
|
10
|
-
export { InvalidPublishableKeyError, init, mount, mountButton, parsePublishableKey, sessions, version };
|