@checktiv/sdk-web 1.8.1 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/agents/manifest.json +12 -0
  2. package/dist/api-EY_fOZm-.d.ts +578 -0
  3. package/dist/capture-ui.d.ts +4 -4
  4. package/dist/capture-ui.js +4 -3
  5. package/dist/capture.d.ts +3 -3
  6. package/dist/capture.js +2 -1
  7. package/dist/challenge.js +1 -1
  8. package/dist/chunk-2SPZA3CQ.js +3 -0
  9. package/dist/chunk-4HIQN4KL.js +3 -0
  10. package/dist/chunk-C7GRMEYT.js +3 -0
  11. package/dist/chunk-KYV5BPCD.js +6 -0
  12. package/dist/chunk-LRKS6JEP.js +9 -0
  13. package/dist/chunk-SU6RE6UR.js +12 -0
  14. package/dist/chunk-T6NMRTFB.js +7 -0
  15. package/dist/chunk-UVTAPUGQ.js +3 -0
  16. package/dist/{chunk-WC6TLR42.js → chunk-WALPQ6TH.js} +2 -1
  17. package/dist/chunk-YK4WW4LX.js +7 -0
  18. package/dist/chunk-YRM5SYRT.js +8 -0
  19. package/dist/chunk-ZU4L3NDZ.js +3 -0
  20. package/dist/collect-user-info.d.ts +4 -4
  21. package/dist/collect-user-info.js +5 -5
  22. package/dist/{controller-DYXlBzQS.d.ts → controller-CO5r6vXD.d.ts} +2 -2
  23. package/dist/{copy-DVW_qbbM.d.ts → copy-D6Sd0BIe.d.ts} +3 -2
  24. package/dist/custom-form.css +1 -1
  25. package/dist/custom-form.d.ts +3 -3
  26. package/dist/custom-form.js +6 -7
  27. package/dist/esign/ceremony-runtime.js +7 -0
  28. package/dist/esign.d.ts +4 -0
  29. package/dist/esign.js +422 -0
  30. package/dist/fraud.d.ts +3 -3
  31. package/dist/fraud.js +4 -5
  32. package/dist/idv/cross-device.d.ts +3 -3
  33. package/dist/idv/cross-device.js +4 -4
  34. package/dist/idv.d.ts +3 -3
  35. package/dist/idv.js +12 -11
  36. package/dist/{index-DBJeQp6J.d.ts → index-iyKwn5_z.d.ts} +3 -3
  37. package/dist/index.d.ts +6 -6
  38. package/dist/index.js +6 -7
  39. package/dist/{machine-Z0b9Q7zQ.d.ts → machine-DXxarDcC.d.ts} +39 -2
  40. package/dist/react.d.ts +4 -4
  41. package/dist/react.js +7 -8
  42. package/dist/workspace.d.ts +3 -3
  43. package/dist/workspace.js +2 -1
  44. package/package.json +10 -3
  45. package/dist/api-DicBOi5f.d.ts +0 -342
  46. package/dist/chunk-523TT3PD.js +0 -7
  47. package/dist/chunk-AW7QM2QH.js +0 -6
  48. package/dist/chunk-BBO2X73Y.js +0 -9
  49. package/dist/chunk-CNHIOCUU.js +0 -5
  50. package/dist/chunk-LHALMQW3.js +0 -13
  51. package/dist/chunk-OMR5UY5H.js +0 -7
  52. package/dist/chunk-S24BZWVR.js +0 -3
  53. package/dist/chunk-S2OOEDJS.js +0 -3
@@ -0,0 +1,3 @@
1
+ var ESIGN_STATES=["preparing","consent","read","scroll_incomplete","adopt","age_gate","explain","sign","decline","withdraw","obscured","frame_blocked","age_blocked","conflict","token_expired","protocol_mismatch","error","submit_error","terminal_signed","terminal_declined","terminal_voided","terminal_expired","terminal_withdrawn"];var ESIGN_FRAME_FATAL_STATES=["conflict","protocol_mismatch","error"];function isEsignFrameFatalState(state){return ESIGN_FRAME_FATAL_STATES.includes(state)}var TERMINAL_STATUS_TO_STATE={signed:"terminal_signed",declined:"terminal_declined",voided:"terminal_voided",expired:"terminal_expired"};function isTerminalEnvelopeStatus(status){return Object.prototype.hasOwnProperty.call(TERMINAL_STATUS_TO_STATE,status)}var ESIGN_CONSENT_ACTIONS=["withdraw_consent","request_paper_copy"];var ESIGN_DOCUMENT_ACTIONS=["download"];var ESIGN_STATE_RIGHTS={preparing:"none",consent:"both",read:"both",scroll_incomplete:"both",adopt:"both",age_gate:"both",explain:"both",sign:"both",decline:"both",withdraw:"both",obscured:"both",age_blocked:"none",frame_blocked:"none",conflict:"none",token_expired:"none",protocol_mismatch:"none",error:"none",submit_error:"none",terminal_signed:"none",terminal_declined:"none",terminal_voided:"none",terminal_expired:"none",terminal_withdrawn:"none"};function esignStateOffersRights(state){return ESIGN_STATE_RIGHTS[state]!=="none"}var ESIGN_PREPARING_MAX_INTERVAL_MS=5e3;var ESIGN_PREPARING_MAX_ATTEMPTS=12;var ESIGN_PREPARING_STALL_MS=2e4;var ESIGN_FRAME_ANNOUNCE_TIMEOUT_MS=2e4;var ESIGN_PREPARING_DEFAULT_INTERVAL_MS=1500;function esignPreparingDelayMs(retryAfterMs){const floor=typeof retryAfterMs==="number"&&Number.isFinite(retryAfterMs)&&retryAfterMs>0?retryAfterMs:ESIGN_PREPARING_DEFAULT_INTERVAL_MS;return Math.min(floor,ESIGN_PREPARING_MAX_INTERVAL_MS)}var ESIGN_SCROLL_TARGET_MARGIN_PX=24;var ESIGN_COPY_FALLBACKS={preparing:"Your documents are being prepared. This page will update on its own in a moment.",consent:"Select the signature line in the document to add your signature. Confirming it also records your agreement to use electronic records.",read:"Read the full document below. Scroll to the end to continue.",scroll_incomplete:"You have not reached the end of the document yet. Scroll to the bottom and the Finish button turns on.",adopt:"Select the signature line in the document. Adding your signature also records your agreement to use electronic records.",age_gate:"Confirm that you meet the minimum age for this document, then continue.",explain:"Selecting Finish applies the signature you adopted to the document above and records the date and time. Read the document once more if you want to, then select Finish.",sign:"Select Finish to apply your signature to the document above.",decline:"Tell us why you do not want to sign, then select Send my decline. You can close this window afterward.",withdraw:"You can stop using electronic records for this document. Confirm below to stop here, and nothing will be signed. Asking for a mailed paper copy is a separate control, and it stays available afterward.",obscured:"The Finish button is covered by something else on this page, so it is turned off for now. Open your signing link directly in a new window to continue.",frame_blocked:"The signing window did not open. Reload the page to try again. If it still does not open, try a different browser, or ask the company that sent you this link for help.",conflict:"This document changed while you had it open. Reload the page to get the current version before you sign.",token_expired:"This signing page needs a fresh connection. Reload the page to pick up where you left off.",protocol_mismatch:"This page is out of date and cannot show the document safely. Reload the page. If it keeps happening, contact the company that sent you this link.",error:"Something went wrong loading your document. Reload the page to try again. If it keeps happening, contact the company that sent you this link.",submit_error:"We could not confirm that your signature was recorded. Reload the page to see whether it went through, and sign again if it did not.",terminal_signed:"This document is signed. Nothing else is needed here, so you can close this window.",terminal_declined:"You declined to sign this document. If that was a mistake, contact the company that sent you this link.",terminal_voided:"This document was canceled and can no longer be signed. Contact the company that sent you this link if you still need to sign it.",terminal_expired:"The time to sign this document has passed. Contact the company that sent you this link to ask for a new one.",terminal_withdrawn:"You withdrew your agreement to sign electronically, so nothing was signed. The company that sent you this link has been told. Contact them to ask for this document on paper, or for a new signing link if you change your mind.",age_blocked:"This document can only be signed by someone above a minimum age, so it cannot be signed here. Nothing was signed. You can decline to sign from More actions, or contact the company that sent you this link if you think this is wrong.",frameTitle:"Document signing"};var ESIGN_LABELS=["finish","adopt","cancel","change","tryAgain","reload","reloadToCheck","getHelp","moreActions","jumpToEnd","readNotice","signatureBlock","signatureBlockDone","finishLater","printAndSign","decline","declineSubmit","declineCancel","signatureName","signatureStyle","declineReason","ageConfirm","documentHeading","signatureHeading"];var ESIGN_LABEL_FALLBACKS={finish:"Finish",adopt:"Use this signature",cancel:"Cancel",change:"Change",tryAgain:"Try again",reload:"Reload the page",reloadToCheck:"Reload to check",getHelp:"Get help",moreActions:"More actions",readNotice:"Notice and your rights",jumpToEnd:"Jump to the end",signatureBlock:"Add your signature here. Required.",signatureBlockDone:"Your signature. Select to change it.",finishLater:"Finish later",printAndSign:"Print and sign",decline:"Decline to sign",declineSubmit:"Send my decline",declineCancel:"Go back",signatureName:"Your full legal name",signatureStyle:"Signature style",declineReason:"Why are you declining?",ageConfirm:"I meet the minimum age",documentHeading:"Document",signatureHeading:"Your signature"};var ESIGN_RIGHTS_KEYS=["heading","intro","withdraw","paperCopy","working","error","confirmTitle","confirmBody","confirmSubmit","confirmCancel","withdrawnBeforeSigning","withdrawnAfterSigning","paperCopyRequested","paperCopyAlreadyOutstanding"];var ESIGN_RIGHTS_FALLBACKS={heading:"Your rights",intro:"You do not have to use electronic records. You can stop using them for this document, or ask for a paper copy in the mail. Neither costs anything.",withdraw:"Stop using electronic records",paperCopy:"Ask for a mailed paper copy",working:"Working on your request.",error:"Your request did not go through. Select it again. If it keeps failing, contact the company that sent you this link.",confirmTitle:"Withdraw your consent?",confirmBody:"This ends the signing session and no electronic signature is recorded for you. The company that sent you this link is told that you withdrew. This costs nothing and no penalty applies, and you can still ask for a mailed paper copy afterward.",confirmSubmit:"Yes, withdraw consent",confirmCancel:"Go back",withdrawnBeforeSigning:"You withdrew your consent to use electronic records, and nothing was signed. The company that sent you this link has been told. If you want this document on paper, ask for a copy below. You can close this window.",withdrawnAfterSigning:"You withdrew your consent to use electronic records. The document you already signed still stands, because a signature cannot be taken back after the fact. The company that sent you this link has been told. If you want this document on paper, ask them to send you a copy.",paperCopyRequested:"We asked the company that sent you this link to send you a paper copy. There is no fee.",paperCopyAlreadyOutstanding:"A paper copy is already on its way to you, so there was nothing new to request."};var ESIGN_OUTCOME_RIGHTS_KEY={consent_withdrawn_before_signing:"withdrawnBeforeSigning",consent_withdrawn_after_signing:"withdrawnAfterSigning",paper_copy_requested:"paperCopyRequested",paper_copy_already_outstanding:"paperCopyAlreadyOutstanding"};function isEsignConsentOutcome(value){return Object.prototype.hasOwnProperty.call(ESIGN_OUTCOME_RIGHTS_KEY,value)}var ESIGN_DOCUMENT_KEYS=["download","printAndSignStarted","downloadFailed","downloadRemoved"];var ESIGN_DOCUMENT_FALLBACKS={download:"Download a copy",printAndSignStarted:"Print your copy, sign it by hand, and send it to the company that sent you this link. You cannot return a printed page through this page.",downloadFailed:"We could not download that document. Select it again. If it keeps failing, contact the company that sent you this link.",downloadRemoved:"This copy is no longer stored. Ask the company that sent you this link to send you a new copy or a printed record."};var ESIGN_COUNT_TOKEN="{count}";var ESIGN_SHELL_KEYS=["stepsBlocked","gateRead","gateSignature","gateAge","consentTermsLink","consentTermsNewWindow","consentAgeAttest","consentError","adoptTitle","adoptConsent","adoptFinePrint","declineTitle","declineBody","finishLaterTitle","finishLaterBody","disclosureTitle","disclosureVersionLabel","disclosurePublicCopy","disclosureBack","statusSigned","statusDeclined","statusVoided","statusExpired","statusWithdrawn"];var ESIGN_SHELL_FALLBACKS={stepsBlocked:"Not finished yet. Taking you to what is left.",gateRead:"Please read to the end",gateSignature:"Please sign above",gateAge:"Please confirm your age",consentTermsLink:"See terms.",consentTermsNewWindow:"Opens in a new window.",consentAgeAttest:"I am {count} or older.",consentError:"We could not record your agreement, so your signature was not added. Select the signature line in the document to try again.",adoptTitle:"Add your signature",adoptConsent:"Selecting Use this signature also records your agreement to sign and to get records for this document electronically.",adoptFinePrint:"Use this signature adopts what you see above as your signature. Selecting Finish signs the document.",declineTitle:"Decline to sign?",declineBody:"This ends your signing session and tells the company that sent you this link. No penalty applies. You can ask them for a new link later.",finishLaterTitle:"Finish later?",finishLaterBody:"Come back to this same link any time before the deadline. What you have done is kept.",disclosureTitle:"Using electronic records",disclosureVersionLabel:"Notice version",disclosurePublicCopy:"Open this notice in a new window",disclosureBack:"Back to the document",statusSigned:"Signed",statusDeclined:"Declined",statusVoided:"Canceled",statusExpired:"Expired",statusWithdrawn:"Withdrawn"};var ESIGN_TERMINAL_STATUS_KEY={terminal_signed:"statusSigned",terminal_declined:"statusDeclined",terminal_voided:"statusVoided",terminal_expired:"statusExpired",terminal_withdrawn:"statusWithdrawn"};function resolveEsignDocumentCopy(copy,key){const injected=copy?.documents?.[key];if(typeof injected==="string"&&injected.length>0)return injected;return ESIGN_DOCUMENT_FALLBACKS[key]}function resolveEsignShellCopy(copy,key){const injected=copy?.shell?.[key];if(typeof injected==="string"&&injected.length>0)return injected;return ESIGN_SHELL_FALLBACKS[key]}function resolveEsignTerminalStatus(copy,state){return resolveEsignShellCopy(copy,ESIGN_TERMINAL_STATUS_KEY[state])}function resolveEsignRightsCopy(copy,key){const injected=copy?.rights?.[key];if(typeof injected==="string"&&injected.length>0)return injected;return ESIGN_RIGHTS_FALLBACKS[key]}function resolveEsignOutcomeCopy(copy,outcome){return resolveEsignRightsCopy(copy,ESIGN_OUTCOME_RIGHTS_KEY[outcome])}function resolveEsignLabel(copy,label){const injected=copy?.labels?.[label];if(typeof injected==="string"&&injected.length>0)return injected;return ESIGN_LABEL_FALLBACKS[label]}function resolveEsignCopy(copy,state){const injected=copy?.[state];if(typeof injected==="string"&&injected.length>0)return injected;return ESIGN_COPY_FALLBACKS[state]}function resolveEsignFrameTitle(copy){const injected=copy?.frameTitle;if(typeof injected==="string"&&injected.length>0)return injected;return ESIGN_COPY_FALLBACKS.frameTitle}var ESIGN_COPY_STATE_KEYS=ESIGN_STATES;
2
+
3
+ export { ESIGN_CONSENT_ACTIONS, ESIGN_COPY_FALLBACKS, ESIGN_COPY_STATE_KEYS, ESIGN_COUNT_TOKEN, ESIGN_DOCUMENT_ACTIONS, ESIGN_DOCUMENT_FALLBACKS, ESIGN_DOCUMENT_KEYS, ESIGN_FRAME_ANNOUNCE_TIMEOUT_MS, ESIGN_LABELS, ESIGN_LABEL_FALLBACKS, ESIGN_OUTCOME_RIGHTS_KEY, ESIGN_PREPARING_MAX_ATTEMPTS, ESIGN_PREPARING_STALL_MS, ESIGN_RIGHTS_FALLBACKS, ESIGN_RIGHTS_KEYS, ESIGN_SCROLL_TARGET_MARGIN_PX, ESIGN_SHELL_FALLBACKS, ESIGN_SHELL_KEYS, ESIGN_STATES, ESIGN_STATE_RIGHTS, ESIGN_TERMINAL_STATUS_KEY, TERMINAL_STATUS_TO_STATE, esignPreparingDelayMs, esignStateOffersRights, isEsignConsentOutcome, isEsignFrameFatalState, isTerminalEnvelopeStatus, resolveEsignCopy, resolveEsignDocumentCopy, resolveEsignFrameTitle, resolveEsignLabel, resolveEsignOutcomeCopy, resolveEsignRightsCopy, resolveEsignShellCopy, resolveEsignTerminalStatus };
@@ -0,0 +1,3 @@
1
+ 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}}
2
+
3
+ export { resolveCaptureTheme };
@@ -0,0 +1,3 @@
1
+ var CREDENTIAL_UNVERIFIABLE_STATUS=401;function isCredentialUnverifiable(result){if(typeof result!=="object"||result===null)return false;if(!("status"in result))return false;return result.status===CREDENTIAL_UNVERIFIABLE_STATUS}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=isCredentialUnverifiable){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 CHECKTIV_RECOVERY_STRATEGIES=["retry","cross_device","refresh_session","contact_operator"];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."},session_parked:{recoverable:false,recovery:"contact_operator",message:"This verification is not available because of a setup problem on the organization side. Contact the organization that sent you this link."},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_policy_blocked:{recoverable:false,recovery:"contact_operator",message:"This page does not allow camera access. Contact the site operator."},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."},submit_failed:{recoverable:true,recovery:"retry",message:"The submission did not complete. Your captured images are saved. 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."}};var CHECKTIV_ERROR_CODES=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===CREDENTIAL_UNVERIFIABLE_STATUS)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"}function isChecktivErrorCode(value){return CHECKTIV_ERROR_CODES.some(code=>code===value)}function isChecktivRecovery(value){return CHECKTIV_RECOVERY_STRATEGIES.some(recovery=>recovery===value)}function isChecktivError(value){if(typeof value!=="object"||value===null)return false;if(!("code"in value)||!("message"in value)||!("recoverable"in value)||!("recovery"in value)){return false}const{code,message,recoverable,recovery}=value;return typeof code==="string"&&isChecktivErrorCode(code)&&typeof message==="string"&&typeof recoverable==="boolean"&&typeof recovery==="string"&&isChecktivRecovery(recovery)}
2
+
3
+ export { CHECKTIV_ERROR_CODES, CREDENTIAL_UNVERIFIABLE_STATUS, createChecktivError, createTokenManager, isChecktivError, isCredentialUnverifiable, mapHttpStatusToError, withTokenRetry };
@@ -0,0 +1,6 @@
1
+ import { isCameraPolicyRelabelable } from './chunk-ZU4L3NDZ.js';
2
+ import { createChecktivError } from './chunk-C7GRMEYT.js';
3
+
4
+ function createChecktivErrorEvent(code){return {type:"checktiv.idv.error",error:createChecktivError(code)}}var CAPTURE_ERROR_CODE={cv_gate_failed:"cv_gate_failed",upload_failed:"upload_failed",sdk_load_failed:"sdk_load_failed",biometric_unsupported:"biometric_unsupported",camera_unsupported:"camera_unsupported",selfie_camera_denied:"camera_denied",liveness_camera_denied:"camera_denied",liveness_runtime_error:"sdk_load_failed",liveness_timeout:"sdk_load_failed",liveness_server_error:"sdk_load_failed",liveness_cancelled:"sdk_load_failed",protocol_mismatch:"protocol_mismatch"};function captureErrorCode(state){if(state.cameraPolicyBlocked===true&&isCameraPolicyRelabelable(state.errorKind)){return "camera_policy_blocked"}return CAPTURE_ERROR_CODE[state.errorKind]}function mapStateToEvent(state,ctx){switch(state.kind){case "minting":case "waiting_for_init":case "submitting":return null;case "ready":return {type:"checktiv.idv.ready",config:ctx.config};case "capturing":if(state.phase==="coaching"&&state.coaching!==null){return {type:"checktiv.idv.coaching",hint:state.coaching}}return {type:"checktiv.idv.phase",phase:state.phase};case "mint_error":return createChecktivErrorEvent("session_expired");case "submit_error":return createChecktivErrorEvent("submit_failed");case "submit_pending":return {type:"checktiv.idv.processing",reason:"signal_pending"};case "capture_superseded":return {type:"checktiv.idv.capture_superseded"};case "token_expired":return createChecktivErrorEvent("token_expired");case "capture_error":return createChecktivErrorEvent(captureErrorCode(state));default:{return null}}}var opener=null;function registerCrossDeviceOpener(fn){opener=fn;}function getCrossDeviceOpener(){return opener}
5
+
6
+ export { createChecktivErrorEvent, getCrossDeviceOpener, mapStateToEvent, registerCrossDeviceOpener };
@@ -0,0 +1,9 @@
1
+ import { parsePublishableKey, createWorkingTokenSource, createWorkingTokenManager } from './chunk-WALPQ6TH.js';
2
+ import { resolveSession, warnWrongTokenPlane } from './chunk-YK4WW4LX.js';
3
+ import { assertNever } from './chunk-UBQTPS5J.js';
4
+ import { withTokenRetry, CREDENTIAL_UNVERIFIABLE_STATUS } from './chunk-C7GRMEYT.js';
5
+ import { stepSubmitPath, dataPlaneHeaders, resolveApiBaseOrigin } from './chunk-HFQJYEGZ.js';
6
+
7
+ var NAME_COMPONENTS_REQUIRED_ERROR_CODE="name_components_required";var ERROR_MESSAGES={not_collect_step:"The current step does not collect user info. Mount the verification journey to continue.",validation_failed:"The submitted information was not accepted. Check the required fields and try again.",[NAME_COMPONENTS_REQUIRED_ERROR_CODE]:"This verification needs the name in separate parts. Enter the family name and the given names, then try again.",token_expired:"The verification session expired. Create a new session so fetchToken returns a fresh client token, then try again.",origin_not_allowed:"This origin is not allowed for the publishable key. Add it to the allowed origins list in the Checktiv console.",rate_limited:"Too many requests. Wait a moment and try again.",service_unavailable:"The service is temporarily unavailable. Try again in a few seconds.",session_expired:"The verification session is no longer valid. Start a new verification from your backend.",wrong_token_type:"This verification could not start. Make sure fetchToken returns the client token, the same one you pass to Checktiv.mount().",network_error:"The request could not be completed. Check the connection and try again.",session_parked:"This verification is not available because of a setup problem on the organization side. Contact the organization that sent you this link."};function fail(code){return {ok:false,code,message:ERROR_MESSAGES[code]}}function mapSubmitStatus(status){if(status===400||status===422)return "validation_failed";if(status===CREDENTIAL_UNVERIFIABLE_STATUS)return "token_expired";if(status===403)return "origin_not_allowed";if(status===404)return "session_expired";if(status===429)return "rate_limited";if(status>=500)return "service_unavailable";return "session_expired"}async function mapSubmitFailure(res){const fallback=mapSubmitStatus(res.status);if(res.status!==400&&res.status!==422)return fallback;let body;try{body=await res.json();}catch{return fallback}if(typeof body!=="object"||body===null)return fallback;const error=body.error;if(typeof error!=="object"||error===null)return fallback;const code=error.code;return code===NAME_COMPONENTS_REQUIRED_ERROR_CODE?NAME_COMPONENTS_REQUIRED_ERROR_CODE:fallback}var WIRE_KEYS=["legalName","familyName","givenNames","nameSuffix","email","phone","dateOfBirth","address"];var IDENTIFIER_KEY=/^[A-Za-z_$][\w$]{0,39}$/;function buildSubmitBody(input){const body={};for(const key of WIRE_KEYS){const value=input[key];if(value!==void 0)body[key]=value;}const dropped=Object.keys(input).filter(key=>!WIRE_KEYS.some(wire=>wire===key));if(dropped.length>0){const safe=dropped.filter(key=>IDENTIFIER_KEY.test(key)).join(", ");console.warn(`[Checktiv] collectUserInfo dropped ${dropped.length} unknown key(s)${safe&&`: ${safe}`}. Known: ${WIRE_KEYS.join(", ")}.`);}return body}function buildContext(session,fetchImpl){const scope="publishableKey"in session?{...parsePublishableKey(session.publishableKey),publishableKey:session.publishableKey}:{region:session.region,mode:session.mode,publishableKey:void 0};const apiBaseOrigin=resolveApiBaseOrigin(session.apiBase,scope.region,scope.mode);let clientTokenPromise=null;const getClientToken=()=>{if(clientTokenPromise!==null)return clientTokenPromise;const p=session.fetchToken();clientTokenPromise=p;void p.catch(()=>{if(clientTokenPromise===p)clientTokenPromise=null;});return p};const mintWorkingToken=createWorkingTokenSource(apiBaseOrigin,getClientToken,scope.publishableKey,fetchImpl);const tokens=createWorkingTokenManager(mintWorkingToken);let sessionId="";const ctx={region:scope.region,mode:scope.mode,publishableKey:scope.publishableKey,apiBaseOrigin,locale:"en",betas:[],tokens,getSessionId:()=>sessionId,setSessionId:id=>{sessionId=id;}};return {ctx,tokens}}function collectUserInfo(opts){const{session}=opts;const fetchImpl=session.fetchImpl??fetch;const{ctx,tokens}=buildContext(session,fetchImpl);return {async submit(input){try{const resolution=await resolveSession(ctx,fetchImpl);switch(resolution.kind){case "wrong_token":warnWrongTokenPlane();return fail("wrong_token_type");case "unresolved":return fail("session_expired");case "parked":return fail("session_parked");case "nothing_to_render":return fail("not_collect_step");case "ok":break;default:return assertNever(resolution)}const resolved=resolution.session;if(resolved.stepType!=="collect_user_info"){return fail("not_collect_step")}const body=buildSubmitBody(input);let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(ctx.apiBaseOrigin+stepSubmitPath(resolved.sessionId,resolved.stepId),{method:"POST",headers:dataPlaneHeaders(ctx,token,{withJsonBody:true}),body:JSON.stringify(body)}));}catch{return fail("network_error")}if(res.ok)return {ok:true};return fail(await mapSubmitFailure(res))}finally{tokens.stop();}},async describe(){const fresh=buildContext(session,fetchImpl);try{const resolution=await resolveSession(fresh.ctx,fetchImpl);switch(resolution.kind){case "wrong_token":warnWrongTokenPlane();return {ok:false,code:"wrong_token_type"};case "unresolved":return {ok:false,code:"session_expired"};case "parked":return {ok:false,code:"session_parked"};case "nothing_to_render":return {ok:false,code:"not_collect_step"};case "ok":break;default:return assertNever(resolution)}const resolved=resolution.session;if(resolved.stepType!=="collect_user_info"){return {ok:false,code:"not_collect_step"}}const config=resolved.collectUserInfoConfig;if(config===void 0){return {ok:true,fields:[],nameComponents:"requested",captureStructuredName:false}}return {ok:true,fields:config.fields,nameComponents:config.nameComponents,captureStructuredName:config.captureStructuredName}}finally{fresh.tokens.stop();}}}}
8
+
9
+ export { collectUserInfo };
@@ -0,0 +1,12 @@
1
+ import { R, k } from './chunk-XOGHMNBX.js';
2
+ import { parsePublishableKey, createWorkingTokenSource, createWorkingTokenManager } from './chunk-WALPQ6TH.js';
3
+ import { getModule } from './chunk-GFHNOZVO.js';
4
+ import { resolveSession, warnWrongTokenPlane } from './chunk-YK4WW4LX.js';
5
+ import { assertNever } from './chunk-UBQTPS5J.js';
6
+ import { createTokenManager, createChecktivError, isChecktivError } from './chunk-C7GRMEYT.js';
7
+ import { resolveApiBaseOrigin, sdkPublicSettings, shortCodeRefreshPath, PUBLISHABLE_KEY_HEADER, SESSIONS_ME_REFRESH_LINK_PATH } from './chunk-HFQJYEGZ.js';
8
+ import { getServiceOrigin } from './chunk-QFA3K5ZV.js';
9
+
10
+ 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};case "esign":return {type:"checktiv.esign.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,esign:true};var STEP_TYPE_TO_VISUAL_MODULE={id_verification:"idv",custom_form:"custom_form",esign:"esign"};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,maxWidth:opts.maxWidth,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})}})}if(name==="esign"){const factory2=getModule("esign");if(factory2===void 0)return Promise.resolve(null);return Promise.resolve({mount:(ctx,opts)=>factory2(ctx,{target:opts.target,copy:opts.esignCopy,onEvent:opts.onEvent,session:opts.session,onRequestHelp:opts.onRequestHelp})})}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;case "parked":emit(moduleErrorFor("idv","session_parked"));return;case "nothing_to_render":emit({type:"checktiv.idv.processing",reason:"no_renderable_step"});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,maxWidth:opts.maxWidth,onBeforeSubmit:opts.onBeforeSubmit,onBehaviorSegment:opts.onBehaviorSegment,synthetic:opts.synthetic,crossDeviceCopy:opts.crossDeviceCopy,onOpenCrossDevice:opts.onOpenCrossDevice,customFormConfig:opts.customFormConfig,customFormCopy:opts.customFormCopy,esignCopy:opts.esignCopy,onRequestHelp:opts.onRequestHelp,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}:{},...opts.beginScanCopy!==void 0?{beginScanCopy:opts.beginScanCopy}:{},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])}if(args[0]==="esign"){const factory2=getModule("esign");if(factory2===void 0)return missingEsignHandle(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 missingEsignHandle(opts){const base=createChecktivError("sdk_load_failed");const error={type:"checktiv.esign.error",error:{...base,message:missingModuleMessage("esign")}};opts.onEvent?.(error);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 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{}}}}var SESSIONS_CREATE_ERROR_CODES=["unauthorized","invalid_template","rate_limited","network","server_error"];function createSessionsCreateError(code,message){return {code,message}}function mapHttpStatusToSessionsCreateError(status){if(status===401||status===403)return "unauthorized";if(status===429)return "rate_limited";if(status===400||status===404||status===422)return "invalid_template";return "server_error"}function isSessionsCreateErrorCode(value){return SESSIONS_CREATE_ERROR_CODES.some(code=>code===value)}function isSessionsCreateError(value){if(typeof value!=="object"||value===null)return false;if(!("code"in value)||!("message"in value))return false;const{code,message}=value;return typeof code==="string"&&isSessionsCreateErrorCode(code)&&typeof message==="string"}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.10.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 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 checktivErrorFromEvent(e){if(!e.type.endsWith(".error")||!("error"in e))return null;const err=e.error;return isChecktivError(err)?err:null}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=createWorkingTokenSource(mintOrigin,getClientToken,scope.publishableKey,fetchImpl);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.onError!==void 0||opts.onComplete!==void 0||store!==null;const safeCall=fn=>{try{fn();}catch{}};const onEvent=needsChannel?e=>{safeCall(()=>opts.onEvent?.(e));const error=checktivErrorFromEvent(e);if(error!==null)safeCall(()=>opts.onError?.(error));const sessionId=completionSessionId(e);if(sessionId!==null){store?.clear();safeCall(()=>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.maxWidth!==void 0?{maxWidth:opts.maxWidth}:{},...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 addressToWire(a){const wire={line1:a.line1,city:a.city,country:a.country};if(a.line2!==void 0)wire.line2=a.line2;if(a.region!==void 0)wire.region=a.region;if(a.postalCode!==void 0)wire.postal_code=a.postalCode;if(a.placeId!==void 0)wire.place_id=a.placeId;if(a.formatted!==void 0)wire.formatted=a.formatted;return wire}function applicantToWire(a){return {external_id:a.externalId,email:a.email,phone:a.phone,family_name:a.familyName,given_names:a.givenNames===void 0?void 0:[...a.givenNames],name_suffix:a.nameSuffix,date_of_birth:a.dateOfBirth,address:a.address===void 0?void 0:addressToWire(a.address),reference_name:a.referenceName}}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_CREATE_STATUS_HINT={unauthorized:"Verify your secret key (ah_sk_*) and that it matches the apiBase region.",invalid_template:"Verify the templateId (wt_*) and the request body.",rate_limited:"You have hit the rate ceiling. Retry after a short backoff.",network:"Check the apiBase origin and your network connectivity.",server_error:"This looks like a transient server error. Retry after a short backoff."};function sessionsCreateStatusHint(code){return SESSIONS_CREATE_STATUS_HINT[code]}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)});let res;try{res=await fetchImpl(`${options.apiBase}/v1/sessions`,{method:"POST",headers,body});}catch{throw createSessionsCreateError("network","Checktiv sessions.create could not reach the API. Check the apiBase origin and your network connectivity.")}if(!res.ok){const code=mapHttpStatusToSessionsCreateError(res.status);throw createSessionsCreateError(code,`Checktiv sessions.create failed (status ${res.status}). ${sessionsCreateStatusHint(code)}`)}let parsed;try{parsed=await res.json();}catch{throw createSessionsCreateError("network","Checktiv sessions.create returned a non-JSON response.")}const clientToken=readCreatedClientToken(parsed);if(clientToken===null){throw createSessionsCreateError("server_error","Checktiv sessions.create response carried no client token. Enable the working-token capability for this environment, then retry.")}return {clientToken}}};
11
+
12
+ export { init, isSessionsCreateError, mount, mountButton, sessions, version };
@@ -0,0 +1,7 @@
1
+ import { external_exports } from './chunk-NHNGQ5BB.js';
2
+ import { detectCameraPolicyBlock, warnCameraPolicyBlock } from './chunk-ZU4L3NDZ.js';
3
+ import { IDV_DOCUMENT_TYPES, isTwoSidedDocumentType } from './chunk-IQKHRPJR.js';
4
+
5
+ var behaviorTraitsSchema=external_exports.object({webdriver:external_exports.boolean(),maxTouchPoints:external_exports.number().int().min(0).max(512),timezone:external_exports.string().max(64).nullable(),pluginCount:external_exports.number().int().min(0).max(256),deviceModelHint:external_exports.string().max(120).nullable()}).strict();var behaviorStepSchema=external_exports.object({stepId:external_exports.string().max(80),seconds:external_exports.number().min(0).max(86400),pasteCount:external_exports.number().int().min(0).max(1e4)}).strict();var behaviorSurfaceEnum=external_exports.enum(["parent","embed"]);var behaviorCapturedPayloadSchema=external_exports.object({steps:external_exports.array(behaviorStepSchema).max(50),traits:behaviorTraitsSchema,segments:external_exports.array(external_exports.object({surface:behaviorSurfaceEnum,steps:external_exports.array(behaviorStepSchema).max(50),traits:behaviorTraitsSchema}).strict()).max(4).optional()}).strict();behaviorCapturedPayloadSchema.extend({ingress:external_exports.enum(["hosted","embedded"]).optional(),stepId:external_exports.string().max(128).optional()}).strict();var REGION_IDS=["us","eu"];var SystemModes=["live","test"];var DataRegions=REGION_IDS;var CURRENT_PROTOCOL_VERSION=2;var IDV_ACQUISITION_WHEN_ABSENT="camera";var LivenessAwsRegions=["us-east-1","eu-west-1"];({us:LivenessAwsRegions[0],eu:LivenessAwsRegions[1]});external_exports.uuid();external_exports.email().toLowerCase();external_exports.object({createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()});var dataRegionEnum=external_exports.enum(DataRegions);var dataModeEnum=external_exports.enum(SystemModes);external_exports.object({orgId:external_exports.string().min(1),mode:dataModeEnum,region:dataRegionEnum});external_exports.object({orgId:external_exports.string().min(1),actorId:external_exports.string().min(1),mode:dataModeEnum,region:dataRegionEnum,traceId:external_exports.string().optional()});var canonicalOriginSchema=external_exports.string().min(1).refine(v=>{if(v.includes("*"))return false;try{return new URL(v).origin===v}catch{return false}},"must be a canonical origin (scheme and host[:port], no path / query / fragment / credentials / wildcard)");canonicalOriginSchema.refine(v=>{try{return new URL(v).protocol==="https:"}catch{return false}},"must be a canonical https-only origin (scheme https: and host[:port], no path / query / fragment / credentials / wildcard)");var MAX_FIELDS_PER_SCREEN=8;var MAX_RULES_PER_SCREEN=10;var MAX_LOCALES=5;var MAX_LABEL_LEN=600;var bcp47LocaleSchema=external_exports.string().regex(/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,"must be a BCP-47 locale tag");var bcp47I18nLabelSchema=external_exports.record(bcp47LocaleSchema,external_exports.string().max(MAX_LABEL_LEN)).refine(map=>Object.keys(map).length<=MAX_LOCALES,{message:`at most ${MAX_LOCALES} locales per label`});var FORM_FIELD_TYPES=["short_text","long_text","number","email","phone","date","single_select","multi_select","boolean","file_upload","content_heading","content_paragraph"];var RESERVED_SLUGS=new Set(["__proto__","constructor","prototype"]);var formFieldSlugSchema=external_exports.string().regex(/^[a-z][a-z0-9_]{0,63}$/,"must be a lowercase slug").refine(s=>!RESERVED_SLUGS.has(s),{message:"reserved slug is not allowed"});var formFieldValidationSchema=external_exports.object({minLength:external_exports.number().int().nonnegative().optional(),maxLength:external_exports.number().int().positive().optional(),min:external_exports.number().optional(),max:external_exports.number().optional(),minSelections:external_exports.number().int().nonnegative().optional(),maxSelections:external_exports.number().int().positive().optional()}).strict();var formFieldOptionSchema=external_exports.object({value:external_exports.string().min(1).max(200),label:bcp47I18nLabelSchema}).strict();var formFieldSchema=external_exports.object({id:formFieldSlugSchema,type:external_exports.enum(FORM_FIELD_TYPES),label:bcp47I18nLabelSchema,helpText:bcp47I18nLabelSchema.optional(),required:external_exports.boolean().default(false),validation:formFieldValidationSchema.optional(),options:external_exports.array(formFieldOptionSchema).max(50).optional()}).strict();var formRuleOpEnum=external_exports.enum(["eq","neq","in","gt","gte","lt","lte","includes","not_includes","ends_with"]);var formRuleActionEnum=external_exports.enum(["flag_for_review","notify_email"]);var formRuleValueSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean(),external_exports.array(external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean()]))]);var formRuleSchema=external_exports.object({id:formFieldSlugSchema,when:external_exports.object({fieldId:formFieldSlugSchema,op:formRuleOpEnum,value:formRuleValueSchema}).strict(),actions:external_exports.array(formRuleActionEnum).min(1),notifyOrgMemberIds:external_exports.array(external_exports.string().min(1)).max(25).optional()}).strict();var customFormScreenConfigSchema=external_exports.object({supportedLocales:external_exports.array(bcp47LocaleSchema).min(1).max(MAX_LOCALES),fields:external_exports.array(formFieldSchema).min(1).max(MAX_FIELDS_PER_SCREEN),rules:external_exports.array(formRuleSchema).max(MAX_RULES_PER_SCREEN).default([])}).strict();var hexColorSchema=external_exports.string().regex(/^#[0-9a-fA-F]{6}$/,"Must be a 6-digit hex color, e.g. #2563eb");var colorModeSchema=external_exports.enum(["auto","light","dark"]);external_exports.object({primaryColor:hexColorSchema,secondaryColor:hexColorSchema.nullable().default(null),colorMode:colorModeSchema.default("auto")});var organizationBrandingSchema=external_exports.object({brandName:external_exports.string().min(1).max(120).optional(),primaryColor:hexColorSchema.optional(),secondaryColor:hexColorSchema.nullable().optional(),colorMode:colorModeSchema.optional(),logoUrl:external_exports.url().optional()});organizationBrandingSchema.omit({logoUrl:true});var checkTypeEnum=external_exports.enum(["collect_user_info","watchlist","background_us_criminal","background_global","id_verification","custom_form","esign"]);var testHintEnum=external_exports.enum(["pass","review","fail","doc_quality"]);var idvAcquisitionEnum=external_exports.enum(["camera","upload"]);var esignStepConfigSchema=external_exports.object({documentTemplateVersionIds:external_exports.array(external_exports.uuid()).max(1).default([]),requireScrollToEnd:external_exports.boolean().default(false),minimumAgeYears:external_exports.number().int().min(0).max(150).optional(),allowFullIdDocumentNumber:external_exports.boolean().default(false),sendCopyToApplicant:external_exports.boolean().default(true),sendCopyToOperator:external_exports.boolean().default(true)}).strict();var STEP_ID_REGEX=/^step_[0-9A-Za-z_-]{1,64}$/;var ADDRESS_TEXT_REGEX=/^[^\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069<>]+$/;var safeAddressText=max=>external_exports.string().min(1).max(max).regex(ADDRESS_TEXT_REGEX,"invalid characters");var postalCodeField=external_exports.string().max(20).regex(/^[A-Za-z0-9 \-]*$/);var countryField=external_exports.string().length(2).regex(/^[A-Z]{2}$/);var placeIdField=external_exports.string().max(255).regex(/^[A-Za-z0-9_\-:]+$/);function levenshtein(a,b){const m=a.length;const n=b.length;let prev=Array.from({length:n+1},(_,j)=>j);let curr=new Array(n+1).fill(0);for(let i=1;i<=m;i++){curr[0]=i;for(let j=1;j<=n;j++){const cost=a[i-1]===b[j-1]?0:1;curr[j]=Math.min(prev[j]+1,curr[j-1]+1,prev[j-1]+cost);}[prev,curr]=[curr,prev];}return prev[n]}var normalizeKey=key=>key.toLowerCase().replace(/[^a-z0-9]/g,"");var CURATED_KEY_SYNONYMS={zip:"postal_code",zipcode:"postal_code",postcode:"postal_code",templateid:"workflow_template_id",suffix:"name_suffix"};function nearestKnownKey(key,knownKeys){const target=normalizeKey(key);if(target.length===0)return null;const curated=Object.hasOwn(CURATED_KEY_SYNONYMS,target)?CURATED_KEY_SYNONYMS[target]:void 0;if(curated!==void 0){const curatedNormalized=normalizeKey(curated);const match=knownKeys.find(candidate=>normalizeKey(candidate)===curatedNormalized);if(match!==void 0)return match}let best=null;let bestDistance=Number.POSITIVE_INFINITY;for(const candidate of knownKeys){const normalized=normalizeKey(candidate);const distance=normalized===target?0:levenshtein(target,normalized);if(distance<bestDistance){bestDistance=distance;best=candidate;}}const threshold=Math.max(1,Math.ceil(target.length/2));return bestDistance<=threshold?best:null}function unknownKeyErrorMap(knownKeys,retiredKeys={}){const retiredByNormalizedKey=new Map(Object.entries(retiredKeys).map(([retired,message])=>[normalizeKey(retired),message]));return issue=>{if(issue.code!=="unrecognized_keys")return void 0;return issue.keys.map(key=>{const migration=retiredByNormalizedKey.get(normalizeKey(key));if(migration!==void 0)return `Unknown field "${key}". ${migration}`;const suggestion=nearestKnownKey(key,knownKeys);return suggestion?`Unknown field "${key}". Did you mean "${suggestion}"?`:`Unknown field "${key}".`}).join(" ")}}external_exports.object({line1:safeAddressText(120),line2:safeAddressText(120).optional(),city:safeAddressText(80),region:safeAddressText(80).optional(),postalCode:postalCodeField.optional(),country:countryField,placeId:placeIdField.optional(),formatted:safeAddressText(500).optional()});var wireAddressShape={line1:safeAddressText(120),line2:safeAddressText(120).optional(),city:safeAddressText(80),region:safeAddressText(80).optional(),postal_code:postalCodeField.optional(),country:countryField,place_id:placeIdField.optional(),formatted:safeAddressText(500).optional()};external_exports.strictObject(wireAddressShape,{error:unknownKeyErrorMap(Object.keys(wireAddressShape))}).transform(wire=>({line1:wire.line1,line2:wire.line2,city:wire.city,region:wire.region,postalCode:wire.postal_code,country:wire.country,placeId:wire.place_id,formatted:wire.formatted}));var applicantSkipPolicySchema=external_exports.object({minAttemptsBeforeShown:external_exports.number().int().nonnegative().default(0),requireReason:external_exports.boolean().default(false)}).loose();var i18nLabelSchema=external_exports.record(external_exports.string(),external_exports.string());var stepConditionSchema=external_exports.object({field:external_exports.string(),operator:external_exports.enum(["eq","neq","in","not_in"]),value:external_exports.union([external_exports.string(),external_exports.array(external_exports.string())])}).optional();var workflowStepSchema=external_exports.object({checkType:checkTypeEnum,isRequired:external_exports.boolean().default(true),order:external_exports.number().int(),maxAttempts:external_exports.number().int().default(3),condition:stepConditionSchema,label:external_exports.string().optional()});external_exports.array(workflowStepSchema).min(1);var baseStepFields={id:external_exports.string().regex(STEP_ID_REGEX),order:external_exports.number().int().nonnegative(),isRequired:external_exports.boolean().default(true),applicantSkippable:external_exports.boolean().default(false),applicantSkipPolicy:applicantSkipPolicySchema.optional(),maxAttempts:external_exports.number().int().positive().default(3),label:i18nLabelSchema.optional(),description:i18nLabelSchema.optional(),dependsOn:external_exports.array(external_exports.string()).optional(),condition:external_exports.unknown().nullable().optional()};var backgroundConfigSchema=external_exports.object({jurisdictionScope:external_exports.enum(["us","eu","global"]).default("global"),recordTypesIncluded:external_exports.array(external_exports.enum(["criminal","sex_offender","adverse_media"])).min(1).default(["criminal"])}).default({jurisdictionScope:"global",recordTypesIncluded:["criminal"]});var watchlistConfigSchema=external_exports.object({lists:external_exports.array(external_exports.enum(["pep","ofac","eu","un"])).default([]),confidenceThreshold:external_exports.number().min(0).max(1).default(.8)}).default({lists:[],confidenceThreshold:.8});var COLLECT_USER_INFO_FIELDS=["email","phone","dob","address"];var collectUserInfoConfigSchema=external_exports.object({fields:external_exports.preprocess(raw=>{if(!Array.isArray(raw))return raw;return raw.filter(v=>v!=="name")},external_exports.array(external_exports.enum(COLLECT_USER_INFO_FIELDS))).default(["email","phone"]),captureStructuredName:external_exports.boolean().default(false)}).default({fields:["email","phone"],captureStructuredName:false});var idvDocumentTypeEnum=external_exports.enum(IDV_DOCUMENT_TYPES);var idVerificationConfigSchema=external_exports.object({documentTypes:idvDocumentTypeEnum.array().min(1).default([...IDV_DOCUMENT_TYPES]),biometricMode:external_exports.enum(["none","selfie","liveness"]).default("none"),requireMrzMatch:external_exports.boolean().default(false),requireExpiryValid:external_exports.boolean().default(true),requireNameMatch:external_exports.boolean().default(false),documentAuthenticity:external_exports.boolean().default(false),minAge:external_exports.number().int().min(0).max(150).optional(),allowDocumentUpload:external_exports.boolean().default(false).describe("Lets the applicant upload an existing photo of their identity document instead of scanning it with the camera, so a device without a working camera can still supply the document (a template with face match or liveness still requires the camera for that step). Uploaded photos are checked the same way as camera scans and can pass automatically. Every result records which method - scan or upload - produced the document.")}).strict().default({documentTypes:[...IDV_DOCUMENT_TYPES],biometricMode:"none",requireMrzMatch:false,requireExpiryValid:true,requireNameMatch:false,documentAuthenticity:false,allowDocumentUpload:false});var watchlistStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("watchlist"),config:watchlistConfigSchema});var backgroundUsCriminalStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("background_us_criminal"),config:backgroundConfigSchema});var backgroundGlobalStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("background_global"),config:backgroundConfigSchema});var collectUserInfoStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("collect_user_info"),config:collectUserInfoConfigSchema});var idVerificationStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("id_verification"),config:idVerificationConfigSchema});var customFormScreenStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("custom_form"),config:customFormScreenConfigSchema});var esignStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("esign"),config:esignStepConfigSchema});external_exports.discriminatedUnion("type",[watchlistStepSchema,backgroundUsCriminalStepSchema,backgroundGlobalStepSchema,collectUserInfoStepSchema,idVerificationStepSchema,customFormScreenStepSchema,esignStepSchema]);var captureBrandTokensSchema=external_exports.object({primary:hexColorSchema,primaryHover:hexColorSchema,onPrimary:hexColorSchema,secondary:hexColorSchema,onSecondary:hexColorSchema,ring:hexColorSchema}).strict();var captureThemeSchema=external_exports.object({colorMode:external_exports.enum(["light","dark"]),brandTokens:captureBrandTokensSchema.nullable().default(null)}).strict();var captureDocumentSideEnum=external_exports.enum(["front","back"]);var captureDocumentGroupEnum=external_exports.enum(["unknown","dl","id","passport","passport-card","visa"]);var captureErrorCodeEnum=external_exports.enum(["cv_gate_failed","upload_failed","sdk_load_failed","token_expired","biometric_unsupported","camera_unsupported","selfie_camera_denied","liveness_camera_denied","liveness_timeout","liveness_server_error","liveness_runtime_error","liveness_cancelled","protocol_mismatch"]);external_exports.enum(["no_face","multiple_faces","too_dark","move_closer","not_centered","hold_still","ready"]);var selfiePromptMapSchema=external_exports.object({no_face:external_exports.string().min(1).max(120).optional(),multiple_faces:external_exports.string().min(1).max(120).optional(),too_dark:external_exports.string().min(1).max(120).optional(),move_closer:external_exports.string().min(1).max(120).optional(),not_centered:external_exports.string().min(1).max(120).optional(),hold_still:external_exports.string().min(1).max(120).optional(),ready:external_exports.string().min(1).max(120).optional()}).strict();var selfieChromeCopySchema=external_exports.object({shutterLabel:external_exports.string().min(1).max(80).optional(),shutterHint:external_exports.string().min(1).max(120).optional(),confirm:external_exports.string().min(1).max(80).optional(),retake:external_exports.string().min(1).max(80).optional()}).strict();var beginScanCopySchema=external_exports.object({prompt:external_exports.string().min(1).max(200).optional(),label:external_exports.string().min(1).max(80).optional(),cameraStartingLabel:external_exports.string().min(1).max(80).optional(),cameraUnavailableNotice:external_exports.string().min(1).max(200).optional(),uploadPrompt:external_exports.string().min(1).max(200).optional(),uploadLabel:external_exports.string().min(1).max(80).optional(),uploadSingleSideLabel:external_exports.string().min(1).max(80).optional(),uploadFrontLabel:external_exports.string().min(1).max(80).optional(),uploadBackLabel:external_exports.string().min(1).max(80).optional(),uploadEntryLabel:external_exports.string().min(1).max(80).optional(),uploadBackAction:external_exports.string().min(1).max(80).optional(),uploadChangeDocumentAction:external_exports.string().min(1).max(80).optional(),uploadChooseDocumentPrompt:external_exports.string().min(1).max(200).optional(),documentTypePassport:external_exports.string().min(1).max(80).optional(),documentTypeDriversLicense:external_exports.string().min(1).max(80).optional(),documentTypeIdCard:external_exports.string().min(1).max(80).optional(),documentTypeResidencePermit:external_exports.string().min(1).max(80).optional(),documentTypeVisa:external_exports.string().min(1).max(80).optional(),documentTypeWorkPermit:external_exports.string().min(1).max(80).optional(),uploadPickAction:external_exports.string().min(1).max(80).optional(),uploadReplaceAction:external_exports.string().min(1).max(80).optional(),uploadKeepAction:external_exports.string().min(1).max(80).optional(),uploadPreparingLabel:external_exports.string().min(1).max(80).optional(),uploadAddedNotice:external_exports.string().min(1).max(80).optional(),uploadBusyLabel:external_exports.string().min(1).max(200).optional(),uploadIncompleteNotice:external_exports.string().min(1).max(200).optional(),uploadIncompleteSingleNotice:external_exports.string().min(1).max(200).optional(),uploadTooLargeNotice:external_exports.string().min(1).max(200).optional(),uploadUnsupportedNotice:external_exports.string().min(1).max(200).optional(),uploadUnreadableNotice:external_exports.string().min(1).max(200).optional()}).strict();var captureInitMessageSchema=external_exports.object({type:external_exports.literal("capture:init"),captureToken:external_exports.string().min(1),config:idVerificationConfigSchema,locale:external_exports.string().min(2).max(35),theme:captureThemeSchema,mode:dataModeEnum.optional(),testHint:testHintEnum.optional(),protocolVersion:external_exports.number().int().min(1).optional(),beginScanCopy:beginScanCopySchema.optional(),beginScanPrompt:external_exports.string().min(1).max(200).optional(),beginScanLabel:external_exports.string().min(1).max(80).optional(),selfiePromptMap:selfiePromptMapSchema.optional(),selfieChromeCopy:selfieChromeCopySchema.optional()}).strict();external_exports.object({data:external_exports.object({captureToken:external_exports.string().min(1),embedOrigin:canonicalOriginSchema,runIndex:external_exports.number().int().min(0),expiresAt:external_exports.iso.datetime({offset:true}),embedContextToken:external_exports.string().min(1),mode:dataModeEnum.optional(),testHint:testHintEnum.optional()}).strict()}).strict();var captureReadyMessageSchema=external_exports.object({type:external_exports.literal("capture:ready")}).strict();var captureDocumentCompleteMessageSchema=external_exports.object({type:external_exports.literal("capture:document-complete"),side:captureDocumentSideEnum,r2Key:external_exports.string().min(1)}).strict();var captureSelfieCompleteMessageSchema=external_exports.object({type:external_exports.literal("capture:selfie-complete"),r2Key:external_exports.string().min(1)}).strict();var captureCoachingMessageSchema=external_exports.object({type:external_exports.literal("capture:coaching"),state:external_exports.string().min(1).max(120),attemptIndex:external_exports.number().int().min(0)}).strict();var captureSelfieCvRejectMessageSchema=external_exports.object({type:external_exports.literal("capture:selfie-cv-reject"),retryReason:external_exports.string().min(1).max(120).optional(),attemptIndex:external_exports.number().int().min(0)}).strict();var captureErrorMessageSchema=external_exports.object({type:external_exports.literal("capture:error"),code:captureErrorCodeEnum}).strict();var captureBiometricCameraLiveMessageSchema=external_exports.object({type:external_exports.literal("capture:biometric_camera_live"),timestamp:external_exports.number().optional()}).strict();var idvR2KeysSchema=external_exports.object({front:external_exports.string().min(1),back:external_exports.string().min(1).optional(),selfie:external_exports.string().min(1).optional()}).strict();var captureAllCompleteMessageSchema=external_exports.object({type:external_exports.literal("capture:all-complete"),r2Keys:idvR2KeysSchema,documentGroup:captureDocumentGroupEnum.optional(),acquisition:idvAcquisitionEnum.optional()}).strict();external_exports.object({stepId:external_exports.string().min(1),runIndex:external_exports.number().int().min(0),r2Keys:idvR2KeysSchema,acquisition:idvAcquisitionEnum.optional(),traceId:external_exports.string().optional()}).strict();external_exports.object({stepId:external_exports.string().min(1).optional()}).strict();var idvLivenessStsCredentialsSchema=external_exports.object({accessKeyId:external_exports.string().min(1),secretAccessKey:external_exports.string().min(1),sessionToken:external_exports.string().min(1),expiration:external_exports.string().min(1)}).strict();var livenessAwsRegionEnum=external_exports.enum(LivenessAwsRegions);external_exports.object({awsSessionId:external_exports.string().min(1),awsRegion:livenessAwsRegionEnum,credentials:idvLivenessStsCredentialsSchema}).strict();var captureBehaviorMessageSchema=external_exports.object({type:external_exports.literal("capture:behavior"),steps:external_exports.array(behaviorStepSchema).max(50),traits:behaviorTraitsSchema}).strict();var captureFromIframeMessageSchema=external_exports.discriminatedUnion("type",[captureReadyMessageSchema,captureDocumentCompleteMessageSchema,captureSelfieCompleteMessageSchema,captureCoachingMessageSchema,captureSelfieCvRejectMessageSchema,captureErrorMessageSchema,captureAllCompleteMessageSchema,captureBehaviorMessageSchema,captureBiometricCameraLiveMessageSchema]);external_exports.discriminatedUnion("type",[captureInitMessageSchema]);var idvCvGateRetryReasonEnum=external_exports.enum(["no_face_detected","multiple_faces","low_confidence","no_id_document","image_read_failed"]);external_exports.object({ok:external_exports.boolean(),retryReason:idvCvGateRetryReasonEnum.optional()}).strict();external_exports.enum(["front","back","selfie"]);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,...action.cameraPolicyBlocked===true?{cameraPolicyBlocked:true}:{}};default:return state}}function nextCapturePhaseAfterDocument(side,documentTypes,biometricMode){if(side==="front"&&documentTypes.some(isTwoSidedDocumentType))return "uploading";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 mintMode;let mintTestHint;let cameraPolicyChecked=false;let cameraPolicyBlocked=false;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 checkCameraPolicy(iframe,origin){if(cameraPolicyChecked)return;cameraPolicyChecked=true;try{const block=detectCameraPolicyBlock(iframe,origin);if(block===null)return;warnCameraPolicyBlock(block);cameraPolicyBlocked=true;}catch{}}function postInit(){if(destroyed||captureToken===null||pinnedOrigin===null)return false;const iframe=deps.getIframe();if(iframe===null||iframe.contentWindow===null)return false;checkCameraPolicy(iframe,pinnedOrigin);const mintFields={...mintMode!==void 0?{mode:mintMode}:{},...mintTestHint!==void 0?{testHint:mintTestHint}:{}};const init={type:"capture:init",captureToken,...deps.initPayload(),...mintFields};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,...cameraPolicyBlocked?{cameraPolicyBlocked:true}:{}});return}case "capture:all-complete":{void submitCapture(msg.r2Keys,msg.acquisition??IDV_ACQUISITION_WHEN_ABSENT);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,acquisition){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;const submitWithAcquisition=deps.submit;try{result=await submitWithAcquisition(runIndex,r2Keys,acquisition);}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;mintMode=minted.mode;mintTestHint=minted.testHint;messageListener=onWindowMessage;window.addEventListener("message",messageListener);dispatch({type:"mint_ok",captureToken:minted.captureToken,embedOrigin:minted.embedOrigin,runIndex:minted.runIndex});}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;}}}}
6
+
7
+ export { CURRENT_PROTOCOL_VERSION, IDV_ACQUISITION_WHEN_ABSENT, coachingKindForState, createCaptureController, isBiometricPhase, nextCapturePhaseAfterDocument, reducer };
@@ -0,0 +1,3 @@
1
+ function isOriginTargetedPoster(value){return typeof value==="object"&&value!==null&&"postMessage"in value}function initTransport(options,announce){const{win,allowedOrigins,parse,onMessage,accept,expectedSource,reAnnounce}=options;if(!Array.isArray(allowedOrigins)||allowedOrigins.length===0){return {teardown:()=>{}}}const allowlist=new Set(allowedOrigins);const onMessageListener=event=>{if(!allowlist.has(event.origin))return;if(expectedSource!==void 0){const expected=expectedSource();if(expected===null||event.source!==expected)return}const parsed=parse(event.data);if(parsed===null)return;if(accept&&!accept(parsed,event.origin))return;const source=event.source;if(!isOriginTargetedPoster(source))return;const post=message=>source.postMessage(message,event.origin);onMessage(parsed,post,event.origin);};win.addEventListener("message",onMessageListener);const broadcast=message=>{for(const origin of allowlist){win.parent.postMessage(message,origin);}};if(announce!==void 0)broadcast(announce);let timer=null;if(reAnnounce!==void 0&&reAnnounce.maxAttempts>0){const scheduler=reAnnounce.schedule??{set:(cb,ms)=>setTimeout(cb,ms),clear:handle=>clearTimeout(handle)};let attemptsLeft=reAnnounce.maxAttempts;const tick=()=>{if(attemptsLeft<=0){timer=null;return}attemptsLeft-=1;broadcast(reAnnounce.message);timer=attemptsLeft>0?scheduler.set(tick,reAnnounce.intervalMs):null;};timer=scheduler.set(tick,reAnnounce.intervalMs);return {teardown:()=>{win.removeEventListener("message",onMessageListener);if(timer!==null){scheduler.clear(timer);timer=null;}}}}return {teardown:()=>{win.removeEventListener("message",onMessageListener);}}}
2
+
3
+ export { initTransport };
@@ -1,5 +1,6 @@
1
+ import { createChecktivError } from './chunk-C7GRMEYT.js';
1
2
  import { WORKING_TOKEN_MINT_PATH, PUBLISHABLE_KEY_HEADER } from './chunk-HFQJYEGZ.js';
2
3
 
3
- 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"&&region!=="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 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();}}}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 createWorkingTokenSource(origin,getClientToken,publishableKey,fetchImpl){return async()=>{const clientToken=await getClientToken();const minted=await mintWorkingTokenFacet(origin,clientToken,publishableKey,fetchImpl);return {token:minted.workingToken,expiresAt:minted.expiresAt}}}
4
+ 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"&&region!=="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 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();}}}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){if(res.status===409)throw createChecktivError("session_parked");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 createWorkingTokenSource(origin,getClientToken,publishableKey,fetchImpl){return async()=>{const clientToken=await getClientToken();const minted=await mintWorkingTokenFacet(origin,clientToken,publishableKey,fetchImpl);return {token:minted.workingToken,expiresAt:minted.expiresAt}}}
4
5
 
5
6
  export { InvalidPublishableKeyError, createWorkingTokenManager, createWorkingTokenSource, parsePublishableKey };
@@ -0,0 +1,7 @@
1
+ import { IDV_DOCUMENT_TYPES } from './chunk-IQKHRPJR.js';
2
+ import { withTokenRetry, isChecktivError } from './chunk-C7GRMEYT.js';
3
+ import { sdkPublicSettings, SESSIONS_ME_PATH, dataPlaneHeaders } from './chunk-HFQJYEGZ.js';
4
+
5
+ var SDK_MODULES=["idv","fraud","custom_form","esign"];var BIOMETRIC_MODES=["none","selfie","liveness"];var DOCUMENT_TYPES=IDV_DOCUMENT_TYPES;var SDK_MODES=["live","test"];var DATA_REGIONS=Object.keys(sdkPublicSettings.regions);var COLLECT_USER_INFO_FIELD_VALUES=["email","phone","dob","address"];var COLLECT_USER_INFO_NAME_COMPONENTS_VALUES=["required","requested","optional"];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 isCollectUserInfoField(v){return typeof v==="string"&&COLLECT_USER_INFO_FIELD_VALUES.includes(v)}function isNameComponents(v){return typeof v==="string"&&COLLECT_USER_INFO_NAME_COMPONENTS_VALUES.includes(v)}function parseCollectUserInfoConfig(value){if(!isRecord(value))return null;const fields=value.fields;const captureStructuredName=value.capture_structured_name;const nameComponents=value.name_components;if(!Array.isArray(fields))return null;const parsedFields=[];for(const f of fields){if(!isCollectUserInfoField(f))return null;parsedFields.push(f);}if(typeof captureStructuredName!=="boolean")return null;if(!isNameComponents(nameComponents))return null;return {fields:parsedFields,nameComponents,captureStructuredName}}function warnMalformedAllowDocumentUpload(received){console.warn(`[Checktiv] The sessions/me config carried a non-boolean \`allow_document_upload\` (received ${received}). Treating it as false, so this session will not offer document upload even if the template enables it. This is a server or serializer drift, not a client option.`);}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 rawAllowDocumentUpload=value.allow_document_upload;if(rawAllowDocumentUpload!==void 0&&typeof rawAllowDocumentUpload!=="boolean"){warnMalformedAllowDocumentUpload(typeof rawAllowDocumentUpload);}const allowDocumentUpload=rawAllowDocumentUpload===true;const config={documentTypes:types,biometricMode,allowDocumentUpload};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}const collectUserInfoConfig=stepType==="collect_user_info"?parseCollectUserInfoConfig(d.config)??void 0:void 0;return {sessionId,stepId,stepType,config,mode:d.mode,region:d.region,modules,...collectUserInfoConfig!==void 0?{collectUserInfoConfig}:{}}}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 isNonRenderableMarker(body){if(!isRecord(body)||!isRecord(body.data))return false;return body.data.renderable===false}function warnWrongTokenPlane(){console.warn("[Checktiv] The session token reached the wrong data plane. For the zero-lifecycle APIs (Checktiv.mount() or collectUserInfo), fetchToken must return your durable client token, which the SDK exchanges for a working token. For a customer-embed Checktiv.init(), getSessionToken must return a browser 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)}));}catch(err){if(isChecktivError(err)&&err.code==="session_parked")return {kind:"parked"};return {kind:"unresolved"}}if(!res.ok)return {kind:"unresolved"};let body;try{body=await res.json();}catch{return {kind:"unresolved"}}if(isNonRenderableMarker(body))return {kind:"nothing_to_render"};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"}}
6
+
7
+ export { isJourneyPlaneBody, isRecord, resolveSession, warnWrongTokenPlane };
@@ -0,0 +1,8 @@
1
+ import { createCaptureController, isBiometricPhase, coachingKindForState } from './chunk-T6NMRTFB.js';
2
+ import { isCameraPolicyRelabelable } from './chunk-ZU4L3NDZ.js';
3
+ import { u } from './chunk-HV2QKVJX.js';
4
+ import { R, k } from './chunk-XOGHMNBX.js';
5
+
6
+ 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."}}var CAMERA_POLICY_BLOCKED_TEXT="This page is not allowing camera access, so verification cannot continue. This is a setup problem on the site, not a problem with your device, and another device will not help. Please contact the operator to continue.";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,cameraPolicyBlocked:()=>CAMERA_POLICY_BLOCKED_TEXT,tryAgain:()=>"Try again",frameTitle:()=>"Identity verification capture"};var CSS_LENGTH_PATTERN=/^\d+(?:\.\d+)?(?:px|rem|em|vw|vh|%|ch)$/;function isValidCssLength(value){return CSS_LENGTH_PATTERN.test(value)}function maxWidthStyle(maxWidth){if(maxWidth===void 0||!isValidCssLength(maxWidth))return void 0;return `--idv-capture-max-width: ${maxWidth};`}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",maxWidth}=props;const style=maxWidthStyle(maxWidth);return u("div",{className:"idv-capture-root","data-color-mode":colorMode,style,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 cameraPolicyBlocked=state.cameraPolicyBlocked===true&&isCameraPolicyRelabelable(errorKind);const terminal=errorKind==="protocol_mismatch"||cameraPolicyBlocked;return u("div",{className:"idv-capture-error",role:"alert",children:[u("p",{children:cameraPolicyBlocked?(copy.cameraPolicyBlocked??fallbackCopy.cameraPolicyBlocked)():(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,maxWidth,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,maxWidth,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();}}}
7
+
8
+ export { fallbackCopy, mount };
@@ -0,0 +1,3 @@
1
+ var CAMERA_FEATURE="camera";function isFeaturePolicyLike(value){if(typeof value!=="object"||value===null)return false;return "allowsFeature"in value&&typeof value.allowsFeature==="function"&&"getAllowlistForFeature"in value&&typeof value.getAllowlistForFeature==="function"}function readFramePolicy(frame){if(!("featurePolicy"in frame))return null;const candidate=frame.featurePolicy;return isFeaturePolicyLike(candidate)?candidate:null}function readCameraAllowlist(policy){let raw;try{raw=policy.getAllowlistForFeature(CAMERA_FEATURE);}catch{return null}if(!Array.isArray(raw))return null;return raw.filter(entry=>typeof entry==="string")}function detectCameraPolicyBlock(frame,captureOrigin){const policy=readFramePolicy(frame);if(policy===null)return null;let allowed;try{allowed=policy.allowsFeature(CAMERA_FEATURE,captureOrigin);}catch{return null}if(allowed!==false)return null;return {captureOrigin,allowlist:readCameraAllowlist(policy)}}var MAX_LOGGED_ORIGINS=5;var MAX_LOGGED_ORIGIN_LENGTH=120;var ORIGIN_SHAPE=/^https?:\/\/[A-Za-z0-9._:-]+$/;function summarizeAllowlist(origins){const shown=origins.slice(0,MAX_LOGGED_ORIGINS).map(origin=>{const trimmed=origin.slice(0,MAX_LOGGED_ORIGIN_LENGTH);return ORIGIN_SHAPE.test(trimmed)?trimmed:"(unreadable entry)"});const omitted=origins.length-shown.length;return omitted>0?`${shown.join(", ")} (+${omitted} more)`:shown.join(", ")}function warnCameraPolicyBlock(block){const allowlist=block.allowlist===null?"":block.allowlist.length===0?" The frame is currently allowed the camera for no origin at all.":` The frame is currently allowed the camera for: ${summarizeAllowlist(block.allowlist)}.`;console.warn(`[Checktiv] This page's Permissions-Policy header does not grant the camera to the capture frame at ${block.captureOrigin}, so identity capture cannot start.${allowlist} The header served on this page must allow both self and the capture origin, for example: Permissions-Policy: camera=(self "${block.captureOrigin}"). An allowlist that names the capture origin but omits self still denies the frame, because a page can only delegate a permission it holds. Sending the applicant to another device will not help, because that device receives the same header. See /developers/sdks/security-headers in the Checktiv developer docs.`);}var CAMERA_POLICY_RELABELABLE={sdk_load_failed:true,camera_unsupported:true,selfie_camera_denied:true,liveness_camera_denied:true,biometric_unsupported:false,liveness_runtime_error:false,liveness_timeout:false,liveness_server_error:false,liveness_cancelled:false,cv_gate_failed:false,upload_failed:false,protocol_mismatch:false};function isCameraPolicyRelabelable(kind){return CAMERA_POLICY_RELABELABLE[kind]}
2
+
3
+ export { detectCameraPolicyBlock, isCameraPolicyRelabelable, warnCameraPolicyBlock };
@@ -1,6 +1,6 @@
1
- import { H as ChecktivInitScope } from './api-DicBOi5f.js';
2
- import './machine-Z0b9Q7zQ.js';
3
- import './copy-DVW_qbbM.js';
1
+ import { O as ChecktivInitScope } from './api-EY_fOZm-.js';
2
+ import './machine-DXxarDcC.js';
3
+ import './copy-D6Sd0BIe.js';
4
4
  import './copy-DCeQ4JKx.js';
5
5
 
6
6
  declare const COLLECT_USER_INFO_FIELDS: readonly ["email", "phone", "dob", "address"];
@@ -48,7 +48,7 @@ type CollectUserInfoSession = ChecktivInitScope & {
48
48
  interface CollectUserInfoOptions {
49
49
  session: CollectUserInfoSession;
50
50
  }
51
- type CollectUserInfoSubmitErrorCode = 'not_collect_step' | 'validation_failed' | typeof NAME_COMPONENTS_REQUIRED_ERROR_CODE | 'token_expired' | 'origin_not_allowed' | 'rate_limited' | 'service_unavailable' | 'session_expired' | 'wrong_token_type' | 'network_error';
51
+ type CollectUserInfoSubmitErrorCode = 'not_collect_step' | 'validation_failed' | typeof NAME_COMPONENTS_REQUIRED_ERROR_CODE | 'token_expired' | 'origin_not_allowed' | 'rate_limited' | 'service_unavailable' | 'session_expired' | 'wrong_token_type' | 'network_error' | 'session_parked';
52
52
  type CollectUserInfoSubmitResult = {
53
53
  ok: true;
54
54
  } | {
@@ -1,9 +1,9 @@
1
- export { collectUserInfo } from './chunk-BBO2X73Y.js';
2
- import './chunk-WC6TLR42.js';
3
- import './chunk-523TT3PD.js';
1
+ export { collectUserInfo } from './chunk-LRKS6JEP.js';
2
+ import './chunk-WALPQ6TH.js';
3
+ import './chunk-YK4WW4LX.js';
4
+ import './chunk-IQKHRPJR.js';
4
5
  import './chunk-UBQTPS5J.js';
5
- import './chunk-S2OOEDJS.js';
6
+ import './chunk-C7GRMEYT.js';
6
7
  import './chunk-HFQJYEGZ.js';
7
- import './chunk-IQKHRPJR.js';
8
8
  import './chunk-QFA3K5ZV.js';
9
9
  import './chunk-AIK7CDV6.js';
@@ -1,4 +1,4 @@
1
- import { f as CaptureState, D as DataMode, T as TestHint, I as IdvR2Keys, g as CaptureInitMessage, h as CaptureInitStaticKey, a as CaptureBehaviorMessage } from './machine-Z0b9Q7zQ.js';
1
+ import { f as CaptureState, D as DataMode, T as TestHint, I as IdvR2Keys, g as IdvAcquisition, h as CaptureInitMessage, j as CaptureInitStaticKey, a as CaptureBehaviorMessage } from './machine-DXxarDcC.js';
2
2
 
3
3
  type CaptureEvent = {
4
4
  type: 'selfie-cv-reject';
@@ -25,7 +25,7 @@ interface CaptureControllerDeps {
25
25
  mode?: DataMode;
26
26
  testHint?: TestHint;
27
27
  }>;
28
- submit: (runIndex: number, r2Keys: IdvR2Keys) => Promise<SubmitResult>;
28
+ submit: (runIndex: number, r2Keys: IdvR2Keys, acquisition?: IdvAcquisition) => Promise<SubmitResult>;
29
29
  getEmbedSrc: (embedOrigin: string) => string;
30
30
  initPayload: () => Pick<CaptureInitMessage, CaptureInitStaticKey>;
31
31
  onBehaviorSegment?: (segment: Pick<CaptureBehaviorMessage, 'steps' | 'traits'>) => void;
@@ -1,16 +1,17 @@
1
- import { b as CoachingKind, d as CaptureErrorKind, e as CapturePhase } from './machine-Z0b9Q7zQ.js';
1
+ import { b as CoachingKind, d as CaptureErrorKind, e as CapturePhase } from './machine-DXxarDcC.js';
2
2
 
3
3
  type TerminalKind = 'mint_error' | 'submit_error' | 'token_expired' | 'capture_superseded';
4
4
  interface MountCopy {
5
5
  cvReject?: (attemptIndex: number, kind: CoachingKind) => string;
6
6
  error?: (kind: CaptureErrorKind) => string;
7
+ cameraPolicyBlocked?: () => string;
7
8
  status?: (phase: CapturePhase) => string;
8
9
  coaching?: (kind: CoachingKind) => string;
9
10
  terminal?: (kind: TerminalKind) => string;
10
11
  tryAgain?: string;
11
12
  frameTitle?: string;
12
13
  }
13
- declare const fallbackCopy: Required<Pick<MountCopy, 'cvReject' | 'error' | 'status' | 'coaching' | 'terminal'>> & {
14
+ declare const fallbackCopy: Required<Pick<MountCopy, 'cvReject' | 'error' | 'status' | 'coaching' | 'terminal' | 'cameraPolicyBlocked'>> & {
14
15
  tryAgain: () => string;
15
16
  frameTitle: () => string;
16
17
  };
@@ -1 +1 @@
1
- .checktiv-cf-field{display:flex;flex-direction:column;gap:0.375rem;margin-bottom:1rem}.checktiv-cf-label{font-size:0.875rem;font-weight:500;color:var(--theme-on-surface-1, #16181d)}.checktiv-cf-help{margin:0;font-size:0.8125rem;color:var(--theme-on-surface-1-muted, rgba(22, 24, 29, 0.62))}.checktiv-cf-input,.checktiv-cf-select{width:100%;box-sizing:border-box;padding:0.5rem 0.75rem;font-size:0.9375rem;font-family:inherit;line-height:1.5;color:var(--theme-on-surface-1, #16181d);background-color:var(--theme-surface-1, #ffffff);border:1px solid var(--theme-border-strong, rgba(22, 24, 29, 0.18));border-radius:var(--theme-button-border-radius, 0.4rem);outline:none;transition:border-color 0.15s ease,box-shadow 0.15s ease}.checktiv-cf-input::placeholder{color:var(--theme-on-surface-1-muted, rgba(22, 24, 29, 0.62))}textarea.checktiv-cf-input{min-height:6rem;resize:vertical}.checktiv-cf-input:focus,.checktiv-cf-select:focus{border-color:var(--theme-primary, #2563eb);box-shadow:0 0 0 3px var(--theme-ring, rgba(37, 99, 235, 0.35))}.checktiv-cf-multiselect input[type=checkbox],.checktiv-cf-radio{width:1rem;height:1rem;accent-color:var(--theme-primary, #2563eb)}.checktiv-cf-radiogroup{display:flex;flex-direction:row;gap:1.25rem;margin:0;padding:0;border:0}.checktiv-cf-radio-option{display:inline-flex;align-items:center;gap:0.5rem;font-size:0.9375rem;color:var(--theme-on-surface-1, #16181d);cursor:pointer}.checktiv-cf-multiselect{display:flex;flex-direction:column;gap:0.375rem}.checktiv-cf-option{display:flex;align-items:center;gap:0.5rem;font-size:0.9375rem;color:var(--theme-on-surface-1, #16181d)}.checktiv-cf-file{width:100%;box-sizing:border-box;padding:0.5rem 0.75rem;font-size:0.9375rem;font-family:inherit;color:var(--theme-on-surface-1, #16181d);background-color:var(--theme-surface-1, #ffffff);border:1px dashed var(--theme-border-strong, rgba(22, 24, 29, 0.18));border-radius:var(--theme-button-border-radius, 0.4rem)}.checktiv-cf-error{margin:0.125rem 0 0;font-size:0.8125rem;line-height:1.4;color:var(--theme-danger, #dc2626)}.checktiv-cf-input[aria-invalid=true],.checktiv-cf-select[aria-invalid=true],.checktiv-cf-file[aria-invalid=true]{border-color:var(--theme-danger, #dc2626)}.checktiv-cf-input[aria-invalid=true]:focus,.checktiv-cf-select[aria-invalid=true]:focus{border-color:var(--theme-danger, #dc2626);box-shadow:0 0 0 3px var(--theme-danger, #dc2626)}.checktiv-cf-heading{margin:1rem 0 0.5rem;font-size:1.125rem;font-weight:600;color:var(--theme-on-surface-1, #16181d)}.checktiv-cf-paragraph{margin:0 0 1rem;font-size:0.9375rem;line-height:1.6;color:var(--theme-on-surface-1-muted, rgba(22, 24, 29, 0.62))}.checktiv-cf-submit{display:inline-flex;align-items:center;justify-content:center;padding:0.5rem 1.25rem;font-size:0.9375rem;font-weight:600;font-family:inherit;color:var(--theme-on-primary, #ffffff);background-color:var(--theme-primary, #2563eb);border:none;border-radius:var(--theme-button-border-radius, 0.4rem);cursor:pointer;transition:background-color 0.15s ease}.checktiv-cf-submit:hover:not(:disabled){background-color:var(--theme-primary-hover, #1d4ed8)}.checktiv-cf-submit:disabled{opacity:0.55;cursor:not-allowed}
1
+ .checktiv-cf-field{display:flex;flex-direction:column;gap:0.375rem;margin-bottom:1rem}.checktiv-cf-label{font-size:0.875rem;font-weight:500;color:var(--theme-on-surface-1, #16181d)}.checktiv-cf-help{margin:0;font-size:0.8125rem;color:var(--theme-on-surface-1-muted, rgba(22, 24, 29, 0.62))}.checktiv-cf-input,.checktiv-cf-select{width:100%;box-sizing:border-box;padding:0.5rem 0.75rem;font-size:0.9375rem;font-family:inherit;line-height:1.5;color:var(--theme-on-surface-1, #16181d);background-color:var(--theme-surface-1, #ffffff);border:1px solid var(--theme-border-strong, rgba(22, 24, 29, 0.18));border-radius:var(--theme-button-border-radius, 0.4rem);outline:none;transition:border-color 0.15s ease,box-shadow 0.15s ease}.checktiv-cf-input::placeholder{color:var(--theme-on-surface-1-muted, rgba(22, 24, 29, 0.62))}textarea.checktiv-cf-input{min-height:6rem;resize:vertical}.checktiv-cf-input:focus,.checktiv-cf-select:focus{border-color:var(--theme-primary, #2563eb);box-shadow:0 0 0 3px var(--theme-ring, rgba(37, 99, 235, 0.35))}.checktiv-cf-multiselect input[type=checkbox],.checktiv-cf-radio{width:1rem;height:1rem;accent-color:var(--theme-primary, #2563eb)}.checktiv-cf-radiogroup{display:flex;flex-direction:row;gap:1.25rem;margin:0;padding:0;border:0}.checktiv-cf-radio-option{display:inline-flex;align-items:center;gap:0.5rem;font-size:0.9375rem;color:var(--theme-on-surface-1, #16181d);cursor:pointer}.checktiv-cf-multiselect{display:flex;flex-direction:column;gap:0.375rem}.checktiv-cf-option{display:flex;align-items:center;gap:0.5rem;font-size:0.9375rem;color:var(--theme-on-surface-1, #16181d)}.checktiv-cf-file{width:100%;box-sizing:border-box;padding:0.5rem 0.75rem;font-size:0.9375rem;font-family:inherit;color:var(--theme-on-surface-1, #16181d);background-color:var(--theme-surface-1, #ffffff);border:1px dashed var(--theme-border-strong, rgba(22, 24, 29, 0.18));border-radius:var(--theme-button-border-radius, 0.4rem)}.checktiv-cf-error{margin:0.125rem 0 0;font-size:0.8125rem;line-height:1.4;color:var(--theme-danger, #dc2626)}.checktiv-cf-input[aria-invalid=true],.checktiv-cf-select[aria-invalid=true],.checktiv-cf-file[aria-invalid=true]{border-color:var(--theme-danger, #dc2626)}.checktiv-cf-input[aria-invalid=true]:focus,.checktiv-cf-select[aria-invalid=true]:focus{border-color:var(--theme-danger, #dc2626);box-shadow:0 0 0 3px var(--theme-danger, #dc2626)}.checktiv-cf-heading{margin:1rem 0 0.5rem;font-size:1.125rem;font-weight:600;color:var(--theme-on-surface-1, #16181d)}.checktiv-cf-paragraph{margin:0 0 1rem;font-size:0.9375rem;line-height:1.6;color:var(--theme-on-surface-1-muted, rgba(22, 24, 29, 0.62))}.checktiv-cf-submit{display:inline-flex;align-items:center;justify-content:center;padding:0.5rem 1.25rem;font-size:0.9375rem;font-weight:600;font-family:inherit;color:var(--theme-on-primary, #ffffff);background-color:var(--theme-primary, #2563eb);border:none;border-radius:var(--theme-button-border-radius, 0.4rem);cursor:pointer;transition:background-color 0.15s ease}.checktiv-cf-submit:hover:not(:disabled){background-color:var(--theme-primary-hover, #1d4ed8)}.checktiv-cf-submit:disabled{opacity:0.55;cursor:not-allowed}.checktiv-cf-submit[aria-busy=true]{cursor:progress}.checktiv-cf-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0}
@@ -1,4 +1,4 @@
1
- export { N as ChecktivCustomFormEvent, O as CustomFormCopy, Q as CustomFormFieldCopy, U as CustomFormHandle, V as CustomFormMountOptions, W as createCustomForm } from './api-DicBOi5f.js';
2
- import './machine-Z0b9Q7zQ.js';
3
- import './copy-DVW_qbbM.js';
1
+ export { W as ChecktivCustomFormEvent, X as CustomFormCopy, Y as CustomFormFieldCopy, Z as CustomFormHandle, _ as CustomFormMountOptions, $ as createCustomForm } from './api-EY_fOZm-.js';
2
+ import './machine-DXxarDcC.js';
3
+ import './copy-D6Sd0BIe.js';
4
4
  import './copy-DCeQ4JKx.js';
@@ -1,15 +1,14 @@
1
- import { registerModule } from './chunk-GFHNOZVO.js';
2
- import { createChecktivError, mapHttpStatusToError } from './chunk-S24BZWVR.js';
3
- import { warnWrongTokenPlane, isRecord, isJourneyPlaneBody } from './chunk-523TT3PD.js';
4
- import { assertNever } from './chunk-UBQTPS5J.js';
5
- import { withTokenRetry } from './chunk-S2OOEDJS.js';
6
- import { SESSIONS_ME_PATH, dataPlaneHeaders, stepSubmitPath, formUploadUrlPath } from './chunk-HFQJYEGZ.js';
7
1
  import { u } from './chunk-HV2QKVJX.js';
8
2
  import { R, k, S } from './chunk-XOGHMNBX.js';
3
+ import { registerModule } from './chunk-GFHNOZVO.js';
4
+ import { warnWrongTokenPlane, isRecord, isJourneyPlaneBody } from './chunk-YK4WW4LX.js';
9
5
  import './chunk-IQKHRPJR.js';
6
+ import { assertNever } from './chunk-UBQTPS5J.js';
7
+ import { withTokenRetry, isChecktivError, createChecktivError, mapHttpStatusToError } from './chunk-C7GRMEYT.js';
8
+ import { SESSIONS_ME_PATH, dataPlaneHeaders, stepSubmitPath, formUploadUrlPath } from './chunk-HFQJYEGZ.js';
10
9
  import './chunk-QFA3K5ZV.js';
11
10
  import './chunk-AIK7CDV6.js';
12
11
 
13
- function describedBy(props){const ids=[];if(props.copy?.helpText!==void 0)ids.push(`${props.id}-help`);if(props.error!==void 0)ids.push(`${props.id}-error`);return ids.length>0?ids.join(" "):void 0}function ariaInvalid(props){return props.error!==void 0?"true":void 0}function labelText(props){return props.copy?.label??props.field.id}function labelIdFor(controlId){return `${controlId}-label`}function FieldShell(props,control){const help=props.copy?.helpText;return u("div",{class:"checktiv-cf-field",children:[u("label",{id:labelIdFor(props.id),for:props.id,class:"checktiv-cf-label",children:labelText(props)}),help!==void 0?u("p",{id:`${props.id}-help`,class:"checktiv-cf-help",children:help}):null,control,props.error!==void 0?u("p",{id:`${props.id}-error`,class:"checktiv-cf-error",role:"alert",children:props.error}):null]})}function asText(value){return typeof value==="string"?value:""}function asInputValue(value){return typeof value==="number"?String(value):asText(value)}function inputTypeFor(type){switch(type){case "email":return "email";case "phone":return "tel";case "date":return "date";case "number":return "number";default:return "text"}}function renderTextLike(props){const{field}=props;const onInput=e=>{const target=e.target;if(field.type==="number"){const input=target;props.onChange(input.value===""||Number.isNaN(input.valueAsNumber)?void 0:input.valueAsNumber);return}props.onChange(target.value);};if(field.type==="long_text"){return FieldShell(props,u("textarea",{id:props.id,name:field.id,required:field.required,class:"checktiv-cf-input",value:asInputValue(props.value),"aria-invalid":ariaInvalid(props),"aria-describedby":describedBy(props),onInput,onBlur:props.onBlur}))}return FieldShell(props,u("input",{id:props.id,name:field.id,type:inputTypeFor(field.type),required:field.required,class:"checktiv-cf-input",value:asInputValue(props.value),"aria-invalid":ariaInvalid(props),"aria-describedby":describedBy(props),onInput,onBlur:props.onBlur}))}function renderBoolean(props){const yesId=`${props.id}-yes`;const noId=`${props.id}-no`;return FieldShell(props,u("fieldset",{class:"checktiv-cf-radiogroup",role:"radiogroup","aria-labelledby":labelIdFor(props.id),"aria-required":props.field.required?"true":void 0,"aria-invalid":ariaInvalid(props),"aria-describedby":describedBy(props),children:[u("label",{for:yesId,class:"checktiv-cf-radio-option",children:[u("input",{id:yesId,name:props.field.id,type:"radio",class:"checktiv-cf-radio",checked:props.value===true,onChange:e=>{if(e.target.checked)props.onChange(true);}}),props.booleanYes]}),u("label",{for:noId,class:"checktiv-cf-radio-option",children:[u("input",{id:noId,name:props.field.id,type:"radio",class:"checktiv-cf-radio",checked:props.value===false,onChange:e=>{if(e.target.checked)props.onChange(false);}}),props.booleanNo]})]}))}function optionLabel(props,value){return props.copy?.options?.[value]??value}function renderSingleSelect(props){const options=props.field.options??[];return FieldShell(props,u("select",{id:props.id,name:props.field.id,required:props.field.required,class:"checktiv-cf-select",value:asText(props.value),"aria-invalid":ariaInvalid(props),"aria-describedby":describedBy(props),onChange:e=>props.onChange(e.target.value),children:[u("option",{value:"",children:""}),options.map(o=>u("option",{value:o.value,children:optionLabel(props,o.value)}))]}))}function renderMultiSelect(props){const options=props.field.options??[];const selected=Array.isArray(props.value)?props.value:[];const toggle=(value,checked)=>{const next=checked?[...selected,value]:selected.filter(v=>v!==value);props.onChange(next);};return FieldShell(props,u("div",{class:"checktiv-cf-multiselect",role:"group","aria-labelledby":labelIdFor(props.id),"aria-invalid":ariaInvalid(props),"aria-describedby":describedBy(props),children:options.map(o=>u("label",{class:"checktiv-cf-option",children:[u("input",{type:"checkbox",name:props.field.id,value:o.value,checked:selected.includes(o.value),onChange:e=>toggle(o.value,e.target.checked)}),optionLabel(props,o.value)]}))}))}function renderFileUpload(props){return FieldShell(props,u("input",{id:props.id,name:props.field.id,type:"file",class:"checktiv-cf-file",required:props.field.required,"aria-invalid":ariaInvalid(props),"aria-describedby":describedBy(props),onChange:e=>{const files=e.target.files;props.onFile(files&&files.length>0?files[0]:null);}}))}function renderContent(props){const text=props.copy?.label??props.field.id;return props.field.type==="content_heading"?u("h2",{class:"checktiv-cf-heading",children:text}):u("p",{class:"checktiv-cf-paragraph",children:text})}function renderField(props){switch(props.field.type){case "short_text":case "long_text":case "email":case "phone":case "date":case "number":return renderTextLike(props);case "boolean":return renderBoolean(props);case "single_select":return renderSingleSelect(props);case "multi_select":return renderMultiSelect(props);case "file_upload":return renderFileUpload(props);case "content_heading":case "content_paragraph":return renderContent(props);default:{const _exhaustive=props.field.type;return _exhaustive}}}var CLIENT_PHONE_RE=/^\+?[0-9 ().-]{6,24}$/;var CLIENT_EMAIL_RE=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function isEmptyAnswer(answer){if(answer===void 0)return true;if(typeof answer==="string")return answer.length===0;if(Array.isArray(answer))return answer.length===0;return false}function validateField(field,answer){const requiredIfEmpty=()=>isEmptyAnswer(answer)?field.required?"required":void 0:void 0;switch(field.type){case "short_text":case "long_text":case "date":case "file_upload":return requiredIfEmpty();case "boolean":return field.required&&answer===void 0?"required":void 0;case "email":{if(isEmptyAnswer(answer))return field.required?"required":void 0;return typeof answer==="string"&&!CLIENT_EMAIL_RE.test(answer)?"invalid_email":void 0}case "phone":{if(isEmptyAnswer(answer))return field.required?"required":void 0;return typeof answer==="string"&&!CLIENT_PHONE_RE.test(answer)?"invalid_phone":void 0}case "number":{if(isEmptyAnswer(answer))return field.required?"required":void 0;if(typeof answer!=="number")return void 0;const min=field.validation?.min;const max=field.validation?.max;if(min!==void 0&&answer<min)return "out_of_range";if(max!==void 0&&answer>max)return "out_of_range";return void 0}case "single_select":{if(isEmptyAnswer(answer))return field.required?"required":void 0;const options=field.options??[];if(typeof answer==="string"&&options.length>0){return options.some(o=>o.value===answer)?void 0:"invalid_option"}return void 0}case "multi_select":{const selected=Array.isArray(answer)?answer:[];if(selected.length===0)return field.required?"required":void 0;const min=field.validation?.minSelections;const max=field.validation?.maxSelections;if(min!==void 0&&selected.length<min)return "out_of_range";if(max!==void 0&&selected.length>max)return "out_of_range";return void 0}case "content_heading":case "content_paragraph":return void 0;default:return assertNever(field.type)}}function collectAnswers(answers){const blob={};for(const[fieldId,value]of answers){if(value===void 0)continue;if(typeof value==="string"&&value.length===0)continue;blob[fieldId]=value;}return blob}function isRecord2(v){return typeof v==="object"&&v!==null}function parseUploadTarget(body){if(!isRecord2(body)||!isRecord2(body.data))return null;const d=body.data;const uploadUrl=d.upload_url;const r2Key=d.r2_key;if(typeof uploadUrl!=="string"||uploadUrl.length===0)return null;if(typeof r2Key!=="string"||r2Key.length===0)return null;return {uploadUrl,r2Key}}function extensionOf(fileName){const dot=fileName.lastIndexOf(".");if(dot<0||dot===fileName.length-1)return "";return fileName.slice(dot+1).toLowerCase()}async function uploadFormFile(ctx,fetchImpl,stepId,fieldId,file){const origin=ctx.apiBaseOrigin;let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(origin+formUploadUrlPath(stepId),{method:"POST",headers:dataPlaneHeaders(ctx,token,{withJsonBody:true}),body:JSON.stringify({fieldId,ext:extensionOf(file.name),contentLength:file.size})}),result=>result?.status===401);}catch{return null}if(!res.ok)return null;let body;try{body=await res.json();}catch{return null}const target=parseUploadTarget(body);if(target===null)return null;let putRes;try{putRes=await fetchImpl(target.uploadUrl,{method:"PUT",headers:{"content-type":file.type||"application/octet-stream"},body:file});}catch{return null}if(!putRes.ok)return null;return target.r2Key}var FALLBACK={submit:"Continue",requiredError:"This field is required.",invalidPhoneError:"Enter a valid phone number.",invalidEmailError:"Enter a valid email address.",invalidDateError:"Enter a valid date.",invalidOptionError:"Choose one of the available options.",outOfRangeError:"That value is outside the allowed range.",invalidFormatError:"That value is not in the expected format.",invalidError:"That value is not valid.",validationError:"Some answers could not be accepted. Review your entries and try again.",uploadError:"That file could not be uploaded. Choose the file and try again.",submitError:"Something went wrong submitting the form. Please try again.",booleanYes:"Yes",booleanNo:"No"};function resolveCopy(copy){return {submit:copy?.submit??FALLBACK.submit,requiredError:copy?.requiredError??FALLBACK.requiredError,invalidPhoneError:copy?.invalidPhoneError??FALLBACK.invalidPhoneError,invalidEmailError:copy?.invalidEmailError??FALLBACK.invalidEmailError,invalidDateError:copy?.invalidDateError??FALLBACK.invalidDateError,invalidOptionError:copy?.invalidOptionError??FALLBACK.invalidOptionError,outOfRangeError:copy?.outOfRangeError??FALLBACK.outOfRangeError,invalidFormatError:copy?.invalidFormatError??FALLBACK.invalidFormatError,invalidError:copy?.invalidError??FALLBACK.invalidError,validationError:copy?.validationError??FALLBACK.validationError,uploadError:copy?.uploadError??FALLBACK.uploadError,submitError:copy?.submitError??FALLBACK.submitError,booleanYes:copy?.booleanYes??FALLBACK.booleanYes,booleanNo:copy?.booleanNo??FALLBACK.booleanNo}}function messageForReason(chrome,reason){const byReason={required:chrome.requiredError,invalid_phone:chrome.invalidPhoneError,invalid_email:chrome.invalidEmailError,invalid_date:chrome.invalidDateError,invalid_option:chrome.invalidOptionError,out_of_range:chrome.outOfRangeError,invalid_format:chrome.invalidFormatError,invalid:chrome.invalidError};return byReason[reason]}var CUSTOM_FORM_FIELD_ERROR_REASONS=["required","invalid_phone","invalid_email","invalid_date","invalid_option","out_of_range","invalid_format","invalid"];var REASON_SET=new Set(CUSTOM_FORM_FIELD_ERROR_REASONS);function isCustomFormFieldErrorReason(value){return REASON_SET.has(value)}function createCustomFormErrorEvent(code){return {type:"checktiv.custom_form.error",error:createChecktivError(code)}}function resolveTarget(target){if(typeof target!=="string")return target;if(typeof document==="undefined")return null;return document.querySelector(target)}async function resolveSessionIdentity(ctx,fetchImpl){let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(ctx.apiBaseOrigin+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"}}if(!isRecord(body))return {kind:"unresolved"};if(isRecord(body.data)&&body.data.renderable===false){return {kind:"unresolved"}}const data=body.data;if(isRecord(data)){const sessionId=data.session_id;const stepId=data.step_id;if(typeof sessionId==="string"&&sessionId.length>0&&typeof stepId==="string"&&stepId.length>0){ctx.setSessionId(sessionId);return {kind:"ok",identity:{sessionId,stepId}}}}return isJourneyPlaneBody(body)?{kind:"wrong_token"}:{kind:"unresolved"}}async function parseFieldErrors(res){let body;try{body=await res.json();}catch{return null}if(typeof body!=="object"||body===null)return null;const fieldErrors=body.fieldErrors;if(typeof fieldErrors!=="object"||fieldErrors===null)return null;const out=new Map;for(const[fieldId,reason]of Object.entries(fieldErrors)){if(typeof reason==="string"&&isCustomFormFieldErrorReason(reason)){out.set(fieldId,reason);}}return out}function noopHandle(){return {destroy:()=>void 0}}function createCustomForm(ctx,opts){const element=resolveTarget(opts.target);if(element===null){console.warn('[Checktiv] mount("custom_form"): 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;const chrome=resolveCopy(opts.copy);const answers=new Map;const pendingFiles=new Map;const errors=new Map;let formError=null;let identity=null;let submitting=false;let cancelled=false;const PENDING_FILE_SENTINEL="\0pending-file";const clearFieldError=fieldId=>{const clearedField=errors.delete(fieldId);const clearedForm=formError!==null;formError=null;if(clearedField||clearedForm)paint();};const focusField=fieldId=>{element.querySelector(`[name="${fieldId}"]`)?.focus();};const validateAll=()=>{errors.clear();let firstInvalid=null;for(const field of opts.config.fields){const answer=pendingFiles.has(field.id)?PENDING_FILE_SENTINEL:answers.get(field.id);const reason=validateField(field,answer);if(reason!==void 0){errors.set(field.id,reason);if(firstInvalid===null)firstInvalid=field.id;}}return firstInvalid};const applyServerFieldErrors=fieldErrors=>{errors.clear();formError=null;const knownFieldIds=new Set(opts.config.fields.map(f=>f.id));for(const[fieldId,reason]of fieldErrors){if(knownFieldIds.has(fieldId))errors.set(fieldId,reason);}if(errors.size===0)formError=chrome.validationError;paint();const first=opts.config.fields.find(f=>errors.has(f.id));if(first!==void 0)focusField(first.id);};const paint=()=>{if(cancelled)return;R(k(S,null,[...opts.config.fields.map(field=>{const reason=errors.get(field.id);return renderField({field,copy:opts.copy?.fields?.[field.id],value:answers.get(field.id),id:`checktiv-cf-${field.id}`,error:reason!==void 0?messageForReason(chrome,reason):void 0,booleanYes:chrome.booleanYes,booleanNo:chrome.booleanNo,onChange:next=>{answers.set(field.id,next);if(field.type==="multi_select"||field.type==="boolean"||field.type==="single_select"){const clearedField=errors.delete(field.id);const clearedForm=formError!==null;formError=null;if(field.type==="multi_select"||clearedField||clearedForm)paint();}},onBlur:()=>clearFieldError(field.id),onFile:file=>{if(file===null){pendingFiles.delete(field.id);answers.delete(field.id);}else {pendingFiles.set(field.id,file);}clearFieldError(field.id);}})}),formError!==null?k("p",{class:"checktiv-cf-error",role:"alert",id:"checktiv-cf-form-error"},formError):null,k("button",{type:"submit",class:"checktiv-cf-submit",disabled:opts.preview===true,onClick:e=>{e.preventDefault();if(opts.preview===true)return;void onSubmit();}},chrome.submit)]),element);};async function onSubmit(){if(submitting||cancelled)return;formError=null;const firstInvalid=validateAll();if(firstInvalid!==null){paint();focusField(firstInvalid);return}if(identity===null){emit(createCustomFormErrorEvent("session_expired"));return}const session=identity;submitting=true;for(const[fieldId,file]of pendingFiles){const key=await uploadFormFile(ctx,fetchImpl,session.stepId,fieldId,file);if(cancelled)return;if(key===null){emit(createCustomFormErrorEvent("upload_failed"));submitting=false;return}answers.set(fieldId,key);}pendingFiles.clear();const blob=collectAnswers(answers);let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(ctx.apiBaseOrigin+stepSubmitPath(session.sessionId,session.stepId),{method:"POST",headers:dataPlaneHeaders(ctx,token,{withJsonBody:true}),body:JSON.stringify(blob)}),result=>result?.status===401);}catch(err){console.warn("[Checktiv] custom_form submit request failed.",err);submitting=false;return}if(cancelled)return;if(!res.ok){if(res.status===422){const fieldErrors=await parseFieldErrors(res);if(cancelled)return;if(fieldErrors!==null&&fieldErrors.size>0){applyServerFieldErrors(fieldErrors);}else {formError=chrome.validationError;paint();}submitting=false;return}if(res.status===400){formError=chrome.validationError;paint();submitting=false;return}emit(createCustomFormErrorEvent(mapHttpStatusToError(res.status)));submitting=false;return}emit({type:"checktiv.custom_form.submitted",sessionId:session.sessionId});}if(opts.preview===true){paint();emit({type:"checktiv.custom_form.ready"});return {destroy(){if(cancelled)return;cancelled=true;R(null,element);}}}void(async()=>{try{if(opts.session!==void 0){identity=opts.session;}else {const resolution=await resolveSessionIdentity(ctx,fetchImpl);if(cancelled)return;switch(resolution.kind){case "ok":identity=resolution.identity;break;case "wrong_token":warnWrongTokenPlane();emit(createCustomFormErrorEvent("wrong_token_type"));return;case "unresolved":emit(createCustomFormErrorEvent("session_expired"));return;default:return assertNever(resolution)}}if(cancelled)return;paint();emit({type:"checktiv.custom_form.ready"});}catch(err){if(cancelled)return;console.warn('[Checktiv] mount("custom_form") setup failed.',err);emit(createCustomFormErrorEvent("sdk_load_failed"));}})();return {destroy(){if(cancelled)return;cancelled=true;R(null,element);}}}registerModule("custom_form",createCustomForm);
12
+ function describedBy(props){const ids=[];if(props.copy?.helpText!==void 0)ids.push(`${props.id}-help`);if(props.error!==void 0)ids.push(`${props.id}-error`);return ids.length>0?ids.join(" "):void 0}function ariaInvalid(props){return props.error!==void 0?"true":void 0}function labelText(props){return props.copy?.label??props.field.id}function labelIdFor(controlId){return `${controlId}-label`}function FieldShell(props,control){const help=props.copy?.helpText;return u("div",{class:"checktiv-cf-field",children:[u("label",{id:labelIdFor(props.id),for:props.id,class:"checktiv-cf-label",children:labelText(props)}),help!==void 0?u("p",{id:`${props.id}-help`,class:"checktiv-cf-help",children:help}):null,control,props.error!==void 0?u("p",{id:`${props.id}-error`,class:"checktiv-cf-error",role:"alert",children:props.error}):null]})}function asText(value){return typeof value==="string"?value:""}function asInputValue(value){return typeof value==="number"?String(value):asText(value)}function inputTypeFor(type){switch(type){case "email":return "email";case "phone":return "tel";case "date":return "date";case "number":return "number";default:return "text"}}function renderTextLike(props){const{field}=props;const onInput=e=>{const target=e.target;if(field.type==="number"){const input=target;props.onChange(input.value===""||Number.isNaN(input.valueAsNumber)?void 0:input.valueAsNumber);return}props.onChange(target.value);};if(field.type==="long_text"){return FieldShell(props,u("textarea",{id:props.id,name:field.id,required:field.required,class:"checktiv-cf-input",value:asInputValue(props.value),"aria-invalid":ariaInvalid(props),"aria-describedby":describedBy(props),onInput,onBlur:props.onBlur}))}return FieldShell(props,u("input",{id:props.id,name:field.id,type:inputTypeFor(field.type),required:field.required,class:"checktiv-cf-input",value:asInputValue(props.value),"aria-invalid":ariaInvalid(props),"aria-describedby":describedBy(props),onInput,onBlur:props.onBlur}))}function renderBoolean(props){const yesId=`${props.id}-yes`;const noId=`${props.id}-no`;return FieldShell(props,u("fieldset",{class:"checktiv-cf-radiogroup",role:"radiogroup","aria-labelledby":labelIdFor(props.id),"aria-required":props.field.required?"true":void 0,"aria-invalid":ariaInvalid(props),"aria-describedby":describedBy(props),children:[u("label",{for:yesId,class:"checktiv-cf-radio-option",children:[u("input",{id:yesId,name:props.field.id,type:"radio",class:"checktiv-cf-radio",checked:props.value===true,onChange:e=>{if(e.target.checked)props.onChange(true);}}),props.booleanYes]}),u("label",{for:noId,class:"checktiv-cf-radio-option",children:[u("input",{id:noId,name:props.field.id,type:"radio",class:"checktiv-cf-radio",checked:props.value===false,onChange:e=>{if(e.target.checked)props.onChange(false);}}),props.booleanNo]})]}))}function optionLabel(props,value){return props.copy?.options?.[value]??value}function renderSingleSelect(props){const options=props.field.options??[];return FieldShell(props,u("select",{id:props.id,name:props.field.id,required:props.field.required,class:"checktiv-cf-select",value:asText(props.value),"aria-invalid":ariaInvalid(props),"aria-describedby":describedBy(props),onChange:e=>props.onChange(e.target.value),children:[u("option",{value:"",children:""}),options.map(o=>u("option",{value:o.value,children:optionLabel(props,o.value)}))]}))}function renderMultiSelect(props){const options=props.field.options??[];const selected=Array.isArray(props.value)?props.value:[];const toggle=(value,checked)=>{const next=checked?[...selected,value]:selected.filter(v=>v!==value);props.onChange(next);};return FieldShell(props,u("div",{class:"checktiv-cf-multiselect",role:"group","aria-labelledby":labelIdFor(props.id),"aria-invalid":ariaInvalid(props),"aria-describedby":describedBy(props),children:options.map(o=>u("label",{class:"checktiv-cf-option",children:[u("input",{type:"checkbox",name:props.field.id,value:o.value,checked:selected.includes(o.value),onChange:e=>toggle(o.value,e.target.checked)}),optionLabel(props,o.value)]}))}))}function renderFileUpload(props){return FieldShell(props,u("input",{id:props.id,name:props.field.id,type:"file",class:"checktiv-cf-file",required:props.field.required,"aria-invalid":ariaInvalid(props),"aria-describedby":describedBy(props),onChange:e=>{const files=e.target.files;props.onFile(files&&files.length>0?files[0]:null);}}))}function renderContent(props){const text=props.copy?.label??props.field.id;return props.field.type==="content_heading"?u("h2",{class:"checktiv-cf-heading",children:text}):u("p",{class:"checktiv-cf-paragraph",children:text})}function renderField(props){switch(props.field.type){case "short_text":case "long_text":case "email":case "phone":case "date":case "number":return renderTextLike(props);case "boolean":return renderBoolean(props);case "single_select":return renderSingleSelect(props);case "multi_select":return renderMultiSelect(props);case "file_upload":return renderFileUpload(props);case "content_heading":case "content_paragraph":return renderContent(props);default:{const _exhaustive=props.field.type;return _exhaustive}}}var CLIENT_PHONE_RE=/^\+?[0-9 ().-]{6,24}$/;var CLIENT_EMAIL_RE=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function isEmptyAnswer(answer){if(answer===void 0)return true;if(typeof answer==="string")return answer.length===0;if(Array.isArray(answer))return answer.length===0;return false}function validateField(field,answer){const requiredIfEmpty=()=>isEmptyAnswer(answer)?field.required?"required":void 0:void 0;switch(field.type){case "short_text":case "long_text":case "date":case "file_upload":return requiredIfEmpty();case "boolean":return field.required&&answer===void 0?"required":void 0;case "email":{if(isEmptyAnswer(answer))return field.required?"required":void 0;return typeof answer==="string"&&!CLIENT_EMAIL_RE.test(answer)?"invalid_email":void 0}case "phone":{if(isEmptyAnswer(answer))return field.required?"required":void 0;return typeof answer==="string"&&!CLIENT_PHONE_RE.test(answer)?"invalid_phone":void 0}case "number":{if(isEmptyAnswer(answer))return field.required?"required":void 0;if(typeof answer!=="number")return void 0;const min=field.validation?.min;const max=field.validation?.max;if(min!==void 0&&answer<min)return "out_of_range";if(max!==void 0&&answer>max)return "out_of_range";return void 0}case "single_select":{if(isEmptyAnswer(answer))return field.required?"required":void 0;const options=field.options??[];if(typeof answer==="string"&&options.length>0){return options.some(o=>o.value===answer)?void 0:"invalid_option"}return void 0}case "multi_select":{const selected=Array.isArray(answer)?answer:[];if(selected.length===0)return field.required?"required":void 0;const min=field.validation?.minSelections;const max=field.validation?.maxSelections;if(min!==void 0&&selected.length<min)return "out_of_range";if(max!==void 0&&selected.length>max)return "out_of_range";return void 0}case "content_heading":case "content_paragraph":return void 0;default:return assertNever(field.type)}}function collectAnswers(answers){const blob={};for(const[fieldId,value]of answers){if(value===void 0)continue;if(typeof value==="string"&&value.length===0)continue;blob[fieldId]=value;}return blob}function isRecord2(v){return typeof v==="object"&&v!==null}function parseUploadTarget(body){if(!isRecord2(body)||!isRecord2(body.data))return null;const d=body.data;const uploadUrl=d.upload_url;const r2Key=d.r2_key;if(typeof uploadUrl!=="string"||uploadUrl.length===0)return null;if(typeof r2Key!=="string"||r2Key.length===0)return null;return {uploadUrl,r2Key}}function extensionOf(fileName){const dot=fileName.lastIndexOf(".");if(dot<0||dot===fileName.length-1)return "";return fileName.slice(dot+1).toLowerCase()}async function uploadFormFile(ctx,fetchImpl,stepId,fieldId,file){const origin=ctx.apiBaseOrigin;let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(origin+formUploadUrlPath(stepId),{method:"POST",headers:dataPlaneHeaders(ctx,token,{withJsonBody:true}),body:JSON.stringify({fieldId,ext:extensionOf(file.name),contentLength:file.size})}));}catch{return null}if(!res.ok)return null;let body;try{body=await res.json();}catch{return null}const target=parseUploadTarget(body);if(target===null)return null;let putRes;try{putRes=await fetchImpl(target.uploadUrl,{method:"PUT",headers:{"content-type":file.type||"application/octet-stream"},body:file});}catch{return null}if(!putRes.ok)return null;return target.r2Key}var FALLBACK={submit:"Continue",submitPending:"Submitting\u2026",requiredError:"This field is required.",invalidPhoneError:"Enter a valid phone number.",invalidEmailError:"Enter a valid email address.",invalidDateError:"Enter a valid date.",invalidOptionError:"Choose one of the available options.",outOfRangeError:"That value is outside the allowed range.",invalidFormatError:"That value is not in the expected format.",invalidError:"That value is not valid.",validationError:"Some answers could not be accepted. Review your entries and try again.",uploadError:"That file could not be uploaded. Choose the file and try again.",submitError:"Something went wrong submitting the form. Please try again.",booleanYes:"Yes",booleanNo:"No"};function resolveCopy(copy){return {submit:copy?.submit??FALLBACK.submit,submitPending:copy?.submitPending??FALLBACK.submitPending,requiredError:copy?.requiredError??FALLBACK.requiredError,invalidPhoneError:copy?.invalidPhoneError??FALLBACK.invalidPhoneError,invalidEmailError:copy?.invalidEmailError??FALLBACK.invalidEmailError,invalidDateError:copy?.invalidDateError??FALLBACK.invalidDateError,invalidOptionError:copy?.invalidOptionError??FALLBACK.invalidOptionError,outOfRangeError:copy?.outOfRangeError??FALLBACK.outOfRangeError,invalidFormatError:copy?.invalidFormatError??FALLBACK.invalidFormatError,invalidError:copy?.invalidError??FALLBACK.invalidError,validationError:copy?.validationError??FALLBACK.validationError,uploadError:copy?.uploadError??FALLBACK.uploadError,submitError:copy?.submitError??FALLBACK.submitError,booleanYes:copy?.booleanYes??FALLBACK.booleanYes,booleanNo:copy?.booleanNo??FALLBACK.booleanNo}}function messageForReason(chrome,reason){const byReason={required:chrome.requiredError,invalid_phone:chrome.invalidPhoneError,invalid_email:chrome.invalidEmailError,invalid_date:chrome.invalidDateError,invalid_option:chrome.invalidOptionError,out_of_range:chrome.outOfRangeError,invalid_format:chrome.invalidFormatError,invalid:chrome.invalidError};return byReason[reason]}var CUSTOM_FORM_FIELD_ERROR_REASONS=["required","invalid_phone","invalid_email","invalid_date","invalid_option","out_of_range","invalid_format","invalid"];var REASON_SET=new Set(CUSTOM_FORM_FIELD_ERROR_REASONS);function isCustomFormFieldErrorReason(value){return REASON_SET.has(value)}function createCustomFormErrorEvent(code){return {type:"checktiv.custom_form.error",error:createChecktivError(code)}}function resolveTarget(target){if(typeof target!=="string")return target;if(typeof document==="undefined")return null;return document.querySelector(target)}async function resolveSessionIdentity(ctx,fetchImpl){let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(ctx.apiBaseOrigin+SESSIONS_ME_PATH,{method:"GET",headers:dataPlaneHeaders(ctx,token)}));}catch(err){if(isChecktivError(err)&&err.code==="session_parked")return {kind:"parked"};return {kind:"unresolved"}}if(!res.ok)return {kind:"unresolved"};let body;try{body=await res.json();}catch{return {kind:"unresolved"}}if(!isRecord(body))return {kind:"unresolved"};if(isRecord(body.data)&&body.data.renderable===false){return {kind:"unresolved"}}const data=body.data;if(isRecord(data)){const sessionId=data.session_id;const stepId=data.step_id;if(typeof sessionId==="string"&&sessionId.length>0&&typeof stepId==="string"&&stepId.length>0){ctx.setSessionId(sessionId);return {kind:"ok",identity:{sessionId,stepId}}}}return isJourneyPlaneBody(body)?{kind:"wrong_token"}:{kind:"unresolved"}}async function parseFieldErrors(res){let body;try{body=await res.json();}catch{return null}if(typeof body!=="object"||body===null)return null;const fieldErrors=body.fieldErrors;if(typeof fieldErrors!=="object"||fieldErrors===null)return null;const out=new Map;for(const[fieldId,reason]of Object.entries(fieldErrors)){if(typeof reason==="string"&&isCustomFormFieldErrorReason(reason)){out.set(fieldId,reason);}}return out}function isPromiseLike(value){return typeof value==="object"&&value!==null&&"then"in value&&typeof value.then==="function"}function noopHandle(){return {destroy:()=>void 0}}function createCustomForm(ctx,opts){const element=resolveTarget(opts.target);if(element===null){console.warn('[Checktiv] mount("custom_form"): no target element found. Pass an element or a selector that resolves.');return noopHandle()}const warnHostHandlerFailed=err=>{console.warn("[Checktiv] custom_form onEvent handler threw.",err);};const emit=e=>{try{const settled=opts.onEvent?.(e);if(isPromiseLike(settled))void settled.then(void 0,warnHostHandlerFailed);}catch(err){warnHostHandlerFailed(err);}};const fetchImpl=opts.fetchImpl??fetch;const chrome=resolveCopy(opts.copy);const answers=new Map;const pendingFiles=new Map;const errors=new Map;let formError=null;let identity=null;let submitting=false;let cancelled=false;const PENDING_FILE_SENTINEL="\0pending-file";const clearFieldError=fieldId=>{const clearedField=errors.delete(fieldId);const clearedForm=formError!==null;formError=null;if(clearedField||clearedForm)paint();};const endSubmitting=()=>{submitting=false;paint();};const focusField=fieldId=>{element.querySelector(`[name="${fieldId}"]`)?.focus();};const validateAll=()=>{errors.clear();let firstInvalid=null;for(const field of opts.config.fields){const answer=pendingFiles.has(field.id)?PENDING_FILE_SENTINEL:answers.get(field.id);const reason=validateField(field,answer);if(reason!==void 0){errors.set(field.id,reason);if(firstInvalid===null)firstInvalid=field.id;}}return firstInvalid};const applyServerFieldErrors=fieldErrors=>{errors.clear();formError=null;const knownFieldIds=new Set(opts.config.fields.map(f=>f.id));for(const[fieldId,reason]of fieldErrors){if(knownFieldIds.has(fieldId))errors.set(fieldId,reason);}if(errors.size===0)formError=chrome.validationError;paint();const first=opts.config.fields.find(f=>errors.has(f.id));if(first!==void 0)focusField(first.id);};const paint=()=>{if(cancelled)return;R(k(S,null,[...opts.config.fields.map(field=>{const reason=errors.get(field.id);return renderField({field,copy:opts.copy?.fields?.[field.id],value:answers.get(field.id),id:`checktiv-cf-${field.id}`,error:reason!==void 0?messageForReason(chrome,reason):void 0,booleanYes:chrome.booleanYes,booleanNo:chrome.booleanNo,onChange:next=>{answers.set(field.id,next);if(field.type==="multi_select"||field.type==="boolean"||field.type==="single_select"){const clearedField=errors.delete(field.id);const clearedForm=formError!==null;formError=null;if(field.type==="multi_select"||clearedField||clearedForm)paint();}},onBlur:()=>clearFieldError(field.id),onFile:file=>{if(file===null){pendingFiles.delete(field.id);answers.delete(field.id);}else {pendingFiles.set(field.id,file);}clearFieldError(field.id);}})}),formError!==null?k("p",{class:"checktiv-cf-error",role:"alert",id:"checktiv-cf-form-error"},formError):null,k("div",{class:"checktiv-cf-sr-only",role:"status","aria-live":"polite","data-testid":"custom-form-submitting-status"},submitting?chrome.submitPending:""),k("button",{type:"submit",class:"checktiv-cf-submit",disabled:opts.preview===true||submitting,"aria-busy":submitting?"true":"false",onClick:e=>{e.preventDefault();if(opts.preview===true)return;void onSubmit();}},submitting?chrome.submitPending:chrome.submit)]),element);};async function onSubmit(){if(submitting||cancelled)return;formError=null;const firstInvalid=validateAll();if(firstInvalid!==null){paint();focusField(firstInvalid);return}if(identity===null){emit(createCustomFormErrorEvent("session_expired"));return}const session=identity;submitting=true;paint();for(const[fieldId,file]of pendingFiles){const key=await uploadFormFile(ctx,fetchImpl,session.stepId,fieldId,file);if(cancelled)return;if(key===null){endSubmitting();emit(createCustomFormErrorEvent("upload_failed"));return}answers.set(fieldId,key);}pendingFiles.clear();const blob=collectAnswers(answers);let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(ctx.apiBaseOrigin+stepSubmitPath(session.sessionId,session.stepId),{method:"POST",headers:dataPlaneHeaders(ctx,token,{withJsonBody:true}),body:JSON.stringify(blob)}));}catch(err){console.warn("[Checktiv] custom_form submit request failed.",err);formError=chrome.submitError;endSubmitting();return}if(cancelled)return;if(!res.ok){if(res.status===422){const fieldErrors=await parseFieldErrors(res);if(cancelled)return;submitting=false;if(fieldErrors!==null&&fieldErrors.size>0){applyServerFieldErrors(fieldErrors);}else {formError=chrome.validationError;paint();}return}if(res.status===400){formError=chrome.validationError;endSubmitting();return}endSubmitting();emit(createCustomFormErrorEvent(mapHttpStatusToError(res.status)));return}emit({type:"checktiv.custom_form.submitted",sessionId:session.sessionId});}if(opts.preview===true){paint();emit({type:"checktiv.custom_form.ready"});return {destroy(){if(cancelled)return;cancelled=true;R(null,element);}}}void(async()=>{try{if(opts.session!==void 0){identity=opts.session;}else {const resolution=await resolveSessionIdentity(ctx,fetchImpl);if(cancelled)return;switch(resolution.kind){case "ok":identity=resolution.identity;break;case "wrong_token":warnWrongTokenPlane();emit(createCustomFormErrorEvent("wrong_token_type"));return;case "unresolved":emit(createCustomFormErrorEvent("session_expired"));return;case "parked":emit(createCustomFormErrorEvent("session_parked"));return;default:return assertNever(resolution)}}if(cancelled)return;paint();emit({type:"checktiv.custom_form.ready"});}catch(err){if(cancelled)return;console.warn('[Checktiv] mount("custom_form") setup failed.',err);emit(createCustomFormErrorEvent("sdk_load_failed"));}})();return {destroy(){if(cancelled)return;cancelled=true;R(null,element);}}}registerModule("custom_form",createCustomForm);
14
13
 
15
14
  export { createCustomForm };