@kc-one/smart-fill-sdk 0.0.1-beta.2 → 0.0.1-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -1
- package/dist/index.esm.js +2748 -1038
- package/dist/index.umd.cjs +28 -19
- package/dist/src/adapters/element.d.ts +2 -2
- package/dist/src/adapters/element.d.ts.map +1 -1
- package/dist/src/adapters/ui-framework.d.ts +5 -0
- package/dist/src/adapters/ui-framework.d.ts.map +1 -0
- package/dist/src/client/gateway-client.d.ts.map +1 -1
- package/dist/src/config/defaults.d.ts +1 -1
- package/dist/src/config/defaults.d.ts.map +1 -1
- package/dist/src/core/smart-fill-instance.d.ts +25 -1
- package/dist/src/core/smart-fill-instance.d.ts.map +1 -1
- package/dist/src/core/smart-fill.d.ts.map +1 -1
- package/dist/src/filler/dom-filler.d.ts.map +1 -1
- package/dist/src/index.d.ts +6 -6
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/rules/local-rules.d.ts.map +1 -1
- package/dist/src/scanner/dom-scanner.d.ts +7 -1
- package/dist/src/scanner/dom-scanner.d.ts.map +1 -1
- package/dist/src/scanner/ui-frameworks.d.ts +38 -0
- package/dist/src/scanner/ui-frameworks.d.ts.map +1 -0
- package/dist/src/select/address-cascader.d.ts +13 -0
- package/dist/src/select/address-cascader.d.ts.map +1 -0
- package/dist/src/select/custom-select.d.ts +19 -0
- package/dist/src/select/custom-select.d.ts.map +1 -0
- package/dist/src/select/option-match.d.ts +14 -0
- package/dist/src/select/option-match.d.ts.map +1 -0
- package/dist/src/select/select-fill.d.ts +4 -0
- package/dist/src/select/select-fill.d.ts.map +1 -0
- package/dist/src/types/index.d.ts +33 -5
- package/dist/src/types/index.d.ts.map +1 -1
- package/dist/style.css +1 -1
- package/package.json +5 -2
package/dist/index.umd.cjs
CHANGED
|
@@ -1,22 +1,31 @@
|
|
|
1
|
-
(function(p,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(p=typeof globalThis<"u"?globalThis:p||self,b(p.SmartFillSDK={}))})(this,function(p){"use strict";var At=Object.defineProperty;var It=(p,b,S)=>b in p?At(p,b,{enumerable:!0,configurable:!0,writable:!0,value:S}):p[b]=S;var c=(p,b,S)=>It(p,typeof b!="symbol"?b+"":b,S);const b="https://loan.kdbank.cn";class S extends Error{constructor(t){super(t.message);c(this,"smartFillError");this.name="SmartFillException",this.smartFillError=t}}function E(n,e,t,s={}){return new S({code:n,message:e,stage:t,...s})}function Ee(n,e,t="RECOGNIZE_FAILED"){return n instanceof S?n.smartFillError:{code:t,message:n instanceof Error?n.message:String(n||"智能录入异常"),stage:e,retryable:e==="recognize"}}function L(n="sf"){return`${n}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}class xe{constructor(e){c(this,"seToken","");c(this,"baseURL",b);this.config=e}setAccessToken(e){this.seToken=e}async createSession(){if(!/^seKey-[A-Za-z0-9_-]{6,}$/.test(this.config.apiKey))throw E("API_KEY_INVALID","apiKey 格式不正确,应以 seKey- 开头。","setup");return{apiKey:this.config.apiKey,rulesVersion:"0.0.1"}}async getFormConfig(e){return e?this.request(`/sdk/forms/${encodeURIComponent(e)}`,{method:"GET"}):null}async resolveInputText(e){var r,a,o,d;const t=(r=e.images)!=null&&r.length?e.images:[],s=((a=e.text)==null?void 0:a.trim())||"";if(!t.length)return{text:s,usedOcr:!1};(o=e.onStatusChange)==null||o.call(e,"image_uploading");const i=await this.recognizeImages(t);return(d=e.onStatusChange)==null||d.call(e,"image_recognizing"),{text:i,usedOcr:!0}}async recognize(e){var a,o;const t=performance.now(),s=(a=e.text)==null?void 0:a.trim();(o=e.onStatusChange)==null||o.call(e,"recognizing");const i=await this.request("/fcloud/flow-product/agentChat/smartEntry",{method:"POST",body:JSON.stringify({formCode:e.formCode||"",configVersion:e.configVersion||"",formMsg:e.fields.map(({element:d,...l})=>l),userInputMsg:s||""})}),r=we(i,e.fields,e.scanToken);return{scanToken:e.scanToken,suggestions:r,trace:i.trace||{traceId:L("trace"),usedOcr:!!e.usedOcr,usedAi:!0,durationMs:Math.round(performance.now()-t)}}}async recognizeImages(e){const t=new FormData;e.forEach(r=>{t.append("image",r,r.name)});const s=await this.request("/fcloud/flow-product/agentChat/smartEntry/ocr",{method:"POST",body:t}),i=ke(s);if(!i)throw E("RECOGNIZE_FAILED","图片识别未提取到文本内容。","recognize");return i}async request(e,t){const s=new AbortController,i=window.setTimeout(()=>s.abort(),this.config.requestTimeoutMs??3e4),r=new Headers(t.headers);t.body&&!(t.body instanceof FormData)&&!r.has("Content-Type")&&r.set("Content-Type","application/json"),r.set("x-trace-id",L("trace")),this.seToken&&r.set("seToken",`${this.seToken}`);try{const a=await fetch(`${this.baseURL}${e}`,{...t,headers:r,signal:s.signal});if(!a.ok)throw E(Ae(a.status),await a.text(),e.includes("session")?"setup":"recognize",{retryable:a.status>=500||a.status===429});return a.json()}catch(a){throw a instanceof DOMException&&a.name==="AbortError"?E("RECOGNIZE_TIMEOUT","识别请求超时,请稍后重试。","recognize",{retryable:!0}):a}finally{window.clearTimeout(i)}}}const ve=.95;function we(n,e,t){var r;const s=new Map(e.map(a=>[a.fieldId,a]));return(((r=n.data)==null?void 0:r.fieldValues)||[]).filter(a=>!!(a!=null&&a.fieldId)).map(a=>{const o=s.get(a.fieldId);return{fieldId:a.fieldId,scanToken:t,label:a.label||(o==null?void 0:o.label)||a.fieldId,value:a.value,displayValue:a.value==null?"":String(a.value),confidence:Se(a.confidence),source:a.source||"ai",warnings:a.warnings}})}function Se(n){return typeof n!="number"||Number.isNaN(n)?ve:n<0?0:n>1?1:n}function ke(n){var t;const e=typeof n.data=="string"?n.data:((t=n.data)==null?void 0:t.text)||n.text||"";return String(e||"").trim()}function Ae(n){return n===401?"TOKEN_EXPIRED":n===403?"API_KEY_FORBIDDEN":n===404?"FORM_CONFIG_NOT_FOUND":"RECOGNIZE_FAILED"}class _{constructor(){c(this,"handlers",new Map)}on(e,t){const s=this.handlers.get(e)??new Set;return s.add(t),this.handlers.set(e,s),()=>this.off(e,t)}off(e,t){var s;(s=this.handlers.get(e))==null||s.delete(t)}emit(e,t){var s;(s=this.handlers.get(e))==null||s.forEach(i=>i(t))}clear(){this.handlers.clear()}}class Ie{constructor(){c(this,"instances",new Set);c(this,"active",null)}add(e){this.instances.add(e)}activate(e){this.active&&this.active!==e&&this.active.close(),this.active=e}remove(e){this.instances.delete(e),this.active===e&&(this.active=null)}destroyAll(){this.instances.forEach(e=>e.destroy()),this.instances.clear(),this.active=null}}const Ce=[".el-select",".el-date-editor",".el-time-picker",".el-switch",".el-checkbox-group",".el-radio-group",".el-cascader",".el-input-number"].join(", "),Y={name:"element",match:n=>n.matches(Ce),getValue:n=>{var t;const e=n.element;if(e)return e.matches(".el-switch")?e.classList.contains("is-checked")||e.getAttribute("aria-checked")==="true":e.matches(".el-radio-group")?Me(e,"radio"):e.matches(".el-checkbox-group")?Oe(e):((t=Z(e))==null?void 0:t.value)||e.textContent||void 0},setValue:(n,e)=>{const t=n.element;if(!t)return;if(t.matches(".el-switch")){Te(t,e);return}if(t.matches(".el-radio-group")){Fe(t,"radio",e);return}if(t.matches(".el-checkbox-group")){Le(t,e);return}const s=Z(t);if(s){Ne(s,e);return}t.dispatchEvent(new Event("change",{bubbles:!0}))}};function Te(n,e){(n.classList.contains("is-checked")||n.getAttribute("aria-checked")==="true")!==$e(e)&&R(n)}function Le(n,e){var i;const t=new Set(_e(e).map(I)),s=F(n,"checkbox");for(const r of s){const a=((i=r.input)==null?void 0:i.checked)||r.root.classList.contains("is-checked")||r.root.getAttribute("aria-checked")==="true",o=t.has(I(r.value))||t.has(I(r.label));a!==o&&R(r.root)}}function Fe(n,e,t){const s=I(String(t??"")),i=F(n,e).find(r=>I(r.value)===s||I(r.label)===s);i&&R(i.root)}function Me(n,e){var t;return(t=F(n,e).find(s=>{var i;return((i=s.input)==null?void 0:i.checked)||s.root.classList.contains("is-checked")}))==null?void 0:t.value}function Oe(n){return F(n,"checkbox").filter(e=>{var t;return((t=e.input)==null?void 0:t.checked)||e.root.classList.contains("is-checked")}).map(e=>e.value)}function F(n,e){return Array.from(n.querySelectorAll(`.el-${e}, [role="${e}"], input[type="${e}"]`)).map(t=>{const s=t instanceof HTMLInputElement?t:t.querySelector(`input[type="${e}"]`),i=t instanceof HTMLInputElement&&t.closest(`.el-${e}, [role="${e}"]`)||t,r=G(i.textContent||i.getAttribute("aria-label")||(s==null?void 0:s.value)||"");return{root:i,input:s,label:r,value:i.getAttribute("value")||(s==null?void 0:s.value)||r}})}function Z(n){return n.querySelector('input:not([type="hidden"]), textarea')}function Ne(n,e){n.value=String(e??""),n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0})),n.dispatchEvent(new Event("blur",{bubbles:!0}))}function R(n){n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window}))}function $e(n){return typeof n=="boolean"?n:["true","1","是","开启","启用","yes","y"].includes(String(n??"").trim().toLowerCase())}function _e(n){return Array.isArray(n)?n.map(String):String(n??"").split(/[,,;;、]/).map(e=>e.trim()).filter(Boolean)}function I(n){return G(n).toLowerCase()}function G(n){return n.replace(/\s+/g," ").trim()}const Re=[/^(el|rc|ant|radix|headlessui|mui|chakra)-/i,/[0-9a-f]{8,}/i,/\d{6,}/];function v(n){const e=String(n||"").trim();return!e||Re.some(t=>t.test(e))?"":e}function D(n){const e=(n.options||[]).slice(0,20).map(t=>`${t.label}:${String(t.value)}`).join("|");return C([n.fieldId,n.tagName,n.type,v(n.name),v(n.id),n.label,n.placeholder,n.section,e].join("::"))}function C(n){return String(n??"").replace(/\s+/g," ").trim().toLowerCase()}const P=new WeakMap;class z{constructor(e,t,s=[]){this.fields=e,this.schemas=t,this.adapters=s}async apply(e){const t=[],s=[];for(const i of e.values){const r=this.fields.find(l=>l.fieldId===i.fieldId);if(!r){s.push(M(i.fieldId,"",i.value,"字段不在当前扫描结果中","FIELD_NOT_FOUND"));continue}if(r.scanToken!==e.scanToken){s.push(M(r.fieldId,r.label,i.value,"页面扫描已过期,请重新扫描","SCAN_TOKEN_EXPIRED"));continue}const a=this.schemas.find(l=>l.fieldId===i.fieldId),o=a!=null&&a.transform?a.transform(i.value):i.value,d=await this.getValue(r,a);try{const l=a!=null&&a.validate?await a.validate(o):!0;if(l!==!0){s.push(M(r.fieldId,r.label,o,typeof l=="string"?l:"字段校验未通过","VALIDATE_FAILED"));continue}await this.setValue(r,o,a),t.push({fieldId:r.fieldId,label:r.label,value:o,previousValue:d})}catch(l){s.push(M(r.fieldId,r.label,o,l instanceof Error?l.message:"字段回填失败","SET_VALUE_FAILED"))}}return{applied:t,skipped:s,warnings:s.length?["部分字段未回填,请查看跳过原因。"]:void 0}}async getValue(e,t){if(t!=null&&t.getValue)return t.getValue();const s=this.matchAdapter(e);if(s!=null&&s.getValue)return s.getValue(e);const i=H(e);if(i)return i instanceof HTMLInputElement&&i.type==="checkbox"?i.checked:i instanceof HTMLInputElement&&i.type==="radio"?i.checked?i.value:void 0:i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement?i.value:i.textContent}async setValue(e,t,s){if(s!=null&&s.setValue){await s.setValue(t);return}const i=H(e);if(!i)throw new Error("页面中未找到对应字段");if(e.fingerprint&&e.fingerprint!==D({...e,tagName:i.tagName.toLowerCase()}))throw new Error("字段结构已变化,请重新扫描");if(e.disabled||e.readonly||i.hasAttribute("disabled")||i.hasAttribute("readonly"))throw new Error("字段不可编辑");const r=this.matchAdapter(e);if(r){await r.setValue(e,t);return}De(i,t),Pe(i)}matchAdapter(e){const t=H(e);return t?this.adapters.find(s=>s.match(t,e)):void 0}}function H(n){var e;return(e=n.element)!=null&&e.isConnected?n.element:document.querySelector(`[data-smart-fill-id="${K(n.fieldId)}"]`)}function De(n,e){if(n instanceof HTMLInputElement&&n.type==="checkbox")n.checked=!!e;else if(n instanceof HTMLInputElement&&n.type==="radio"){const t=document.querySelector(`input[type="radio"][name="${K(n.name)}"][value="${K(String(e))}"]`);(t||n).checked=!0}else n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement?n.value=String(e??""):n.isContentEditable&&(n.textContent=String(e??""));n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))}function Pe(n){var s;n.setAttribute("data-smart-fill-highlighted","true"),(s=P.get(n))==null||s.abort();const e=new AbortController,t=i=>{i&&"isTrusted"in i&&!i.isTrusted||(n.removeAttribute("data-smart-fill-highlighted"),e.abort(),P.delete(n))};P.set(n,e),n.addEventListener("focus",t,{signal:e.signal}),n.addEventListener("pointerdown",t,{signal:e.signal}),n.addEventListener("keydown",t,{signal:e.signal}),n.addEventListener("input",t,{signal:e.signal}),n.addEventListener("change",t,{signal:e.signal})}function M(n,e,t,s,i){return{fieldId:n,label:e,attemptedValue:t,reason:s,reasonCode:i}}function K(n){return typeof CSS<"u"&&CSS.escape?CSS.escape(n):n.replace(/["\\]/g,"\\$&")}const ze=[{key:"mobile",pattern:new RegExp("(?<!\\d)1[3-9]\\d{9}(?!\\d)","g"),confidence:.98,reason:"手机号正则命中"},{key:"idCard",pattern:new RegExp("(?<!\\d)\\d{17}[\\dXx](?!\\d)","g"),confidence:.96,reason:"身份证号正则命中"},{key:"email",pattern:/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,confidence:.95,reason:"邮箱正则命中"},{key:"bankCard",pattern:new RegExp("(?<!\\d)\\d{16,19}(?!\\d)","g"),confidence:.9,reason:"银行卡号正则命中"},{key:"amount",pattern:/(?:金额|价格|费用|合计|总计)[::\s]*([0-9]+(?:\.[0-9]{1,2})?)/g,confidence:.88,reason:"金额关键词命中"},{key:"date",pattern:/\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2}日?/g,confidence:.86,reason:"日期格式命中"}],X={legalPerson:["法人","法定代表人","法定代表","企业法人","legal person","legal representative"],emergencyContact:["紧急联系人","紧急联络人","emergency contact"],contact:["联系人","联络人","联系人员","contact"],spouse:["配偶","爱人","夫妻","spouse"]},g={mobile:["手机","手机号","电话","联系电话","mobile","phone"],legalPersonMobile:["法人手机号","法人电话","法定代表人手机号","法人手机","legal person mobile"],emergencyContactMobile:["紧急联系人手机号","紧急联系人电话","紧急联系电话","emergency contact mobile"],contactMobile:["联系人手机号","联系人电话","联系手机","contact mobile"],spouseMobile:["配偶手机号","配偶电话","爱人手机号","spouse mobile"],idCard:["身份证","证件号","身份证号","idcard","id card"],legalPersonIdCard:["法人身份证","法人身份证号","法定代表人身份证号"],spouseIdCard:["配偶身份证","配偶身份证号","爱人身份证号"],email:["邮箱","邮件","email","mail"],contactEmail:["联系人邮箱","联系邮箱","contact email"],name:["姓名","名字","称呼","name"],customerName:["客户姓名","申请人姓名","用户姓名","借款人姓名","客户名称"],legalPersonName:["法人姓名","法定代表人姓名","企业法人姓名"],emergencyContactName:["紧急联系人姓名","紧急联系人名称"],contactName:["联系人姓名","联系人名称"],spouseName:["配偶姓名","爱人姓名"],companyName:["公司名称","企业名称","单位名称","商户名称","公司","企业"],address:["地址","住址","通讯地址","联系地址","现住址","办公地址"],detailAddress:["详细地址","街道地址","门牌地址","详细住址"],amount:["金额","费用","价格","合计","总计","amount","price"],applyAmount:["申请金额","贷款金额","借款金额","授信金额","申请额度"],date:["日期","时间","有效期","date"],applyDate:["申请日期","申请时间","受理日期","进件日期"],bankCard:["银行卡","卡号","bank","bank card"]},W={mobile:"mobile",legalPersonMobile:"mobile",emergencyContactMobile:"mobile",contactMobile:"mobile",spouseMobile:"mobile",idCard:"idCard",legalPersonIdCard:"idCard",spouseIdCard:"idCard",email:"email",contactEmail:"email",name:"name",customerName:"name",legalPersonName:"name",emergencyContactName:"name",contactName:"name",spouseName:"name",companyName:"companyName",address:"address",detailAddress:"address",amount:"amount",applyAmount:"amount",date:"date",applyDate:"date",bankCard:"bankCard"};class J{recognize(e,t,s){const i=Xe([...He(e),...Ke(e)]),r=new Set,a=[];for(const o of i.sort((d,l)=>l.confidence-d.confidence)){const d=qe(o,t,r);d&&(a.push({fieldId:d.fieldId,scanToken:s,label:d.label,value:Be(o.value,d),displayValue:o.value,confidence:o.confidence,source:"local_rule",reason:o.reason}),r.add(d.fieldId))}return a}}function He(n){const e=[];for(const t of ze)for(const s of n.matchAll(t.pattern)){const i=Q(s[1]||s[0]);e.push({key:t.key,value:i,confidence:t.confidence,reason:t.reason,baseKey:W[t.key]})}return e}function Ke(n){const e=[],t=n.split(/\r?\n|[;,;]/).map(s=>s.trim()).filter(Boolean);for(const s of t){const i=s.match(/^[“"'`]?([^::=]{2,30})[”"'`]?[::=]\s*(.+)$/);if(!i)continue;const r=Ge(i[1]),a=Q(i[2]);if(!(!r||!a))for(const o of Ve(r,a))e.push(o)}return e}function Ve(n,e){const t=C(n),s=Ye(e),i=[],r=je(t);return h(t,g.applyDate)&&i.push("applyDate"),h(t,g.applyAmount)&&i.push("applyAmount"),h(t,g.companyName)&&i.push("companyName"),h(t,g.detailAddress)&&i.push("detailAddress"),h(t,g.address)&&i.push("address"),(h(t,g.mobile)||s==="mobile")&&r&&V(i,r,"mobile"),(h(t,g.idCard)||s==="idCard")&&r&&V(i,r,"idCard"),(h(t,g.email)||s==="email")&&r&&V(i,r,"email"),(h(t,g.mobile)||s==="mobile")&&i.push("mobile"),(h(t,g.idCard)||s==="idCard")&&i.push("idCard"),(h(t,g.email)||s==="email")&&i.push("email"),(h(t,g.bankCard)||s==="bankCard")&&i.push("bankCard"),(h(t,g.amount)||s==="amount")&&i.push("amount"),(h(t,g.date)||s==="date")&&i.push("date"),We(i).map((a,o)=>({key:a,value:e,confidence:Math.max(.84,.96-o*.04),reason:r?`键值对文本命中(${n},角色增强)`:`键值对文本命中(${n})`,baseKey:W[a]}))}function qe(n,e,t){let s=null;for(const i of e){if(t.has(i.fieldId))continue;const r=Ue(n,i);r>((s==null?void 0:s.score)??0)&&(s={field:i,score:r})}return s&&s.score>=.45?s.field:null}function Ue(n,e){const t=C([e.fieldId,e.label,e.placeholder,e.name,e.id,e.section].join(" ")),s=g[n.key]||[n.key],i=g[n.baseKey]||[n.baseKey];let r=0;return h(t,s)?r+=.95:n.key!==n.baseKey&&h(t,i)?r+=.68:h(t,i)&&(r+=.82),t.includes(C(n.key))&&(r+=.22),e.required&&(r+=.05),n.baseKey==="amount"&&(e.type==="amount"||e.type==="number")&&(r+=.18),n.baseKey==="date"&&e.type==="date"&&(r+=.18),n.baseKey==="address"&&(e.type==="textarea"||e.type==="text")&&(r+=.12),["name","companyName","email","mobile","idCard","bankCard"].includes(n.baseKey)&&e.type==="text"&&(r+=.08),Math.min(r,1)}function Be(n,e){var t;return e.type==="date"?n.replace(/[年月/.]/g,"-").replace(/日/g,"").replace(/--/g,"-"):e.type==="number"||e.type==="amount"?((t=n.match(/[0-9]+(?:\.[0-9]+)?/))==null?void 0:t[0])??n:e.name&&/mobile|phone|idcard|bankcard/i.test(e.name)||e.id&&/mobile|phone|idcard|bankcard/i.test(e.id)||/mobile|phone|idcard|bankcard/i.test(e.fieldId)?n.replace(/\s+/g,""):n}function je(n){const e=Object.keys(X).filter(t=>h(n,X[t]));return e.length?e.includes("emergencyContact")?"emergencyContact":e.includes("legalPerson")?"legalPerson":e.includes("spouse")?"spouse":"contact":null}function Ye(n){const e=n.replace(/\s+/g,"");return/^1[3-9]\d{9}$/.test(e)?"mobile":/^\d{17}[\dXx]$/.test(e)?"idCard":/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(n)?"email":/^\d{16,19}$/.test(e)?"bankCard":/^\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2}日?$/.test(n)?"date":/^[0-9]+(?:\.[0-9]{1,2})?$/.test(e)?"amount":/[省市区县路街道号栋室乡镇]/.test(n)?"address":/^[\u4e00-\u9fa5a-zA-Z·]{2,20}$/.test(n)?"name":"unknown"}function V(n,e,t){var i;const s=(i=Ze[e])==null?void 0:i[t];s&&n.push(s)}const Ze={legalPerson:{mobile:"legalPersonMobile",idCard:"legalPersonIdCard",name:"legalPersonName"},emergencyContact:{mobile:"emergencyContactMobile",name:"emergencyContactName"},contact:{mobile:"contactMobile",email:"contactEmail",name:"contactName"},spouse:{mobile:"spouseMobile",idCard:"spouseIdCard",name:"spouseName"}};function Ge(n){return n.replace(/[“”"'`]/g,"").replace(/\s+/g," ").trim()}function Q(n){return n.replace(/[,。;;]+$/g,"").replace(/^[“”"'`\s]+|[“”"'`\s]+$/g,"").trim()}function h(n,e){const t=C(n);return e.some(s=>t.includes(C(s)))}function Xe(n){const e=new Map;for(const t of n){const s=`${t.key}::${t.value}`,i=e.get(s);(!i||i.confidence<t.confidence)&&e.set(s,t)}return[...e.values()]}function We(n){return[...new Set(n)]}const Je=["input","textarea","select","[contenteditable]:not([contenteditable='false'])"].join(", "),ee=[".el-select",".el-date-editor",".el-time-picker",".el-switch",".el-checkbox-group",".el-radio-group",".el-cascader",".el-input-number"].join(", "),te=["dialog[open]","[role='dialog']","[aria-modal='true']",".modal",".modal-dialog",".ant-modal",".ant-drawer",".el-dialog",".el-drawer",".n-dialog",".n-modal",".popup",".drawer"].join(", "),Qe=new Set(["hidden","submit","button","image","reset","file","password"]);class ne{constructor(e=document){this.root=e}scan(e={}){var d;const t=L("scan");if((d=e.registered)!=null&&d.length)return{scanToken:t,fields:e.registered.map(l=>this.fromSchema(l,t))};const s=this.resolveRoot(e.scanContainer),i=this.collectVisibleFields(s),r=this.detectTopLayerContainer(i),a=i.filter(l=>r.contains(l)),o=(a.length?a:i).slice(0,e.maxFields??200);return{scanToken:t,fields:o.map((l,u)=>this.fromElement(l,u,t))}}fromSchema(e,t){const s=ot(e.element,this.root),i={fieldId:e.rowKey==null?e.fieldId:`${e.fieldId}:${e.rowKey}`,label:e.label,type:e.type,localRuleMode:e.localRuleMode??"inherit",required:e.required,section:e.section,options:e.options,source:"registered",scanToken:t,element:s||void 0,fingerprint:""};return i.fingerprint=D({...i,tagName:s==null?void 0:s.tagName.toLowerCase()}),i}fromElement(e,t,s){const i=et(e,t),r=st(e),a={fieldId:i,fingerprint:"",scanToken:s,type:tt(e),localRuleMode:"inherit",label:q(e),placeholder:se(e),name:v(oe(e))||void 0,id:v(e.id)||void 0,section:nt(e),options:r,required:rt(e),readonly:it(e),disabled:U(e),source:"form_scan",element:e};return a.fingerprint=D({...a,tagName:e.tagName.toLowerCase()}),a}resolveRoot(e){if(e){const t=le(this.root,e);if(t)return t}return this.root}collectVisibleFields(e){const t=Array.from(e.querySelectorAll(ee)).filter(i=>!(i instanceof HTMLElement)||!ie(i)||U(i)?!1:re(i));return[...Array.from(e.querySelectorAll(Je)).filter(i=>!(i instanceof HTMLElement)||!ie(i)||at(i)||i instanceof HTMLInputElement&&Qe.has((i.type||"").toLowerCase())?!1:!U(i)&&!i.hasAttribute("readonly")),...t]}detectTopLayerContainer(e){const t=document.activeElement instanceof HTMLElement?document.activeElement:null,s=t==null?void 0:t.closest(te);if(s instanceof HTMLElement&&e.some(r=>s.contains(r)))return s;const i=e.map(r=>r.closest(te)).filter(r=>r instanceof HTMLElement);return i.length?i.sort((r,a)=>e.filter(o=>a.contains(o)).length-e.filter(o=>r.contains(o)).length)[0]:document.body}}function et(n,e){const t=n.getAttribute("data-smart-fill-id");if(t)return t;const i=v(n.getAttribute("data-smart-fill-key"))||v(oe(n))||v(n.id)||v(q(n))||`smart-fill-${Date.now()}-${e}`;return n.setAttribute("data-smart-fill-id",i),i}function tt(n){const e=ae(n);if(e)return e;if(n instanceof HTMLTextAreaElement)return"textarea";if(n instanceof HTMLSelectElement)return"select";if(n instanceof HTMLInputElement){const t=(n.type||"text").toLowerCase();if(t==="radio")return"radio";if(t==="checkbox")return"checkbox";if(t==="date"||t==="month")return"date";if(t==="number")return"number"}return"text"}function q(n){const e=n.getAttribute("aria-label");if(e)return e.trim();if(n.id){const r=document.querySelector(`label[for="${ce(n.id)}"]`);if(r!=null&&r.textContent)return x(r.textContent)}const t=n.closest("label");if(t!=null&&t.textContent)return x(t.textContent);const s=n.closest(".form-item, .ant-form-item, .el-form-item, .field, .form-row"),i=s==null?void 0:s.querySelector("label, .ant-form-item-label, .el-form-item__label, .label");return i!=null&&i.textContent?x(i.textContent):se(n)||n.getAttribute("name")||n.id||"未命名字段"}function se(n){var e;return n.getAttribute("placeholder")||n.getAttribute("aria-placeholder")||((e=n.querySelector("[placeholder]"))==null?void 0:e.getAttribute("placeholder"))||void 0}function nt(n){const e=n.closest("fieldset, section, .panel, .card, .form-section"),t=e==null?void 0:e.querySelector("legend, h1, h2, h3, .title, .section-title");return t!=null&&t.textContent?x(t.textContent):void 0}function st(n){if(n.matches(".el-radio-group"))return Array.from(n.querySelectorAll('.el-radio, [role="radio"], input[type="radio"]')).map(e=>{var t;return{label:x(e.textContent||e.getAttribute("aria-label")||e.getAttribute("value")||""),value:e.getAttribute("value")||((t=e.querySelector('input[type="radio"]'))==null?void 0:t.value)||x(e.textContent||"")}}).filter(e=>e.label||e.value);if(n.matches(".el-checkbox-group"))return Array.from(n.querySelectorAll('.el-checkbox, [role="checkbox"], input[type="checkbox"]')).map(e=>{var t;return{label:x(e.textContent||e.getAttribute("aria-label")||e.getAttribute("value")||""),value:e.getAttribute("value")||((t=e.querySelector('input[type="checkbox"]'))==null?void 0:t.value)||x(e.textContent||"")}}).filter(e=>e.label||e.value);if(n instanceof HTMLSelectElement)return Array.from(n.options).map(e=>({label:x(e.textContent||e.label),value:e.value}));if(n instanceof HTMLInputElement&&(n.type==="radio"||n.type==="checkbox")&&n.name)return Array.from(document.querySelectorAll(`input[name="${ce(n.name)}"]`)).map(e=>({label:q(e),value:e.value||!0}))}function ie(n){const e=window.getComputedStyle(n);return e.display==="none"||e.visibility==="hidden"||Number(e.opacity)===0?!1:!!(n.offsetWidth||n.offsetHeight||n.getClientRects().length)}function U(n){return n.hasAttribute("disabled")||n.getAttribute("aria-disabled")==="true"||n.classList.contains("is-disabled")||!!n.querySelector('[disabled], [aria-disabled="true"], .is-disabled')}function it(n){return n.hasAttribute("readonly")||!!n.querySelector("[readonly]")}function rt(n){return n.hasAttribute("required")||n.getAttribute("aria-required")==="true"||!!n.querySelector('[required], [aria-required="true"]')}function at(n){const e=n.closest(ee);return e instanceof HTMLElement?re(e):!1}function re(n){return!!ae(n)}function ae(n){return n.matches(".el-select, .el-cascader")?"select":n.matches(".el-date-editor, .el-time-picker")?"date":n.matches(".el-switch")||n.matches(".el-checkbox-group")?"checkbox":n.matches(".el-radio-group")?"radio":n.matches(".el-input-number")?"number":null}function oe(n){var e;return n.getAttribute("name")||((e=n.querySelector("[name]"))==null?void 0:e.getAttribute("name"))||n.getAttribute("data-smart-fill-key")}function ot(n,e){return n instanceof HTMLElement?n:typeof n=="string"?le(e,n):null}function le(n,e){try{const t=n.querySelector(e);return t instanceof HTMLElement?t:null}catch{return null}}function x(n){return n.replace(/[*::]/g,"").replace(/\s+/g," ").trim()}function ce(n){return typeof CSS<"u"&&CSS.escape?CSS.escape(n):n.replace(/["\\]/g,"\\$&")}const B=5,lt=10*1024*1024,ct=50*1024*1024;class dt{constructor(e){c(this,"host",null);c(this,"root",null);c(this,"autoApplyState",null);c(this,"selectedFiles",[]);c(this,"inputText","");c(this,"localPriorityEnabled");c(this,"isOpen",!1);c(this,"dragState",null);c(this,"suppressOpenClick",!1);c(this,"isUploadHovering",!1);c(this,"handleDragMove",e=>{if(!this.dragState||!this.host||e.pointerId!==this.dragState.pointerId)return;const t=e.clientX-this.dragState.startX,s=e.clientY-this.dragState.startY;(Math.abs(t)>3||Math.abs(s)>3)&&(this.dragState.moved=!0);const i=this.host.getBoundingClientRect(),r=Math.max(8,window.innerWidth-i.width-8),a=Math.max(8,window.innerHeight-i.height-8),o=O(this.dragState.startLeft+t,8,r),d=O(this.dragState.startTop+s,8,a);this.host.style.left=`${o}px`,this.host.style.top=`${d}px`});c(this,"handleDragEnd",e=>{!this.dragState||e.pointerId!==this.dragState.pointerId||(this.suppressOpenClick=this.dragState.moved,this.dragState=null,document.removeEventListener("pointermove",this.handleDragMove),document.removeEventListener("pointerup",this.handleDragEnd),document.removeEventListener("pointercancel",this.handleDragEnd),this.suppressOpenClick&&window.setTimeout(()=>{this.suppressOpenClick=!1},0))});c(this,"handleDocumentPaste",e=>{const t=ft(e);if(!t.length||!this.isOpen||!this.host)return;const s=document.activeElement,i=this.root instanceof ShadowRoot?this.root.activeElement:null;!(s===this.host||this.host.contains(s)||i)&&!this.isUploadHovering||(e.preventDefault(),this.handleImages(t))});this.options=e,this.localPriorityEnabled=e.localPriorityEnabled??!1}mount(e){this.host=document.createElement("div"),this.host.className=`sf-sdk-host sf-sdk-host-${this.options.mode}`,e.appendChild(this.host),this.root=this.host.attachShadow?this.host.attachShadow({mode:"open"}):this.host,this.isOpen=this.options.initialOpen??this.options.mode==="inline",document.addEventListener("paste",this.handleDocumentPaste),this.render(this.isOpen)}setOpen(e){this.isOpen=e,this.render(this.isOpen),this.keepHostInViewport()}setLocalPriorityEnabled(e){this.localPriorityEnabled=e;const t=this.query('[data-role="local-priority-toggle"]');t&&(t.checked=e)}setBusy(e,t=""){const s=this.query('[data-role="recognize"]');s&&(s.disabled=e,s.textContent=e?t:this.t("recognize","智能识别"))}setStatus(e){const t=this.query('[data-role="status"]');t&&(t.textContent=e,t.removeAttribute("data-status"))}setError(e){const t=this.query('[data-role="status"]');t&&(t.textContent=e,t.setAttribute("data-status","error"))}setAutoApplyState(e){this.autoApplyState=e,this.render(!0),this.keepHostInViewport(),this.setStatus(this.t("recognized","识别完成,正在自动回填..."))}setApplyResult(e){const t=this.query('[data-role="status"]');t&&(t.textContent=`已回填 ${e.applied.length} 项,跳过 ${e.skipped.length} 项。`,t.setAttribute("data-status",e.skipped.length?"warning":"success"))}destroy(){var e;document.removeEventListener("pointermove",this.handleDragMove),document.removeEventListener("pointerup",this.handleDragEnd),document.removeEventListener("pointercancel",this.handleDragEnd),document.removeEventListener("paste",this.handleDocumentPaste),(e=this.host)==null||e.remove(),this.host=null,this.root=null,this.dragState=null,this.isUploadHovering=!1}render(e){this.root&&(this.root.innerHTML=`
|
|
2
|
-
|
|
1
|
+
(function(g,v){typeof exports=="object"&&typeof module<"u"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(g=typeof globalThis<"u"?globalThis:g||self,v(g.SmartFillSDK={}))})(this,function(g){"use strict";var Vo=Object.defineProperty;var Bo=(g,v,R)=>v in g?Vo(g,v,{enumerable:!0,configurable:!0,writable:!0,value:R}):g[v]=R;var d=(g,v,R)=>Bo(g,typeof v!="symbol"?v+"":v,R);const v={name:"native",match:e=>e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement,getValue:e=>{const t=e.element;if(t instanceof HTMLInputElement&&t.type==="checkbox")return t.checked;if(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)return t.value},setValue:(e,t)=>{const n=e.element;n instanceof HTMLInputElement&&n.type==="checkbox"?n.checked=!!t:(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement)&&(n.value=String(t??"")),n==null||n.dispatchEvent(new Event("input",{bubbles:!0})),n==null||n.dispatchEvent(new Event("change",{bubbles:!0}))}},R=[{framework:"element",selectors:".el-select,.el-select-v2",type:"select",kind:"input"},{framework:"element",selectors:".el-cascader",type:"cascader",kind:"input"},{framework:"element",selectors:".el-date-editor,.el-time-picker",type:"date",kind:"input"},{framework:"element",selectors:".el-input-number",type:"number",kind:"input"},{framework:"element",selectors:".el-switch",type:"checkbox",kind:"switch"},{framework:"element",selectors:".el-radio-group",type:"radio",kind:"radioGroup",optionSelector:'.el-radio,[role="radio"],input[type="radio"]'},{framework:"element",selectors:".el-checkbox-group",type:"checkbox",kind:"checkboxGroup",optionSelector:'.el-checkbox,[role="checkbox"],input[type="checkbox"]'},{framework:"antd",selectors:".ant-select",type:"select",kind:"input"},{framework:"antd",selectors:".ant-cascader",type:"cascader",kind:"input"},{framework:"antd",selectors:".ant-picker",type:"date",kind:"input"},{framework:"antd",selectors:".ant-input-number",type:"number",kind:"input"},{framework:"antd",selectors:".ant-switch",type:"checkbox",kind:"switch"},{framework:"antd",selectors:".ant-radio-group",type:"radio",kind:"radioGroup",optionSelector:'.ant-radio-button,.ant-radio-wrapper,.ant-radio,[role="radio"],input[type="radio"]'},{framework:"antd",selectors:".ant-checkbox-group",type:"checkbox",kind:"checkboxGroup",optionSelector:'.ant-checkbox-wrapper,.ant-checkbox,[role="checkbox"],input[type="checkbox"]'},{framework:"naive",selectors:".n-select",type:"select",kind:"input"},{framework:"naive",selectors:".n-cascader",type:"cascader",kind:"input"},{framework:"naive",selectors:".n-date-picker,.n-time-picker",type:"date",kind:"input"},{framework:"naive",selectors:".n-input-number",type:"number",kind:"input"},{framework:"naive",selectors:".n-switch",type:"checkbox",kind:"switch"},{framework:"naive",selectors:".n-radio-group",type:"radio",kind:"radioGroup",optionSelector:'.n-radio,[role="radio"],input[type="radio"]'},{framework:"naive",selectors:".n-checkbox-group",type:"checkbox",kind:"checkboxGroup",optionSelector:'.n-checkbox,[role="checkbox"],input[type="checkbox"]'},{framework:"arco",selectors:".arco-select",type:"select",kind:"input"},{framework:"arco",selectors:".arco-cascader",type:"cascader",kind:"input"},{framework:"arco",selectors:".arco-picker",type:"date",kind:"input"},{framework:"arco",selectors:".arco-input-number",type:"number",kind:"input"},{framework:"arco",selectors:".arco-switch",type:"checkbox",kind:"switch"},{framework:"arco",selectors:".arco-radio-group",type:"radio",kind:"radioGroup",optionSelector:'.arco-radio,[role="radio"],input[type="radio"]'},{framework:"arco",selectors:".arco-checkbox-group",type:"checkbox",kind:"checkboxGroup",optionSelector:'.arco-checkbox,[role="checkbox"],input[type="checkbox"]'},{framework:"vant",selectors:".van-dropdown-menu",type:"select",kind:"input"},{framework:"vant",selectors:".van-cascader",type:"cascader",kind:"input"},{framework:"vant",selectors:".van-stepper",type:"number",kind:"input"},{framework:"vant",selectors:".van-field--picker",type:"date",kind:"input"},{framework:"vant",selectors:".van-search",type:"text",kind:"input"},{framework:"vant",selectors:".van-field",type:"text",kind:"input"},{framework:"vant",selectors:".van-switch",type:"checkbox",kind:"switch"},{framework:"vant",selectors:".van-radio-group",type:"radio",kind:"radioGroup",optionSelector:'.van-radio,[role="radio"],input[type="radio"]'},{framework:"vant",selectors:".van-checkbox-group",type:"checkbox",kind:"checkboxGroup",optionSelector:'.van-checkbox,[role="checkbox"],input[type="checkbox"]'},{framework:"generic",selectors:'[role="combobox"]',type:"select",kind:"input"}],un=["is-disabled","ant-select-disabled","n-select--disabled","arco-select-disabled","van-field--disabled","van-switch--disabled","van-stepper--disabled","van-dropdown-menu--disabled"],nt=R.map(e=>e.selectors).join(", "),dn=[".form-item",".ant-form-item",".el-form-item",".n-form-item",".arco-form-item",".van-cell",".van-field",".field",".form-row"].join(", "),fn=["label",".ant-form-item-label",".el-form-item__label",".n-form-item-label",".arco-form-item-label",".van-field__label",".label"].join(", "),rt=["dialog[open]","[role='dialog']","[aria-modal='true']",".modal",".modal-dialog",".ant-modal",".ant-drawer",".el-dialog",".el-drawer",".n-modal",".n-dialog",".arco-modal",".arco-drawer",".van-popup",".van-dialog",".van-action-sheet",".popup",".drawer"].join(", "),pn=["is-checked","ant-switch-checked","n-switch--active","arco-switch-checked","van-switch--on","van-radio--checked","van-checkbox--checked"];function $(e){return R.find(t=>e.matches(t.selectors))||null}function ot(e){return!!$(e)}function Te(e){for(let t=e;t;t=t.parentElement)if(ot(t))return t;return null}function ie(e){var n;const t=$(e);if(!t)return null;if(e.matches(".van-field")){if(e.querySelector("textarea"))return"textarea";if(e.classList.contains("van-field--picker"))return"date";if(e.querySelector(".van-dropdown-menu"))return"select";const r=e.querySelector("input");if(r&&(r.readOnly||r.hasAttribute("readonly"))){const o=(r.getAttribute("placeholder")||"").trim();if(!o||/选择|select/i.test(o))return"select"}if(e.classList.contains("van-field--clickable")){const o=f(((n=e.querySelector(".van-field__control"))==null?void 0:n.textContent)||"");if(!e.querySelector("textarea")&&(o==="请选择"||o===""))return"select"}}return t.type}function it(e){const t=$(e);if(t!=null&&t.optionSelector)return Array.from(e.querySelectorAll(t.optionSelector)).map(n=>hn(n)).filter(n=>!!(n.label||n.value))}function hn(e){const t=e instanceof HTMLInputElement?e:e.querySelector('input[type="radio"],input[type="checkbox"]'),n=f(e.textContent||e.getAttribute("aria-label")||e.getAttribute("title")||""),r=e.getAttribute("value")||(t==null?void 0:t.value)||n;return{label:n,value:r}}function B(e){return pn.some(t=>e.classList.contains(t))||e.getAttribute("aria-checked")==="true"||!!e.querySelector("input:checked")}function H(e){return e.querySelector('input:not([type="hidden"]), textarea')}function st(e){var t,n,r;return e.getAttribute("name")||((t=H(e))==null?void 0:t.getAttribute("name"))||e.getAttribute("data-smart-fill-key")||((n=H(e))==null?void 0:n.getAttribute("data-smart-fill-key"))||((r=e.querySelector("[data-smart-fill-key]"))==null?void 0:r.getAttribute("data-smart-fill-key"))}function f(e){return e.replace(/[*::]/g,"").replace(/\s+/g," ").trim()}const Le="data-smart-fill-hide-dropdown-mode",at="smart-fill-hide-dropdown-style",ct=["[role='combobox']","[aria-haspopup='listbox']",".el-cascader",".ant-cascader",".arco-cascader",".ant-select",".el-select",".el-select-v2",".el-select__wrapper",".el-select-v2__wrapper",".n-select",".n-base-selection",".ivu-select",".arco-select",".semi-select",".t-select",".select-trigger",".select__wrapper",".van-dropdown-menu",".van-dropdown-menu__bar",".van-field--picker",".van-field--clickable"].join(", "),gn=[".ant-select-selection-item",".el-select__selected-item",".el-select-v2__selected-item",".el-select-v2-selected-item",".el-select__placeholder",".el-select-v2__placeholder",".el-select-selected-value",".n-base-selection-label",".ivu-select-selected-value",".arco-select-view-value",".semi-select-selection-text",".t-input__inner",".select-value",".selection-item",".van-field__control"].join(", "),Ie=["[role='option']",".ant-select-item-option",".el-select-dropdown__item",".el-select-v2__option",".n-base-select-option",".ivu-select-item",".arco-select-option",".semi-select-option",".t-select-option",".van-picker-column__item",".van-action-sheet__item"].join(", "),se=[Ie,".van-action-sheet__name",".van-cascader__option",".van-dropdown-item__option",".van-picker-column__item--selected",".el-cascader-node",".ant-cascader-menu-item",".n-cascader-node",".arco-cascader-option"].join(", "),Me=[".el-select-dropdown",".el-cascader__dropdown",".el-cascader-panel",".el-select__popper",".el-select-v2__popper",".el-popper.el-cascader__dropdown",".el-popper.el-select__popper",".el-popper.el-select-v2__popper",".el-popper",".ant-select-dropdown",".ant-cascader-menus",".n-base-select-menu",".n-cascader-menu",".arco-select-dropdown",".arco-cascader-panel",".semi-select-dropdown",".t-select__dropdown",".van-popup",".van-action-sheet",".van-dropdown-item__content",".van-dropdown-item",".van-picker","[role='listbox']"].join(", "),lt=[".el-select-dropdown",".el-select__popper",".el-select-v2__popper",".el-popper.el-select__popper",".el-popper.el-select-v2__popper",".ant-select-dropdown",".n-base-select-menu",".arco-select-dropdown",".semi-select-dropdown",".t-select__dropdown",".van-popup",".van-action-sheet",".van-dropdown-item__content",".van-dropdown-item",".van-picker","[role='listbox']"].join(", "),ut=[".el-cascader__dropdown",".el-cascader-panel",".el-popper.el-cascader__dropdown",".ant-cascader-menus",".n-cascader-menu",".arco-cascader-panel",".van-cascader",".van-cascader__options"].join(", "),yn=/(?:省|市|自治区|特别行政区|自治州|地区|盟|县|区)$/,bn=/地址|省|市|区|县|地区|籍贯|户籍|居住地|所在地|区域/,mn=new Set(["select","cascader","date"]);function _(e){return!St(e)||pt(e)?!1:!!e.closest(".el-cascader, .ant-cascader, .van-cascader, .n-cascader, .arco-cascader")}function F(e){var n;if(!e.matches(".van-field"))return!1;if(e.classList.contains("van-field--picker")||e.querySelector(".van-dropdown-menu"))return!0;const t=e.querySelector("input");if(t&&(t.readOnly||t.hasAttribute("readonly"))){const r=(t.getAttribute("placeholder")||"").trim();if(!r||/选择|select/i.test(r))return!0}if(e.classList.contains("van-field--clickable")){const r=f(((n=e.querySelector(".van-field__control"))==null?void 0:n.textContent)||"");if(!e.querySelector("textarea")&&(r==="请选择"||r===""))return!0}return!1}function U(e){return!St(e)||pt(e)||e instanceof HTMLSelectElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?!1:e.matches(ct)||e.getAttribute("role")==="combobox"||e.getAttribute("aria-haspopup")==="listbox"||e.classList.contains("el-select__wrapper")||e.classList.contains("el-select-v2__wrapper")||F(e)}function ae(e){const t=e.closest(".el-cascader, .ant-cascader, .van-cascader, .n-cascader, .arco-cascader");if(t instanceof HTMLElement)return t;const n=e.closest([".el-date-editor",".el-time-picker",".el-date-picker",".el-date-picker-panel",".el-select",".el-select-v2",".ant-picker",".ant-select",".n-date-picker",".n-time-picker",".n-select",".ivu-select",".arco-picker",".arco-select",".semi-select",".t-select",".van-field",".van-dropdown-menu",".van-dropdown-menu__bar","[role='combobox']","[aria-haspopup='listbox']",".select-trigger",".select__wrapper",".el-select__wrapper",".el-select-v2__wrapper"].join(", "));return n instanceof HTMLElement?n.matches(".van-field")&&!F(n)?null:n:U(e)?e:null}function Re(e){if(e instanceof HTMLSelectElement)return e;if(_(e))return e.closest(".el-cascader, .ant-cascader, .van-cascader, .n-cascader, .arco-cascader")||e;const t=ae(e);return t||(e.matches(".van-field")&&F(e)?e:null)}function Fe(e){if(_(e))return"cascader";if(U(e)||F(e))return"select";const t=ie(e);return t||(e instanceof HTMLSelectElement?"select":null)}function j(e,t){const n=t||Fe(e);return n!=null&&mn.has(n)}function vn(e){return j(e,Fe(e)||void 0)}function dt(e){const t=e.querySelector(gn);if(t instanceof HTMLInputElement)return f(t.value);const n=f((t==null?void 0:t.textContent)||"");if(n&&n!=="请选择")return n;const r=e.querySelector('input:not([type="hidden"])');return r!=null&&r.value?f(r.value):n}function ft(e){const t=An(e);if(!t.length)return;const n=Cn(t);return n.length?n:void 0}function ce(e){var t;return!((t=e.options)!=null&&t.length)||e.type==="cascader"||bn.test(e.label||"")?!1:Fn(e.options)}async function wn(e){if(e instanceof HTMLSelectElement)return Array.from(e.options).map(s=>({value:s.value,label:f(s.textContent||s.label)})).filter(s=>s.label||s.value);const t=ft(e);if(t!=null&&t.length)return t;const n=ae(e)||e;if(!U(n)&&!_(n)&&!F(n))return;const r=qn(),o=On(),i=new Set(o.getTrackedDropdowns());try{if(!(_(n)?await En(n,o,i):await Sn(n,o,i)))return;const a=await kn(o,i,n);if(!a.length)return;const c=xn(a);return c.length?c:void 0}finally{await Pn(n,o),await O(60),o.restore(),r()}}function pt(e){return e.hasAttribute("disabled")||e.getAttribute("aria-disabled")==="true"}async function Sn(e,t,n){const r=G(e);if(!r.length)return!1;for(const o of r)if(vt(o),mt(o),await O(160),ht(e,t,n)||(wt(o),await O(180),ht(e,t,n)))return!0;return!1}async function En(e,t,n){const r=[e,e.querySelector(".el-input__wrapper"),e.querySelector(".el-input"),e.querySelector(".van-field__control"),e.querySelector("input")].filter(o=>o instanceof HTMLElement);for(const o of r)if(vt(o),mt(o),await O(180),le(t,n,e).length||(wt(o),await O(180),le(t,n,e).length))return!0;return!1}function xn(e){var r;const t=new Set,n=[];for(const o of e){const i=o.matches(se)?[o]:Array.from(o.querySelectorAll(se));for(const s of i){if(s.classList.contains("is-disabled")||s.classList.contains("ant-select-item-option-disabled")||s.getAttribute("aria-disabled")==="true")continue;const a=f(((r=s.querySelector(".el-cascader-node__label, .ant-cascader-menu-item-content"))==null?void 0:r.textContent)||s.textContent||""),c=s.getAttribute("data-value")||s.getAttribute("value")||a;if(!a&&!c)continue;const l=`${a}::${String(c)}`;t.has(l)||(t.add(l),n.push({label:a,value:c}))}}return n}async function kn(e,t,n){for(let r=0;r<8;r+=1){const o=le(e,t,n);if(o.length)return o;await O(r===0?120:80)}return[]}function ht(e,t,n){return le(t,n,e).length>0?!0:G(e).some(r=>r.getAttribute("aria-expanded")==="true"||r.classList.contains("is-focus")||r.classList.contains("is-focused"))}function _n(e,t,n){const r=t.filter(c=>Oe(e,c)),o=r.filter(c=>Tn(e,c)),i=o.filter(c=>!n.has(c));if(i.length)return i.sort((c,l)=>z(l,e)-z(c,e));const s=gt(e);if(s.size){const c=o.filter(l=>l.id&&s.has(l.id));if(c.length)return c}if(o.length)return o.sort((c,l)=>z(l,e)-z(c,e)).slice(0,1);const a=r.filter(c=>Rn(c)&&yt(e)).sort((c,l)=>z(l,e)-z(c,e)).slice(0,1);return a.length?a:[]}function le(e,t,n){return _n(n,e.getTrackedDropdowns(),t)}function z(e,t){const n=e.getBoundingClientRect(),r=Number.parseInt(window.getComputedStyle(e).zIndex||"0",10);let o=(Number.isNaN(r)?0:r)*10+n.width*n.height;return t&&(o+=bt(t,e)),o}function An(e){const t=_(e)?ut:lt,n=new Set;e.matches(t)&&n.add(e);for(const r of e.querySelectorAll(t))Oe(e,r)&&n.add(r);for(const r of e.querySelectorAll("[role='listbox']"))e.contains(r)&&Oe(e,r)&&n.add(r);return[...n]}function Cn(e){const t=new Set,n=[];for(const r of e){const o=r.matches(Ie)?[r]:Array.from(r.querySelectorAll(Ie));for(const i of o){if(i.classList.contains("is-disabled")||i.classList.contains("ant-select-item-option-disabled")||i.getAttribute("aria-disabled")==="true")continue;const s=f(i.textContent||""),a=i.getAttribute("data-value")||i.getAttribute("value")||s;if(!s&&!a)continue;const c=`${s}::${String(a)}`;t.has(c)||(t.add(c),n.push({label:s,value:a}))}}return n}function gt(e){return new Set(G(e).flatMap(t=>[t.getAttribute("aria-controls"),t.getAttribute("aria-owns")]).filter(t=>!!t))}function Tn(e,t){const n=gt(e);return n.size&&t.id&&n.has(t.id)||e.contains(t)?!0:Mn(t)?yt(e):n.size>0||G(e).some(o=>o.getAttribute("aria-controls")||o.getAttribute("aria-owns"))?!1:bt(e,t)>0}function Oe(e,t){const n=_(e),r=Ln(t);return n?r:r?!1:In(t)}function Ln(e){return e.matches(ut)||!!e.querySelector(".el-cascader-node, .ant-cascader-menu-item, .van-cascader__option, .n-cascader-node, .arco-cascader-option")}function In(e){return e.matches(lt)||!!e.querySelector('.el-select-dropdown__item, .ant-select-item-option, .van-picker-column__item, .van-action-sheet__item, .van-dropdown-item__option, [role="option"]')}function Mn(e){return e.matches(".van-popup, .van-action-sheet, .van-picker, .van-dropdown-item__content, .van-dropdown-item")}function yt(e){return G(e).some(t=>t.getAttribute("aria-expanded")==="true"||t.classList.contains("is-focus")||t.classList.contains("is-focused")||e.contains(document.activeElement))}function Rn(e){return e.matches(se)||!!e.querySelector(se)}function bt(e,t){const n=e.getBoundingClientRect(),r=t.getBoundingClientRect();if(!n.width||!n.height||!r.width||!r.height)return 0;const o=Math.min(n.right,r.right)-Math.max(n.left,r.left);if(o<=0)return 0;const i=r.top>=n.bottom?r.top-n.bottom:n.top-r.bottom;return i>320?0:Math.max(0,400-i)+o}function Fn(e){const t=e.slice(0,8).map(r=>f(String(r.label||r.value||""))).filter(Boolean);return t.length<4?!1:t.filter(r=>yn.test(r)).length/t.length>=.75}function G(e){return[e,e.querySelector(".van-field__control"),e.querySelector(".van-field__body"),e.querySelector(".van-dropdown-menu__bar"),e.querySelector(".el-select__wrapper"),e.querySelector(".el-select-v2__wrapper"),e.querySelector(".el-select__selection"),e.querySelector(".el-input__wrapper"),e.querySelector(".el-input"),e.querySelector("input"),e.querySelector("[role='combobox']"),e.querySelector("[aria-haspopup='listbox']"),e.querySelector(".ant-select-selector"),e.querySelector(".n-base-selection"),e.querySelector(".n-base-selection-label"),e.querySelector(".arco-select-view"),e.querySelector(".arco-cascader"),e.querySelector(".semi-select"),e.querySelector(".t-input"),e.querySelector(".select-trigger"),e.querySelector(".select__wrapper")].filter(n=>n instanceof HTMLElement).filter((n,r,o)=>o.indexOf(n)===r)}function On(){const e=new Map;Dn(),document.documentElement.setAttribute(Le,"true");const t=()=>{for(const r of document.querySelectorAll(Me))e.has(r)||e.set(r,{display:r.style.display,opacity:r.style.opacity,visibility:r.style.visibility,pointerEvents:r.style.pointerEvents}),r.style.opacity="0",r.style.visibility="hidden",r.style.pointerEvents="none"};t();const n=new MutationObserver(()=>t());return n.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","style","aria-hidden"]}),{getTrackedDropdowns:()=>Array.from(document.querySelectorAll(Me)),restore:()=>{n.disconnect(),document.documentElement.removeAttribute(Le);for(const[r,o]of e)r.style.display=o.display,r.style.opacity=o.opacity,r.style.visibility=o.visibility,r.style.pointerEvents=o.pointerEvents}}}function Dn(){if(document.getElementById(at))return;const e=document.createElement("style");e.id=at,e.textContent=`
|
|
2
|
+
${Me.split(",").map(t=>`html[${Le}="true"] ${t.trim()}`).join(`,
|
|
3
|
+
`)} {
|
|
4
|
+
opacity: 0 !important;
|
|
5
|
+
visibility: hidden !important;
|
|
6
|
+
pointer-events: none !important;
|
|
7
|
+
transition: none !important;
|
|
8
|
+
animation: none !important;
|
|
9
|
+
}
|
|
10
|
+
`,document.head.appendChild(e)}async function Pn(e,t){e.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",code:"Escape",bubbles:!0})),document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",code:"Escape",bubbles:!0})),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),document.body.dispatchEvent(new MouseEvent("mousedown",{bubbles:!0,cancelable:!0,view:window})),document.body.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,view:window})),document.body.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),await O(120);for(const n of t.getTrackedDropdowns())n.isConnected&&(n.style.display="none",n.setAttribute("aria-hidden","true"))}function mt(e){window.PointerEvent&&(e.dispatchEvent(new PointerEvent("pointerdown",{bubbles:!0,composed:!0,button:0})),e.dispatchEvent(new PointerEvent("pointerup",{bubbles:!0,composed:!0,button:0}))),e.dispatchEvent(new MouseEvent("mousedown",{bubbles:!0,composed:!0,button:0})),e.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,composed:!0,button:0})),e.click()}function vt(e){e.focus({preventScroll:!0});const t=e instanceof HTMLInputElement?e:e.querySelector("input");t instanceof HTMLElement&&t.focus({preventScroll:!0})}function wt(e){for(const t of[{key:"ArrowDown",code:"ArrowDown"},{key:"Enter",code:"Enter"},{key:" ",code:"Space"}])e.dispatchEvent(new KeyboardEvent("keydown",{...t,bubbles:!0,composed:!0})),e.dispatchEvent(new KeyboardEvent("keyup",{...t,bubbles:!0,composed:!0}))}function O(e){return new Promise(t=>window.setTimeout(t,e))}function qn(){const e=new Map;e.set(window,{left:window.scrollX,top:window.scrollY});for(const t of document.querySelectorAll("*"))(t.scrollTop||t.scrollLeft)&&e.set(t,{left:t.scrollLeft,top:t.scrollTop});return()=>{for(const[t,n]of e)t===window?window.scrollTo(n.left,n.top):t instanceof HTMLElement&&(t.scrollLeft=n.left,t.scrollTop=n.top)}}function St(e){const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||Number(t.opacity)===0)return!1;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}const Nn=/(维吾尔自治区|壮族自治区|回族自治区|特别行政区|自治区直辖县级行政区划|自治区|自治州|地区|盟|林区|街道|苏木|社区|省|市|区|县|旗|镇|乡)$/g,$n=new Set(["市辖区","县","自治区直辖县级行政区划"]);let ue=null;function w(e){return String(e??"").replace(/\s+/g,"").replace(/[,,。.、/\\\-]/g,"").trim().toLowerCase()}function A(e){return w(e).replace(Nn,"")}function De(e){if(e==null)return"";if(typeof e=="string"||typeof e=="number")return String(e).trim();if(Array.isArray(e))return e.map(t=>De(t)).filter(Boolean).join("");if(typeof e=="object"){const t=[],n=new Set,r=o=>{const i=f(String(o??""));!i||n.has(i)||(n.add(i),t.push(i))};for(const o of["province","provinceName","prov","city","cityName","district","districtName","area","areaName","county","countyName","region","regionName","address","detail","detailAddress","fullAddress","label","text","value","name","answer"])r(e[o]);return t.join("")}return f(String(e))}function de(e){const t=[],n=[],r=s=>{const a=f(String(s??""));a&&t.push(a)},o=s=>{const a=w(s);a&&(n.push(a),r(s))};if(Array.isArray(e))for(const s of e)o(s);else if(typeof e=="object"&&e){for(const s of["province","provinceName","prov","city","cityName","district","districtName","area","areaName","county","countyName","region","regionName"])o(e[s]);for(const s of["address","detail","detailAddress","fullAddress","label","value","text","name","answer"])r(e[s])}else r(e);const i=w(t.join(""));return{fullText:i,looseFullText:A(i),structuredParts:n}}function Pe(e,t){const n=w(e),r=w(t);if(!n||!r)return!1;if(n===r||n.includes(r)||r.includes(n))return!0;const o=A(n),i=A(r);return!o||!i?!1:o===i||o.includes(i)||i.includes(o)}function qe(e,t=de(e)){const n=jn();if(!n.length)return[];let r=null,o=0;for(const i of n){const s=Vn(i,t);s>o&&(o=s,r=i)}return o>=120?(r==null?void 0:r.labels)||[]:[]}function Hn(e,t,n,r){let o=null,i=0;const s=zn(t,n,r);for(const a of e){const c=a.querySelector(".el-cascader-node__label, .ant-cascader-menu-item-content, .n-cascader-node__label, .arco-cascader-option-label"),l=f((c==null?void 0:c.textContent)||a.textContent||""),u=w(l);if(!u)continue;const p=A(u);let y=Kn(u,p,s);!y&&t.fullText&&(t.fullText.includes(u)?y=100+u.length:u.includes(t.fullText)?y=70+t.fullText.length:t.looseFullText.includes(p)&&(y=80+p.length)),y>i&&(i=y,o=a)}return i>=75?o:null}function zn(e,t,n){const r=[],o=new Set,i=(s,a)=>{const c=w(s);!c||o.has(c)||(o.add(c),r.push({normalized:c,stripped:A(c),score:a}))};if(t.length){t[n]&&i(t[n],260);for(let s=n+1;s<t.length;s+=1)i(t[s],215-(s-n)*15)}e.structuredParts[n]&&i(e.structuredParts[n],235);for(let s=0;s<e.structuredParts.length;s+=1)s!==n&&i(e.structuredParts[s],180-Math.abs(s-n)*20);return e.fullText&&i(e.fullText,130),r}function Kn(e,t,n){let r=0;for(const o of n){let i=0;o.normalized===e?i=o.score+80:o.stripped&&o.stripped===t?i=o.score+68:o.normalized.includes(e)?i=o.score+40+e.length:e.includes(o.normalized)?i=o.score+28+o.normalized.length:o.stripped&&t&&o.stripped.includes(t)?i=o.score+24+t.length:o.stripped&&t&&t.includes(o.stripped)&&(i=o.score+20+o.stripped.length),i>r&&(r=i)}return r}function Vn(e,t){let n=0,r=0;for(let o=0;o<e.aliasesByLevel.length;o+=1){const i=Bn(e.aliasesByLevel[o],t.structuredParts[o]||"",t.fullText,t.looseFullText,o);i>0?(r+=1,n+=i):t.structuredParts[o]&&(n-=30)}return n+=r*18+e.labels.length*4,t.structuredParts.length>e.labels.length&&(n-=(t.structuredParts.length-e.labels.length)*10),n}function Bn(e,t,n,r,o){const i=[60,95,135,160][o]||160;let s=0;for(const a of e){let c=0;const l=A(a);t&&(t===a?c=Math.max(c,i+130+a.length):t.includes(a)||a.includes(t)?c=Math.max(c,i+95+Math.min(a.length,t.length)):l&&A(t)===l&&(c=Math.max(c,i+80+l.length))),n&&(n.includes(a)?c=Math.max(c,i+50+a.length):l&&r.includes(l)&&(c=Math.max(c,i+35+l.length))),c>s&&(s=c)}return s}function Un(e){const t=f(e),n=w(t);if(!n)return[];const r=new Set([n]),o=A(n);o&&!$n.has(t)&&r.add(o);const i={内蒙古自治区:"内蒙古",广西壮族自治区:"广西",西藏自治区:"西藏",宁夏回族自治区:"宁夏",新疆维吾尔自治区:"新疆",香港特别行政区:"香港",澳门特别行政区:"澳门"};return i[t]&&r.add(i[t]),Array.from(r).filter(Boolean)}function jn(){if(ue)return ue;const e=globalThis.__SMART_FILL_ADDRESS_MAP__,t=e==null?void 0:e.data,n=Array.isArray(t)?t:Array.isArray(t==null?void 0:t.data)?t.data:[];return ue=Gn(n),ue}function Gn(e){const t=[],n=new Set,r=o=>{const i=o.map(a=>f(a)).filter(Boolean);if(!i.length)return;const s=i.join(">");n.has(s)||(n.add(s),t.push({labels:i,aliasesByLevel:i.map(a=>Un(a))}))};for(const o of e)if(o!=null&&o.label&&(r([o.label]),!(!Array.isArray(o.children)||!o.children.length))){for(const i of o.children)if(i!=null&&i.label&&(r([o.label,i.label]),!(!Array.isArray(i.children)||!i.children.length)))for(const s of i.children)s!=null&&s.label&&r([o.label,i.label,s.label])}return t}function Y(e,t){const n=Ne(t);if(!n.length)return null;let r=null,o=0;for(const i of e){const s=C(i.value),a=C(i.label);for(const c of n){let l=0;c===s||c===a?l=120:s&&c.includes(s)||a&&c.includes(a)?l=100:s&&s.includes(c)||a&&a.includes(c)?l=90:(s&&fe(s)===fe(c)||a&&fe(a)===fe(c))&&(l=80),l>o&&(o=l,r=i)}}return o>=80?r:null}function Ne(e){if(Array.isArray(e))return e.flatMap(n=>Ne(n));if(typeof e=="object"&&e){const n=e;return[n.label,n.value,n.text,n.answer,n.name].filter(r=>r!=null).map(r=>C(r)).filter(Boolean)}const t=C(e);return t?[t]:[]}function C(e){return String(e??"").replace(/\s+/g,"").replace(/[::,,。.、()()\-_/]/g,"").trim().toLowerCase()}function fe(e){return C(e).replace(/(请选择|选择|状态|情况|类型|方式|所属|是否)$/g,"")}const pe=[".ant-select-item-option",".el-select-dropdown__item",".el-select-v2__option",".el-select-v2__option-item",".n-base-select-option",".ivu-select-item",".arco-select-option",".semi-select-option",".t-select-option",".van-picker-column__item",".van-action-sheet__item",".van-action-sheet__name",".van-cascader__option",".van-dropdown-item__option",".van-radio","[role='option']"].join(", "),Yn=[".el-cascader-panel .el-cascader-menu",".ant-cascader-menu",".van-cascader__options",".n-cascader-menu",".arco-cascader-list"].join(", "),Wn=[".el-cascader-node",".ant-cascader-menu-item",".van-cascader__option",".n-cascader-node",".arco-cascader-option"].join(", "),Xn=".van-picker__confirm, .van-picker__toolbar .van-picker__confirm",Zn=[".el-input__clear",".el-cascader__tags .el-tag__close",".el-tag__close",".ant-select-clear",".ant-cascader-picker-clear",".n-base-clear",".n-base-close",".arco-icon-close",".van-icon-clear",".van-field__clear"].join(", ");async function Jn(e,t,n,r){const o=tr(t,r);return e instanceof HTMLSelectElement?Qn(e,o):_(e)||n==="cascader"?er(e,o):(U(e)||F(e)||n==="select"||n==="date",xt(e,o))}function Et(e){if(e instanceof HTMLSelectElement){const n=e.options[e.selectedIndex];return f((n==null?void 0:n.textContent)||e.value)}if(_(e))return $e(e);if(U(e)||F(e))return dt(e);const t=e.querySelector("input, textarea");return f((t==null?void 0:t.value)||e.textContent||"")}async function Qn(e,t){const n=Array.from(e.options).map(o=>({source:o,value:o.value,label:o.textContent})),r=Y(n,t.searchValue);if((r==null?void 0:r.source)instanceof HTMLOptionElement){be(e,r.source.value),T(e);return}if(!W(e,t.fillValue))throw new Error("原生下拉框中没有匹配到对应选项")}async function xt(e,t){const n=ae(e)||e,r=dt(n);if(r&&Y([{value:r,label:r}],t.searchValue))return;const o=new Set(J());try{if(!await nr(n)){if(W(n,t.fillValue))return;throw new Error("自定义下拉框未能成功展开")}const s=await cr(n,o),a=await or(t.searchValue,s,!0);if(!(a!=null&&a.source)){if(await ge(n),W(n,t.fillValue))return;throw new Error("自定义下拉框展开后未找到匹配选项")}if(K(a.source),await b(120),ur(),T(n),await b(120),At(n,t.searchValue)||W(n,t.fillValue)&&At(n,t.searchValue))return;throw new Error("自定义下拉框点击选项后未成功回填")}finally{await ge(n),await b(80)}}async function er(e,t){const n=e.closest(".el-cascader, .ant-cascader, .van-cascader, .n-cascader, .arco-cascader")||e;if(!he(n,t.searchValue)&&!(X(n)&&(await ar(n),await b(120),he(n,t.searchValue)))){try{if(await rr(n)){const o=await ir(t.searchValue);if(await b(180),await ge(n),await b(120),o&&he(n,t.searchValue)){T(n);return}}if(sr(n,t.fillValue)&&he(n,t.searchValue))return}finally{await ge(n),await b(80)}throw new Error("级联选择框匹配失败")}}function tr(e,t){var o;const n=(o=t==null?void 0:t.options)!=null&&o.length?Y(t.options.map(i=>({value:String(i.value),label:i.label})),e):null,r=(n==null?void 0:n.value)??(n==null?void 0:n.label)??e;return{searchValue:n?[e,n.label,n.value]:e,fillValue:r}}async function nr(e){const t=He(e);for(const n of t)if(Ct(n),K(n),await b(160),_t(e)||(Tt(n),await b(180),_t(e)))return!0;return!1}async function rr(e){const t=[e,e.querySelector(".el-input__wrapper"),e.querySelector(".el-input"),e.querySelector(".van-field__control"),e.querySelector("input")].filter(n=>n instanceof HTMLElement);for(const n of t)if(Ct(n),K(n),await b(180),Z().length||(Tt(n),await b(180),Z().length))return!0;return!1}async function or(e,t,n=!1){for(let r=0;r<12;r+=1){const o=Y(kt(t,n).map(i=>({source:i,value:i.getAttribute("data-value")||i.getAttribute("value")||i.textContent||"",label:i.textContent||""})),e);if(o)return o;await b(100)}return null}async function ir(e){const t=de(e),n=fr(e,t);if(!t.fullText&&!t.structuredParts.length&&!n.length)return!1;const r=qe(e,t),o=Math.max(r.length,n.length,t.structuredParts.length,1);for(let i=0;i<o;i+=1){const s=Z();if(!s.length)return i>0;const a=s[Math.min(i,s.length-1)],c=Array.from(a.querySelectorAll(Wn)).filter(u=>!u.classList.contains("is-disabled")&&u.getAttribute("aria-disabled")!=="true");if(!c.length)return!1;let l=null;if((t.fullText||t.structuredParts.length)&&(l=Hn(c,t,r,i)),!l){const u=r[i]??n[i];if(!u)return!1;const p=Y(c.map(y=>{var M;return{source:y,value:y.getAttribute("data-value")||y.textContent,label:((M=y.querySelector(".el-cascader-node__label, .ant-cascader-menu-item-content, .n-cascader-node__label, .arco-cascader-option-label"))==null?void 0:M.textContent)||y.textContent}}),u);l=(p==null?void 0:p.source)??null}if(!l)return!1;if(K(l),await b(220),!Z().length)return!0}return!Z().length}function W(e,t){const n=D(t);if(!n)return!1;if(e instanceof HTMLSelectElement){let s=Array.from(e.options).find(a=>a.dataset.smartFillFallbackOption==="true");return s||(s=document.createElement("option"),s.dataset.smartFillFallbackOption="true",e.appendChild(s)),s.value=n,s.textContent=n,s.selected=!0,be(e,n),T(e),!0}const r=e.querySelector('input:not([type="hidden"])');if(!(r instanceof HTMLInputElement)||r.disabled)return!1;const o=r.readOnly,i=r.hasAttribute("readonly");try{return o&&(r.readOnly=!1,r.removeAttribute("readonly")),r.focus(),be(r,n),r.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,data:n,inputType:"insertReplacementText"})),r.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),T(r),T(e),r.blur(),!0}catch{return!1}finally{o&&(r.readOnly=!0,i&&r.setAttribute("readonly",""))}}function sr(e,t){const n=e.querySelector("input"),r=De(t)||D(t);return!(n instanceof HTMLInputElement)||!r||n.disabled?!1:W(e,r)}function $e(e){const t=e.querySelector("input");if(t instanceof HTMLInputElement&&t.value)return f(t.value);const n=e.querySelector(".el-cascader__tags-text, .el-cascader__label, .ant-cascader-picker-label, .n-base-selection-label, .arco-cascader-view-value");return f((n==null?void 0:n.textContent)||"")}function X(e){const t=$e(e);return!!(w(t)||C(t))}async function ar(e){if(!X(e))return!0;const t=e.querySelector(".el-input__wrapper, .el-input, .ant-select-selector, .ant-cascader-picker")??e;t instanceof HTMLElement&&(t.dispatchEvent(new MouseEvent("mouseenter",{bubbles:!0})),await b(80));const n=e.querySelector(Zn);if(n&&P(n)&&(K(n),await b(120),!X(e)))return!0;const r=e.querySelector('input:not([type="hidden"])');if(r instanceof HTMLInputElement&&!r.disabled){const o=r.readOnly,i=r.hasAttribute("readonly");try{if(o&&(r.readOnly=!1,r.removeAttribute("readonly")),r.focus(),be(r,""),r.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,data:"",inputType:"deleteContentBackward"})),r.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),T(r),T(e),r.blur(),await b(80),!X(e))return!0}finally{o&&(r.readOnly=!0,i&&r.setAttribute("readonly",""))}}return!X(e)}function He(e){return[e,e.querySelector(".van-field__control"),e.querySelector(".van-field__body"),e.querySelector(".el-select__wrapper"),e.querySelector(".el-select-v2__wrapper"),e.querySelector(".el-select__selection"),e.querySelector(".el-input__wrapper"),e.querySelector(".el-input"),e.querySelector("input"),e.querySelector("[role='combobox']"),e.querySelector("[aria-haspopup='listbox']"),e.querySelector(".ant-select-selector"),e.querySelector(".n-base-selection"),e.querySelector(".arco-select-view"),e.querySelector(".select-trigger"),e.querySelector(".select__wrapper")].filter(n=>n instanceof HTMLElement).filter((n,r,o)=>o.indexOf(n)===r)}function kt(e,t){return(e.length?e:J()).flatMap(o=>o.matches(pe)?[o]:Array.from(o.querySelectorAll(pe))).filter((o,i,s)=>s.indexOf(o)===i).filter(o=>t?!o.classList.contains("is-disabled")&&!o.classList.contains("ant-select-item-option-disabled")&&o.getAttribute("aria-disabled")!=="true":P(o)&&!o.classList.contains("is-disabled")&&!o.classList.contains("ant-select-item-option-disabled")&&o.getAttribute("aria-disabled")!=="true")}function Z(){return Array.from(document.querySelectorAll(Yn)).filter(P)}async function cr(e,t){for(let n=0;n<10;n+=1){const r=lr(e,t);if(r.length)return r;await b(80)}return J().filter(P)}function lr(e,t){const n=J(),r=n.filter(i=>!t.has(i));if(r.length)return r.sort((i,s)=>ye(s)-ye(i));const o=new Set(He(e).flatMap(i=>[i.getAttribute("aria-controls"),i.getAttribute("aria-owns")]).filter(i=>!!i));if(o.size){const i=n.filter(s=>o.has(s.id));if(i.length)return i}return n.filter(i=>P(i)&&(i.querySelector(pe)||i.matches(pe))).sort((i,s)=>ye(s)-ye(i)).slice(0,1)}function _t(e){return kt(J().filter(P),!1).length>0?!0:He(e).some(t=>t.getAttribute("aria-expanded")==="true"||t.classList.contains("is-focus")||t.classList.contains("is-focused"))}function he(e,t){const n=$e(e),r=w(n);if(!r)return!1;const o=De(t)||D(t),i=w(o);if(Pe(r,i))return!0;const s=de(t),a=qe(t,s);if(Pe(r,w(a.join(""))))return!0;const c=w(s.structuredParts.join(""));return Pe(r,c)}function At(e,t){const n=C(Et(e)),r=C(D(t));return!n||!r?!1:n===r||n.includes(r)||r.includes(n)}function ur(){const e=document.querySelector(Xn);e&&P(e)&&K(e)}async function ge(e){e==null||e.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",code:"Escape",bubbles:!0})),document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",code:"Escape",bubbles:!0})),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),document.body.dispatchEvent(new MouseEvent("mousedown",{bubbles:!0,cancelable:!0,view:window})),document.body.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,view:window})),document.body.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),await b(120)}function J(){return Array.from(document.querySelectorAll(dr()))}function ye(e){const t=e.getBoundingClientRect(),n=Number.parseInt(window.getComputedStyle(e).zIndex||"0",10);return(Number.isNaN(n)?0:n)*10+t.width*t.height}function dr(){return[".el-select-dropdown",".el-cascader__dropdown",".el-cascader-panel",".el-select__popper",".el-select-v2__popper",".el-popper.el-cascader__dropdown",".el-popper.el-select__popper",".el-popper.el-select-v2__popper",".el-popper",".ant-select-dropdown",".ant-cascader-menus",".n-base-select-menu",".n-cascader-menu",".arco-select-dropdown",".arco-cascader-panel",".semi-select-dropdown",".t-select__dropdown",".van-popup",".van-action-sheet",".van-dropdown-item__content",".van-picker","[role='listbox']"].join(", ")}function D(e){if(e==null)return"";if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return f(String(e));if(Array.isArray(e))return e.map(t=>D(t)).filter(Boolean).join(" ");if(typeof e=="object"){const t=e;for(const n of["label","text","value","answer","name"]){const r=D(t[n]);if(r)return r}}return f(String(e))}function fr(e,t=de(e)){if(t.structuredParts.length)return t.structuredParts.map(i=>f(i));const n=qe(e,t);if(n.length)return n;const r=D(e);if(!r)return[];if(r.includes("/")||r.includes("、"))return r.split(/[//、]/).map(i=>i.trim()).filter(Boolean);const o=Ne(e);return o.length?[f(o[0])]:[r]}function be(e,t){var o;const n=Object.getPrototypeOf(e),r=Object.getOwnPropertyDescriptor(n,"value");(o=r==null?void 0:r.set)==null||o.call(e,t)}function T(e){e.dispatchEvent(new Event("focus",{bubbles:!0})),e.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,data:null,inputType:"insertText"})),e.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),e.dispatchEvent(new Event("blur",{bubbles:!0}))}function K(e){window.PointerEvent&&(e.dispatchEvent(new PointerEvent("pointerdown",{bubbles:!0,composed:!0,button:0})),e.dispatchEvent(new PointerEvent("pointerup",{bubbles:!0,composed:!0,button:0}))),e.dispatchEvent(new MouseEvent("mousedown",{bubbles:!0,composed:!0,button:0})),e.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,composed:!0,button:0})),e.click()}function Ct(e){e.focus({preventScroll:!0});const t=e instanceof HTMLInputElement?e:e.querySelector("input");t instanceof HTMLElement&&t.focus({preventScroll:!0})}function Tt(e){for(const t of[{key:"ArrowDown",code:"ArrowDown"},{key:"Enter",code:"Enter"},{key:" ",code:"Space"}])e.dispatchEvent(new KeyboardEvent("keydown",{...t,bubbles:!0,composed:!0})),e.dispatchEvent(new KeyboardEvent("keyup",{...t,bubbles:!0,composed:!0}))}function P(e){const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||Number(t.opacity)===0)return!1;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}function b(e){return new Promise(t=>window.setTimeout(t,e))}const Lt=new Set(["select","cascader","date"]),ze={name:"ui-framework",match:e=>e.matches(nt)||ot(e)||!hr(e)&&j(e),getValue:e=>{var o,i;const t=e.element;if(!t)return;const n=$(t);if((n==null?void 0:n.kind)==="switch")return B(t);if((n==null?void 0:n.kind)==="radioGroup")return mr(t);if((n==null?void 0:n.kind)==="checkboxGroup")return vr(t);const r=e.type||ie(t)||(n==null?void 0:n.type);return r&&Lt.has(r)?Et(t):n?((i=H(t))==null?void 0:i.value)||t.textContent||void 0:(o=H(t))==null?void 0:o.value},setValue:async(e,t)=>{const n=e.element;if(!n)return;const r=$(n);if((r==null?void 0:r.kind)==="switch"){gr(n,t);return}if((r==null?void 0:r.kind)==="radioGroup"){br(n,t);return}if((r==null?void 0:r.kind)==="checkboxGroup"){yr(n,t);return}const o=e.type||ie(n)||(r==null?void 0:r.type);if(o&&Lt.has(o)||j(n,o||void 0)){await Jn(n,t,o||"select",e);return}const i=H(n);if(i){wr(i,t);return}n.dispatchEvent(new Event("change",{bubbles:!0}))}},pr=ze;function hr(e){return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement}function gr(e,t){B(e)!==Sr(t)&&me(e)}function yr(e,t){var o;const n=new Set(Er(t).map(L)),r=it(e)||[];for(const i of Q(e)){const s=ee(i.textContent||""),a=i.getAttribute("value")||((o=i.querySelector("input"))==null?void 0:o.value)||s,c=B(i),l=n.has(L(String(a)))||n.has(L(s));c!==l&&me(i)}if(!Q(e).length&&r.length)for(const i of r)(n.has(L(String(i.value)))||n.has(L(i.label)))&&me(e)}function br(e,t){const n=L(String(t??"")),r=Q(e).find(o=>{var a;const i=ee(o.textContent||""),s=o.getAttribute("value")||((a=o.querySelector("input"))==null?void 0:a.value)||i;return L(String(s))===n||L(i)===n});r&&me(r)}function mr(e){var n;const t=Q(e).find(r=>B(r));if(t)return t.getAttribute("value")||((n=t.querySelector("input"))==null?void 0:n.value)||ee(t.textContent||"")}function vr(e){return Q(e).filter(t=>B(t)).map(t=>{var n;return t.getAttribute("value")||((n=t.querySelector("input"))==null?void 0:n.value)||ee(t.textContent||"")})}function Q(e){const t=$(e);return t!=null&&t.optionSelector?Array.from(e.querySelectorAll(t.optionSelector)):[]}function wr(e,t){e.value=String(t??""),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new Event("blur",{bubbles:!0}))}function me(e){e.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window}))}function Sr(e){return typeof e=="boolean"?e:["true","1","是","开启","启用","yes","y"].includes(String(e??"").trim().toLowerCase())}function Er(e){return Array.isArray(e)?e.map(String):String(e??"").split(/[,,;;、]/).map(t=>t.trim()).filter(Boolean)}function L(e){return ee(e).toLowerCase()}function ee(e){return e.replace(/\s+/g," ").trim()}const It="https://uat.kingdeefin.com";class Mt extends Error{constructor(n){super(n.message);d(this,"smartFillError");this.name="SmartFillException",this.smartFillError=n}}function S(e,t,n,r={}){return new Mt({code:e,message:t,stage:n,...r})}function Rt(e,t,n="RECOGNIZE_FAILED"){return e instanceof Mt?e.smartFillError:{code:n,message:e instanceof Error?e.message:String(e||"智能录入异常"),stage:t,retryable:t==="recognize"}}function ve(e="sf"){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}class xr{constructor(t){d(this,"seToken","");d(this,"baseURL",It);this.config=t}setAccessToken(t){this.seToken=t}async createSession(){if(!/^seKey-[A-Za-z0-9_-]{6,}$/.test(this.config.apiKey))throw S("API_KEY_INVALID","apiKey 格式不正确,应以 seKey- 开头。","setup");return{apiKey:this.config.apiKey,rulesVersion:"0.0.1"}}async getFormConfig(t){return t?this.request(`/sdk/forms/${encodeURIComponent(t)}`,{method:"GET"}):null}async resolveInputText(t){var i,s,a,c;const n=(i=t.images)!=null&&i.length?t.images:[],r=((s=t.text)==null?void 0:s.trim())||"";if(!n.length)return{text:r,usedOcr:!1};(a=t.onStatusChange)==null||a.call(t,"image_uploading");const o=await this.recognizeImages(n);return(c=t.onStatusChange)==null||c.call(t,"image_recognizing"),{text:o,usedOcr:!0}}async recognize(t){var s,a;const n=performance.now(),r=(s=t.text)==null?void 0:s.trim();(a=t.onStatusChange)==null||a.call(t,"recognizing");const o=await this.request("/fcloud/flow-product/agentChat/smartEntry",{method:"POST",body:JSON.stringify({formCode:t.formCode||"",configVersion:t.configVersion||"",formMsg:t.fields.map(({fingerprint:c,element:l,localRuleMode:u,scanToken:p,source:y,...M})=>M),userInputMsg:r||""})}),i=_r(o,t.fields,t.scanToken);return console.log("suggestions",i),{scanToken:t.scanToken,suggestions:i,trace:o.trace||{traceId:ve("trace"),usedOcr:!!t.usedOcr,usedAi:!0,durationMs:Math.round(performance.now()-n)}}}async recognizeImages(t){const n=new FormData;t.forEach(i=>{n.append("image",i,i.name)});const r=await this.request("/fcloud/flow-product/agentChat/smartEntry/ocr",{method:"POST",body:n}),o=Cr(r);if(!o)throw S("RECOGNIZE_FAILED","图片识别未提取到文本内容。","recognize");return o}async request(t,n){const r=new AbortController,o=window.setTimeout(()=>r.abort(),this.config.requestTimeoutMs??3e4),i=new Headers(n.headers);n.body&&!(n.body instanceof FormData)&&!i.has("Content-Type")&&i.set("Content-Type","application/json"),i.set("x-trace-id",ve("trace")),this.seToken&&i.set("seToken",`${this.seToken}`);try{const s=await fetch(`${this.baseURL}${t}`,{...n,headers:i,signal:r.signal});if(!s.ok)throw S(Tr(s.status),await s.text(),t.includes("session")?"setup":"recognize",{retryable:s.status>=500||s.status===429});return s.json()}catch(s){throw s instanceof DOMException&&s.name==="AbortError"?S("RECOGNIZE_TIMEOUT","识别请求超时,请稍后重试。","recognize",{retryable:!0}):s}finally{window.clearTimeout(o)}}}const kr=.95;function _r(e,t,n){var i;const r=new Map(t.map(s=>[s.fieldId,s]));return(((i=e.data)==null?void 0:i.fieldValues)||[]).filter(s=>!!(s!=null&&s.fieldId)).map(s=>{const a=r.get(s.fieldId);return{fieldId:s.fieldId,scanToken:n,label:s.label||(a==null?void 0:a.label)||s.fieldId,value:s.value,displayValue:s.value==null?"":String(s.value),confidence:Ar(s.confidence),source:s.source||"ai",warnings:s.warnings}})}function Ar(e){return typeof e!="number"||Number.isNaN(e)?kr:e<0?0:e>1?1:e}function Cr(e){var n;const t=typeof e.data=="string"?e.data:((n=e.data)==null?void 0:n.text)||e.text||"";return String(t||"").trim()}function Tr(e){return e===401?"TOKEN_EXPIRED":e===403?"API_KEY_FORBIDDEN":e===404?"FORM_CONFIG_NOT_FOUND":"RECOGNIZE_FAILED"}class Ke{constructor(){d(this,"handlers",new Map)}on(t,n){const r=this.handlers.get(t)??new Set;return r.add(n),this.handlers.set(t,r),()=>this.off(t,n)}off(t,n){var r;(r=this.handlers.get(t))==null||r.delete(n)}emit(t,n){var r;(r=this.handlers.get(t))==null||r.forEach(o=>o(n))}clear(){this.handlers.clear()}}class Lr{constructor(){d(this,"instances",new Set);d(this,"active",null)}add(t){this.instances.add(t)}activate(t){this.active&&this.active!==t&&this.active.close(),this.active=t}remove(t){this.instances.delete(t),this.active===t&&(this.active=null)}destroyAll(){this.instances.forEach(t=>t.destroy()),this.instances.clear(),this.active=null}}const Ir=[/^(el|rc|ant|radix|headlessui|mui|chakra)-/i,/[0-9a-f]{8,}/i,/\d{6,}/];function x(e){const t=String(e||"").trim();return!t||Ir.some(n=>n.test(t))?"":t}function te(e){const t=(e.options||[]).slice(0,20).map(n=>`${n.label}:${String(n.value)}`).join("|");return V([e.fieldId,e.tagName,e.type,x(e.name),x(e.id),e.label,e.placeholder,e.section,t].join("::"))}function V(e){return String(e??"").replace(/\s+/g," ").trim().toLowerCase()}const Ve=new WeakMap,Mr=['input:not([type="hidden"])',"textarea","select",".el-input__wrapper",".el-select__wrapper",".el-select-v2__wrapper",".el-date-editor",".ant-select-selector",".ant-picker",".n-base-selection",".n-input__input-el",".arco-select-view",".arco-picker",".ivu-select-selection",".semi-select-selection",".t-input__wrap",".van-field__control",".van-field__body","[role='combobox']"].join(", ");class Be{constructor(t,n,r=[]){this.fields=t,this.schemas=n,this.adapters=r}async apply(t){const n=[],r=[];for(const o of t.values){const i=this.fields.find(l=>l.fieldId===o.fieldId);if(!i){r.push(Se(o.fieldId,"",o.value,"字段不在当前扫描结果中","FIELD_NOT_FOUND"));continue}if(i.scanToken!==t.scanToken){r.push(Se(i.fieldId,i.label,o.value,"页面扫描已过期,请重新扫描","SCAN_TOKEN_EXPIRED"));continue}const s=qr(this.schemas,o.fieldId),a=s!=null&&s.transform?s.transform(o.value):o.value,c=await this.getValue(i,s);try{const l=s!=null&&s.validate?await s.validate(a):!0;if(l!==!0){r.push(Se(i.fieldId,i.label,a,typeof l=="string"?l:"字段校验未通过","VALIDATE_FAILED"));continue}await this.setValue(i,a,s),n.push({fieldId:i.fieldId,label:i.label,value:a,previousValue:c})}catch(l){r.push(Se(i.fieldId,i.label,a,l instanceof Error?l.message:"字段回填失败","SET_VALUE_FAILED"))}}return{applied:n,skipped:r,warnings:r.length?["部分字段未回填,请查看跳过原因。"]:void 0}}async getValue(t,n){if(n!=null&&n.getValue)return n.getValue();const r=this.matchAdapter(t,n);if(r!=null&&r.getValue)return r.getValue(t);const o=we(t,n);if(o)return o instanceof HTMLInputElement&&o.type==="checkbox"?o.checked:o instanceof HTMLInputElement&&o.type==="radio"?o.checked?o.value:void 0:o instanceof HTMLInputElement||o instanceof HTMLTextAreaElement||o instanceof HTMLSelectElement?o.value:o.textContent}async setValue(t,n,r){if(r!=null&&r.setValue){await r.setValue(n);const a=we(t,r);a&&Ue(a,t);return}const o=we(t,r);if(!o)throw new Error("页面中未找到对应字段");if(t.fingerprint&&t.fingerprint!==te({...t,tagName:o.tagName.toLowerCase()}))throw new Error("字段结构已变化,请重新扫描");const i=this.matchAdapter(t,r),s=j(o,t.type);if(t.disabled||o.hasAttribute("disabled")||o.getAttribute("aria-disabled")==="true")throw new Error("字段不可编辑");if(!s&&!i&&(t.readonly||o.hasAttribute("readonly")))throw new Error("字段不可编辑");if(i){await i.setValue(t,n),Ue(o,t);return}Fr(o,n),Ue(o,t)}matchAdapter(t,n){const r=we(t,n);return r?this.adapters.find(o=>o.match(r,t)):void 0}}function we(e,t){var r;if((r=e.element)!=null&&r.isConnected)return e.element;const n=Rr(t==null?void 0:t.element);return n||document.querySelector(`[data-smart-fill-id="${je(e.fieldId)}"]`)}function Rr(e){if(e instanceof HTMLElement)return e.isConnected?e:null;if(typeof e=="string")try{const t=document.querySelector(e);return t instanceof HTMLElement?t:null}catch{return null}return null}function Fr(e,t){if(e instanceof HTMLInputElement&&e.type==="checkbox")e.checked=!!t;else if(e instanceof HTMLInputElement&&e.type==="radio"){const n=document.querySelector(`input[type="radio"][name="${je(e.name)}"][value="${je(String(t))}"]`);(n||e).checked=!0}else e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement?e.value=String(t??""):e.isContentEditable&&(e.textContent=String(t??""));e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}function Ue(e,t){for(const n of Or(e,t))Dr(n)}function Or(e,t){if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)return[e];const n=j(e,t==null?void 0:t.type)&&ae(e)||e,r=Pr(Array.from(n.querySelectorAll(Mr)).filter(Ft));if(r.length)return r;const o=H(n);return o&&Ft(o)?[o]:[n]}function Dr(e){var r;e.setAttribute("data-smart-fill-highlighted","true"),(r=Ve.get(e))==null||r.abort();const t=new AbortController,n=o=>{o&&"isTrusted"in o&&!o.isTrusted||(e.removeAttribute("data-smart-fill-highlighted"),t.abort(),Ve.delete(e))};Ve.set(e,t),e.addEventListener("focus",n,{signal:t.signal}),e.addEventListener("pointerdown",n,{signal:t.signal}),e.addEventListener("keydown",n,{signal:t.signal}),e.addEventListener("input",n,{signal:t.signal}),e.addEventListener("change",n,{signal:t.signal})}function Pr(e){return e.filter(t=>!e.some(n=>n!==t&&n.contains(t)))}function Ft(e){const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||Number(t.opacity)===0)return!1;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}function Se(e,t,n,r,o){return{fieldId:e,label:t,attemptedValue:n,reason:r,reasonCode:o}}function je(e){return typeof CSS<"u"&&CSS.escape?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function qr(e,t){const n=e.find(o=>o.fieldId===t);if(n)return n;const r=t.includes(":")?t.slice(t.lastIndexOf(":")+1):"";if(r)return e.find(o=>o.rowKey!=null&&String(o.rowKey)===r&&`${o.fieldId}:${o.rowKey}`===t)}const Nr=[{key:"mobile",pattern:new RegExp("(?<!\\d)1[3-9]\\d{9}(?!\\d)","g"),confidence:.98,reason:"手机号正则命中"},{key:"idCard",pattern:new RegExp("(?<!\\d)\\d{17}[\\dXx](?!\\d)","g"),confidence:.96,reason:"身份证号正则命中"},{key:"email",pattern:/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,confidence:.95,reason:"邮箱正则命中"},{key:"bankCard",pattern:new RegExp("(?<!\\d)\\d{16,19}(?!\\d)","g"),confidence:.9,reason:"银行卡号正则命中"},{key:"amount",pattern:/(?:金额|价格|费用|合计|总计)[::\s]*([0-9]+(?:\.[0-9]{1,2})?)/g,confidence:.88,reason:"金额关键词命中"},{key:"date",pattern:/\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2}日?/g,confidence:.86,reason:"日期格式命中"}],q={mobile:["手机","手机号","电话","联系电话","mobile","phone","法人手机号","法人电话","法定代表人手机号","法人手机","紧急联系人手机号","紧急联系人电话","紧急联系电话","联系人手机号","联系人电话","联系手机","配偶手机号","配偶电话","爱人手机号"],idCard:["身份证","证件号","身份证号","idcard","id card","法人身份证","法人身份证号","法定代表人身份证号","配偶身份证","配偶身份证号","爱人身份证号"],email:["邮箱","邮件","email","mail","联系人邮箱","联系邮箱","contact email"],bankCard:["银行卡","卡号","bank","bank card"],amount:["金额","费用","价格","合计","总计","amount","price","申请金额","贷款金额","借款金额","授信金额","申请额度"],date:["日期","时间","有效期","date","申请日期","申请时间","受理日期","进件日期"]},Ot={mobile:"mobile",idCard:"idCard",email:"email",bankCard:"bankCard",amount:"amount",date:"date"};class Dt{recognize(t,n,r){const o=Gr([...$r(t),...Hr(t)]),i=new Set,s=[];for(const a of o.sort((c,l)=>l.confidence-c.confidence)){const c=Kr(a,n,i);c&&(s.push({fieldId:c.fieldId,scanToken:r,label:c.label,value:Br(a.value,c),displayValue:a.value,confidence:a.confidence,source:"local_rule",reason:a.reason}),i.add(c.fieldId))}return s}}function $r(e){const t=[];for(const n of Nr)for(const r of e.matchAll(n.pattern)){const o=Pt(r[1]||r[0]);t.push({key:n.key,value:o,confidence:n.confidence,reason:n.reason,baseKey:Ot[n.key]})}return t}function Hr(e){const t=[],n=e.split(/\r?\n|[;,;]/).map(r=>r.trim()).filter(Boolean);for(const r of n){const o=r.match(/^[“"'`]?([^::=]{2,30})[”"'`]?[::=]\s*(.+)$/);if(!o)continue;const i=jr(o[1]),s=Pt(o[2]);if(!(!i||!s))for(const a of zr(i,s))t.push(a)}return t}function zr(e,t){const n=V(e),r=Ur(t),o=[];return(I(n,q.mobile)||r==="mobile")&&o.push("mobile"),(I(n,q.idCard)||r==="idCard")&&o.push("idCard"),(I(n,q.email)||r==="email")&&o.push("email"),(I(n,q.bankCard)||r==="bankCard")&&o.push("bankCard"),(I(n,q.amount)||r==="amount")&&o.push("amount"),(I(n,q.date)||r==="date")&&o.push("date"),Yr(o).map((i,s)=>({key:i,value:t,confidence:Math.max(.84,.96-s*.04),reason:`键值对文本命中(${e})`,baseKey:Ot[i]}))}function Kr(e,t,n){let r=null;for(const o of t){if(n.has(o.fieldId))continue;const i=Vr(e,o);i>((r==null?void 0:r.score)??0)&&(r={field:o,score:i})}return r&&r.score>=.45?r.field:null}function Vr(e,t){const n=V([t.fieldId,t.label,t.placeholder,t.name,t.id,t.section].join(" ")),r=q[e.key]||[e.key];let o=0;return I(n,r)?o+=.95:I(n,[e.key])&&(o+=.82),n.includes(V(e.key))&&(o+=.22),t.required&&(o+=.05),e.baseKey==="amount"&&(t.type==="amount"||t.type==="number")&&(o+=.18),e.baseKey==="date"&&t.type==="date"&&(o+=.18),["email","mobile","idCard","bankCard"].includes(e.baseKey)&&t.type==="text"&&(o+=.08),Math.min(o,1)}function Br(e,t){var n;return t.type==="date"?e.replace(/[年月/.]/g,"-").replace(/日/g,"").replace(/--/g,"-"):t.type==="number"||t.type==="amount"?((n=e.match(/[0-9]+(?:\.[0-9]+)?/))==null?void 0:n[0])??e:t.name&&/mobile|phone|idcard|bankcard/i.test(t.name)||t.id&&/mobile|phone|idcard|bankcard/i.test(t.id)||/mobile|phone|idcard|bankcard/i.test(t.fieldId)?e.replace(/\s+/g,""):e}function Ur(e){const t=e.replace(/\s+/g,"");return/^1[3-9]\d{9}$/.test(t)?"mobile":/^\d{17}[\dXx]$/.test(t)?"idCard":/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(e)?"email":/^\d{16,19}$/.test(t)?"bankCard":/^\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2}日?$/.test(e)?"date":/^[0-9]+(?:\.[0-9]{1,2})?$/.test(t)?"amount":"unknown"}function jr(e){return e.replace(/[“”"'`]/g,"").replace(/\s+/g," ").trim()}function Pt(e){return e.replace(/[,。;;]+$/g,"").replace(/^[“”"'`\s]+|[“”"'`\s]+$/g,"").trim()}function I(e,t){const n=V(e);return t.some(r=>n.includes(V(r)))}function Gr(e){const t=new Map;for(const n of e){const r=`${n.key}::${n.value}`,o=t.get(r);(!o||o.confidence<n.confidence)&&t.set(r,n)}return[...t.values()]}function Yr(e){return[...new Set(e)]}const qt=["input","textarea","select","[contenteditable]:not([contenteditable='false'])"].join(", "),Wr=new Set(["hidden","submit","button","image","reset","file","password"]);class Nt{constructor(t=document){this.root=t}scan(t={}){var l;const n=ve("scan");if((l=t.registered)!=null&&l.length)return{scanToken:n,fields:t.registered.map(u=>this.fromSchema(u,n))};const r=this.resolveRoot(t.scanContainer),o=this.collectVisibleFields(r),i=this.detectTopLayerContainer(o),s=o.filter(u=>i.contains(u)),a=(s.length?s:o).slice(0,t.maxFields??200),c=s.length?i:r;return{scanToken:n,fields:a.map((u,p)=>this.fromElement(u,p,n,c))}}async scanWithDynamicOptions(t={}){var o,i;const n=this.scan(t);if(!n.fields.length||(o=t.registered)!=null&&o.length)return n;const r=[];for(const s of n.fields){const a=!!((i=s.options)!=null&&i.length)&&!ce(s);if(!s.element||a||s.type!=="select"&&s.type!=="cascader"){r.push(s);continue}const c=await wn(s.element),l=c!=null&&c.length&&!ce({...s,options:c})?c:void 0;if(!(l!=null&&l.length)){r.push({...s,options:ce(s)?void 0:s.options});continue}const u={...s,options:l};u.fingerprint=te({...u,tagName:s.element.tagName.toLowerCase()}),r.push(u)}return{...n,fields:r}}fromSchema(t,n){const r=io(t.element,this.root),o=r?Re(r)||Te(r)||r:null,i={fieldId:t.rowKey==null?t.fieldId:`${t.fieldId}:${t.rowKey}`,label:t.label,type:t.type,localRuleMode:t.localRuleMode??"inherit",required:t.required,section:t.section,options:t.options,demoValue:t.demoValue,source:"registered",scanToken:n,element:o||void 0,fingerprint:""};return i.fingerprint=te({...i,tagName:o==null?void 0:o.tagName.toLowerCase()}),i}fromElement(t,n,r,o=this.root){const i=Xr(t,n),s=Qr(t,o),a={fieldId:i,fingerprint:"",scanToken:r,type:Zr(t),localRuleMode:"inherit",label:$t(t),placeholder:zt(t),name:x(st(t))||void 0,id:x(t.id)||void 0,section:Jr(t),options:s,required:no(t),readonly:to(t)&&!vn(t),disabled:Ye(t),source:"form_scan",element:t};return ce(a)&&(a.options=void 0),a.fingerprint=te({...a,tagName:t.tagName.toLowerCase()}),a}resolveRoot(t){if(t){const n=Kt(this.root,t);if(n)return n}return this.root}collectVisibleFields(t){const n=new Set,r=[qt,ct,nt,".van-field"].join(", ");for(const s of t.querySelectorAll(r)){if(!(s instanceof HTMLElement))continue;const a=Re(s)||Te(s);!a||!Ge(a)||Ye(a)||n.add(a)}const o=[...n],i=Array.from(t.querySelectorAll(qt)).filter(s=>!(s instanceof HTMLElement)||!Ge(s)||ro(s)||s instanceof HTMLInputElement&&Wr.has((s.type||"").toLowerCase())?!1:!Ye(s)&&!s.hasAttribute("readonly"));return oo([...i,...o])}detectTopLayerContainer(t){const n=document.activeElement instanceof HTMLElement?document.activeElement:null,r=n==null?void 0:n.closest(rt);if(r instanceof HTMLElement&&t.some(i=>r.contains(i)))return r;const o=t.map(i=>i.closest(rt)).filter(i=>i instanceof HTMLElement);return o.length?o.sort((i,s)=>t.filter(a=>s.contains(a)).length-t.filter(a=>i.contains(a)).length)[0]:document.body}}function Xr(e,t){const n=e.getAttribute("data-smart-fill-id");if(n)return n;const o=x(e.getAttribute("name"))||x(e.getAttribute("data-smart-fill-key"))||x(st(e))||x(e.id)||x($t(e))||`smart-fill-${Date.now()}-${t}`;return e.setAttribute("data-smart-fill-id",o),o}function Zr(e){const t=Fe(e);if(t)return t;const n=ie(e);if(n)return n;if(e instanceof HTMLTextAreaElement)return"textarea";if(e instanceof HTMLSelectElement)return"select";if(e instanceof HTMLInputElement){const r=(e.type||"text").toLowerCase();if(r==="radio")return"radio";if(r==="checkbox")return"checkbox";if(r==="date"||r==="month")return"date";if(r==="number")return"number"}return"text"}function $t(e){const t=e.getAttribute("aria-label");if(t)return t.trim();if(e.id){const i=document.querySelector(`label[for="${We(e.id)}"]`);if(i!=null&&i.textContent)return f(i.textContent)}const n=e.closest(dn),r=n==null?void 0:n.querySelector(fn);if(r!=null&&r.textContent)return f(r.textContent);const o=e.closest("label");if(o){const i=Ht(o,e);if(i)return i}return zt(e)||e.getAttribute("name")||e.id||"未命名字段"}function Ht(e,t){const n=e.cloneNode(!0);for(const o of n.querySelectorAll('input, textarea, select, button, [role="combobox"], [role="listbox"]'))o.remove();const r=f(n.textContent||"");if(r)return t instanceof HTMLInputElement&&t.value&&r.includes(t.value)?f(r.replace(t.value,""))||void 0:r}function zt(e){var t;return e.getAttribute("placeholder")||e.getAttribute("aria-placeholder")||((t=e.querySelector("[placeholder]"))==null?void 0:t.getAttribute("placeholder"))||void 0}function Jr(e){const t=e.closest("fieldset, section, .panel, .card, .form-section"),n=t==null?void 0:t.querySelector("legend, h1, h2, h3, .title, .section-title");return n!=null&&n.textContent?f(n.textContent):void 0}function Qr(e,t=document){const n=ft(e);if(n!=null&&n.length)return n;const r=it(e);if(r!=null&&r.length)return r;if(e instanceof HTMLSelectElement)return Array.from(e.options).map(o=>({label:f(o.textContent||o.label),value:o.value}));if(e instanceof HTMLInputElement&&(e.type==="radio"||e.type==="checkbox")&&e.name)return Array.from(t.querySelectorAll(`input[name="${We(e.name)}"]`)).filter(o=>o.type===e.type&&Ge(o)).map(o=>({label:eo(o),value:o.value||!0}))}function eo(e){if(e.id){const n=document.querySelector(`label[for="${We(e.id)}"]`);if(n!=null&&n.textContent)return f(n.textContent)}const t=e.closest("label");if(t){const n=Ht(t,e);if(n)return n}return f(e.getAttribute("aria-label")||e.value||"")}function Ge(e){const t=window.getComputedStyle(e);return t.display==="none"||t.visibility==="hidden"||Number(t.opacity)===0?!1:!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)}function Ye(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement||e instanceof HTMLButtonElement?e.disabled||e.getAttribute("aria-disabled")==="true":e.hasAttribute("disabled")||e.getAttribute("aria-disabled")==="true"||un.some(t=>e.classList.contains(t))}function to(e){return e.hasAttribute("readonly")||!!e.querySelector("[readonly]")}function no(e){return e.hasAttribute("required")||e.getAttribute("aria-required")==="true"||!!e.querySelector('[required], [aria-required="true"]')}function ro(e){return Re(e)!=null||Te(e)!=null}function oo(e){const t=[];for(const n of e)t.some(r=>r===n||r.contains(n)||n.contains(r))||t.push(n);return t}function io(e,t){return e instanceof HTMLElement?e:typeof e=="string"?Kt(t,e):null}function Kt(e,t){try{const n=e.querySelector(t);return n instanceof HTMLElement?n:null}catch{return null}}function We(e){return typeof CSS<"u"&&CSS.escape?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}const Xe=5,so=10*1024*1024,ao=50*1024*1024;class co{constructor(t){d(this,"host",null);d(this,"root",null);d(this,"autoApplyState",null);d(this,"selectedFiles",[]);d(this,"inputText","");d(this,"localPriorityEnabled");d(this,"isOpen",!1);d(this,"dragState",null);d(this,"suppressOpenClick",!1);d(this,"isUploadHovering",!1);d(this,"handleDragMove",t=>{if(!this.dragState||!this.host||t.pointerId!==this.dragState.pointerId)return;const n=t.clientX-this.dragState.startX,r=t.clientY-this.dragState.startY;(Math.abs(n)>3||Math.abs(r)>3)&&(this.dragState.moved=!0);const o=this.host.getBoundingClientRect(),i=Math.max(8,window.innerWidth-o.width-8),s=Math.max(8,window.innerHeight-o.height-8),a=Ee(this.dragState.startLeft+n,8,i),c=Ee(this.dragState.startTop+r,8,s);this.host.style.left=`${a}px`,this.host.style.top=`${c}px`});d(this,"handleDragEnd",t=>{!this.dragState||t.pointerId!==this.dragState.pointerId||(this.suppressOpenClick=this.dragState.moved,this.dragState=null,document.removeEventListener("pointermove",this.handleDragMove),document.removeEventListener("pointerup",this.handleDragEnd),document.removeEventListener("pointercancel",this.handleDragEnd),this.suppressOpenClick&&window.setTimeout(()=>{this.suppressOpenClick=!1},0))});d(this,"handleDocumentPaste",t=>{const n=uo(t);if(!n.length||!this.isOpen||!this.host)return;const r=document.activeElement,o=this.root instanceof ShadowRoot?this.root.activeElement:null;!(r===this.host||this.host.contains(r)||o)&&!this.isUploadHovering||(t.preventDefault(),this.handleImages(n))});this.options=t,this.localPriorityEnabled=t.localPriorityEnabled??!1}mount(t){this.host=document.createElement("div"),this.host.className=`sf-sdk-host sf-sdk-host-${this.options.mode}`,t.appendChild(this.host),this.root=this.host.attachShadow?this.host.attachShadow({mode:"open"}):this.host,this.isOpen=this.options.initialOpen??this.options.mode==="inline",document.addEventListener("paste",this.handleDocumentPaste),this.render(this.isOpen)}setOpen(t){this.isOpen=t,this.render(this.isOpen),this.keepHostInViewport()}setLocalPriorityEnabled(t){this.localPriorityEnabled=t;const n=this.query('[data-role="local-priority-toggle"]');n&&(n.checked=t)}setBusy(t,n=""){const r=this.query('[data-role="recognize"]');r&&(r.disabled=t,r.textContent=t?n:this.t("recognize","智能识别"))}setStatus(t){const n=this.query('[data-role="status"]');n&&(n.textContent=t,n.removeAttribute("data-status"))}setError(t){const n=this.query('[data-role="status"]');n&&(n.textContent=t,n.setAttribute("data-status","error"))}setAutoApplyState(t){this.autoApplyState=t,this.render(!0),this.keepHostInViewport(),this.setStatus(this.t("recognized","识别完成,正在自动回填..."))}setApplyResult(t){const n=this.query('[data-role="status"]');n&&(n.textContent=`已回填 ${t.applied.length} 项,跳过 ${t.skipped.length} 项。`,n.setAttribute("data-status",t.skipped.length?"warning":"success"))}destroy(){var t;document.removeEventListener("pointermove",this.handleDragMove),document.removeEventListener("pointerup",this.handleDragEnd),document.removeEventListener("pointercancel",this.handleDragEnd),document.removeEventListener("paste",this.handleDocumentPaste),(t=this.host)==null||t.remove(),this.host=null,this.root=null,this.dragState=null,this.isUploadHovering=!1}render(t){this.root&&(this.root.innerHTML=`
|
|
11
|
+
<style>${fo}</style>
|
|
3
12
|
${this.options.mode==="floating"?`<button class="sf-float" type="button" data-role="open">${this.t("entry","智能录入")}</button>`:""}
|
|
4
|
-
<section class="sf-panel ${
|
|
5
|
-
<header class="sf-header">
|
|
13
|
+
<section class="sf-panel ${t?"is-open":""} ${this.options.mode==="inline"?"is-inline":"is-floating"}" aria-label="智能录入面板">
|
|
14
|
+
<header class="sf-header" data-role="close" >
|
|
6
15
|
<strong>${this.t("title","智能录入")}</strong>
|
|
7
|
-
<button class="sf-icon-btn" type="button"
|
|
16
|
+
<button class="sf-icon-btn" type="button" aria-label="${this.options.mode==="inline"?t?this.t("collapse","收起"):this.t("expand","展开"):this.t("close","关闭")}">${this.options.mode==="inline"?t?"∧":"∨":"x"}</button>
|
|
8
17
|
</header>
|
|
9
|
-
<div class="sf-body ${
|
|
18
|
+
<div class="sf-body ${t?"is-open":""}">
|
|
10
19
|
<label class="sf-toggle">
|
|
11
20
|
<span class="sf-toggle-main">
|
|
12
21
|
<input type="checkbox" data-role="local-priority-toggle" ${this.localPriorityEnabled?"checked":""} />
|
|
13
|
-
<span class="sf-toggle-title">${this.t("localPriorityTitle","
|
|
22
|
+
<span class="sf-toggle-title">${this.t("localPriorityTitle","本地优先")}</span>
|
|
23
|
+
<span class="sf-toggle-desc">${this.t("localPriorityDesc","开启后优先使用本地规则提取手机号、证件号等敏感信息")}</span>
|
|
14
24
|
</span>
|
|
15
|
-
<span class="sf-toggle-desc">${this.t("localPriorityDesc","开启后优先使用前端本地规则提取手机号、证件号等;关闭后直接走后端识别流程。")}</span>
|
|
16
25
|
</label>
|
|
17
26
|
<div class="sf-entry-grid">
|
|
18
27
|
<div class="sf-textarea-wrap">
|
|
19
|
-
<textarea class="sf-textarea" data-role="text" placeholder="${this.t("placeholder","粘贴文本,如:姓名:张三 手机号:13800000000")}">${
|
|
28
|
+
<textarea class="sf-textarea" data-role="text" placeholder="${this.t("placeholder","粘贴文本,如:姓名:张三 手机号:13800000000")}">${lo(this.inputText)}</textarea>
|
|
20
29
|
<div class="sf-textarea-actions">
|
|
21
30
|
<button class="sf-btn sf-btn-secondary" type="button" data-role="clear">${this.t("clear","清空")}</button>
|
|
22
31
|
<button class="sf-btn sf-btn-primary" type="button" data-role="recognize">${this.t("recognize","智能识别")}</button>
|
|
@@ -33,7 +42,7 @@
|
|
|
33
42
|
<circle cx="10" cy="10.5" r="1" fill="currentColor"/>
|
|
34
43
|
</svg>
|
|
35
44
|
</span>
|
|
36
|
-
<span class="sf-upload-hint">${this.t("uploadHint",`点击、拖拽、Ctrl + V 粘贴图片至此(最多 ${
|
|
45
|
+
<span class="sf-upload-hint">${this.t("uploadHint",`点击、拖拽、Ctrl + V 粘贴图片至此(最多 ${Xe} 张)`)}</span>
|
|
37
46
|
</span>
|
|
38
47
|
<span class="sf-upload-btn" data-role="file-label">图片识别</span>
|
|
39
48
|
</label>
|
|
@@ -43,23 +52,23 @@
|
|
|
43
52
|
</div>
|
|
44
53
|
</div>
|
|
45
54
|
</section>
|
|
46
|
-
`,this.bindEvents())}bindEvents(){var
|
|
55
|
+
`,this.bindEvents())}bindEvents(){var r,o,i,s,a,c,l;const t=this.query('[data-role="open"]');t==null||t.addEventListener("pointerdown",u=>this.startDrag(u)),t==null||t.addEventListener("click",()=>{this.suppressOpenClick||this.options.onOpen()}),(r=this.query(".sf-header"))==null||r.addEventListener("pointerdown",u=>this.startDrag(u)),(o=this.query('[data-role="close"]'))==null||o.addEventListener("click",()=>{if(this.options.mode==="inline"){this.isOpen?this.options.onClose():this.options.onOpen();return}this.options.onClose()}),(i=this.query('[data-role="file"]'))==null||i.addEventListener("change",u=>{const p=u.target;this.handleImages(Array.from(p.files||[]))});const n=this.query('[data-role="upload"]');n==null||n.addEventListener("pointerenter",()=>{this.isUploadHovering=!0}),n==null||n.addEventListener("pointerleave",()=>{this.isUploadHovering=!1,n.removeAttribute("data-dragover")}),n==null||n.addEventListener("dragenter",u=>{u.preventDefault(),this.isUploadHovering=!0,n.setAttribute("data-dragover","true")}),n==null||n.addEventListener("dragover",u=>{u.preventDefault(),n.setAttribute("data-dragover","true")}),n==null||n.addEventListener("dragleave",u=>{u.currentTarget.contains(u.relatedTarget)||(this.isUploadHovering=!1,n.removeAttribute("data-dragover"))}),n==null||n.addEventListener("drop",u=>{var p;u.preventDefault(),this.isUploadHovering=!1,n.removeAttribute("data-dragover"),this.handleImages(Array.from(((p=u.dataTransfer)==null?void 0:p.files)||[]))}),(s=this.query('[data-role="text"]'))==null||s.addEventListener("input",u=>{this.inputText=u.target.value}),(a=this.query('[data-role="local-priority-toggle"]'))==null||a.addEventListener("change",u=>{var p,y;this.localPriorityEnabled=u.target.checked,(y=(p=this.options).onLocalPriorityChange)==null||y.call(p,this.localPriorityEnabled)}),(c=this.query('[data-role="clear"]'))==null||c.addEventListener("click",()=>{this.clearFormState()}),(l=this.query('[data-role="recognize"]'))==null||l.addEventListener("click",()=>{const u=this.query('[data-role="text"]'),p=u==null?void 0:u.value.trim();if(this.inputText=(u==null?void 0:u.value)||this.inputText,!p){this.setError(this.t("emptyInput","请输入文本内容。"));return}this.options.onRecognize({text:p})})}clearFormState(){this.inputText="",this.resetSelectedFiles(),this.autoApplyState=null,this.render(!0),this.setStatus(this.t("empty","暂无识别结果"))}resetSelectedFiles(){var n;this.selectedFiles=[];const t=this.query('[data-role="file"]');t&&(t.value=""),this.isUploadHovering=!1,(n=this.query('[data-role="upload"]'))==null||n.removeAttribute("data-dragover")}async handleImages(t){const n=t.filter(i=>i.type.startsWith("image/"));if(!n.length){this.resetSelectedFiles(),this.setError(this.t("invalidImageError","请选择图片文件。"));return}if(n.length>Xe){this.resetSelectedFiles(),this.setError(this.t("maxFilesError",`最多上传 ${Xe} 张图片。`));return}if(n.find(i=>i.size>so)){this.resetSelectedFiles(),this.setError(this.t("maxSingleFileSizeError","单张图片不能超过 10MB。"));return}if(n.reduce((i,s)=>i+s.size,0)>ao){this.resetSelectedFiles(),this.setError(this.t("maxTotalFileSizeError","上传图片总大小不能超过 50MB。"));return}this.selectedFiles=n,this.setStatus(this.t("imageReady",`已选择 ${this.selectedFiles.length} 张图片,开始识别...`));try{await this.options.onRecognize({images:[...this.selectedFiles]}),this.resetSelectedFiles()}catch{}}startDrag(t){var r;if(this.options.mode!=="floating"||!this.host||t.button!==0||(r=t.target)!=null&&r.closest('[data-role="close"]'))return;const n=this.host.getBoundingClientRect();this.host.style.left=`${n.left}px`,this.host.style.top=`${n.top}px`,this.host.style.right="auto",this.host.style.bottom="auto",this.dragState={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,startLeft:n.left,startTop:n.top,moved:!1},t.preventDefault(),document.addEventListener("pointermove",this.handleDragMove),document.addEventListener("pointerup",this.handleDragEnd),document.addEventListener("pointercancel",this.handleDragEnd)}keepHostInViewport(){this.options.mode!=="floating"||!this.host||!this.host.style.left||!this.host.style.top||window.requestAnimationFrame(()=>{if(!this.host)return;const t=this.host.getBoundingClientRect(),n=Ee(t.left,8,Math.max(8,window.innerWidth-t.width-8)),r=Ee(t.top,8,Math.max(8,window.innerHeight-t.height-8));this.host.style.left=`${n}px`,this.host.style.top=`${r}px`})}query(t){var n;return((n=this.root)==null?void 0:n.querySelector(t))||null}t(t,n){var r;return((r=this.options.messages)==null?void 0:r[t])||n}}function lo(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]||t)}function Ee(e,t,n){return Math.min(Math.max(e,t),n)}function uo(e){var n;return Array.from(((n=e.clipboardData)==null?void 0:n.items)||[]).filter(r=>r.kind==="file"&&r.type.startsWith("image/")).map(r=>r.getAsFile()).filter(r=>!!r)}const fo=`
|
|
47
56
|
:host, .sf-panel { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
|
|
48
|
-
:host(.sf-sdk-host-floating), .sf-sdk-host-floating { position: fixed; top:
|
|
49
|
-
.sf-float { align-self: flex-end; border: 0; border-radius: 999px; padding:
|
|
50
|
-
.sf-panel { display: none; width: 100%; box-sizing: border-box; border: 1px solid #dbe3ef; border-radius: 16px; background: #fff; color: #
|
|
57
|
+
:host(.sf-sdk-host-floating), .sf-sdk-host-floating { position: fixed; top: 30px; right: 30px; z-index: 2147483647; display: flex; flex-direction: column; align-items: flex-end; gap: 12px; width: min(450px, calc(100vw - 32px)); pointer-events: none; }
|
|
58
|
+
.sf-float { font-size: 15px; align-self: flex-end; border: 0; border-radius: 999px; padding: 10px 30px; color: #fff; background: linear-gradient(to right, #FF7E49, #FFA34E); box-shadow: 0 10px 24px rgba(37,99,235,.3); cursor: move; user-select: none; touch-action: none; pointer-events: auto; }
|
|
59
|
+
.sf-panel { display: none; width: 100%; box-sizing: border-box; border: 1px solid #dbe3ef; border-radius: 16px; background: #fff; color: #FF7E49; box-shadow: 0 18px 48px rgba(15,23,42,.18); padding: 12px 16px; pointer-events: auto; }
|
|
51
60
|
.sf-panel.is-open { display: block; }
|
|
52
61
|
.sf-panel.is-inline { display: block; }
|
|
53
62
|
.sf-body { display: none; }
|
|
54
63
|
.sf-body.is-open { display: block; }
|
|
55
64
|
.sf-header, .sf-actions { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
|
56
65
|
.sf-header { cursor: move; user-select: none; touch-action: none; }
|
|
57
|
-
.sf-icon-btn {font-size: 16px; border: 0; background: transparent; cursor: pointer; color: #
|
|
66
|
+
.sf-icon-btn {font-size: 16px; border: 0; background: transparent; cursor: pointer; color: #FF7E49; font-weight: 900; }
|
|
58
67
|
.sf-tip, .sf-status, .sf-empty, small { color: #64748b; font-size: 12px; }
|
|
59
68
|
.sf-toggle { display: grid; gap: 4px; margin: 10px 0 12px; padding: 10px 12px; border: 1px solid #dbe3ef; border-radius: 10px; background: #f8fbff; }
|
|
60
69
|
.sf-toggle-main { display: flex; align-items: center; gap: 8px; color: #172033; font-size: 13px; font-weight: 600; }
|
|
61
70
|
.sf-toggle-main input { margin: 0; }
|
|
62
|
-
.sf-toggle-desc { color:
|
|
71
|
+
.sf-toggle-desc { color:rgb(119, 128, 141); font-size: 12px; line-height: 1.4; font-weight: 400; }
|
|
63
72
|
.sf-entry-grid { display: grid; grid-template-columns: minmax(0, 1fr) 200px; gap: 12px; align-items: stretch; margin: 10px 0 14px; }
|
|
64
73
|
.sf-textarea-wrap { position: relative; }
|
|
65
74
|
.sf-textarea { width: 100%; min-height: 140px; resize: vertical; border: 1px solid #cbd5e1; border-radius: 10px; padding: 10px 10px 56px; box-sizing: border-box; }
|
|
@@ -77,10 +86,10 @@
|
|
|
77
86
|
.sf-btn { border: 1px solid #d7e3f5; border-radius: 999px; background: #fff; color: #4b5563; padding: 8px 20px; cursor: pointer; font-size: 13px; font-weight: 600; transition: all .18s ease; }
|
|
78
87
|
.sf-btn:hover { transform: translateY(-1px); box-shadow: 0 8px 20px rgba(15, 23, 42, .08); }
|
|
79
88
|
.sf-btn-secondary { background: #fff; color: #6b7280; border-color: #e5e7eb; }
|
|
80
|
-
.sf-btn-primary { min-width: 100px; border-color: transparent; background: linear-gradient(
|
|
89
|
+
.sf-btn-primary { min-width: 100px; border-color: transparent; background: linear-gradient(to right, #FF7E49, #FFA34E); color: #fff; box-shadow: 0 12px 26px rgba(59, 114, 246, .32); }
|
|
81
90
|
.sf-btn:disabled { opacity: .55; cursor: not-allowed; }
|
|
82
91
|
.sf-panel.is-floating .sf-entry-grid { grid-template-columns: 1fr; gap: 10px; }
|
|
83
|
-
.sf-panel.is-floating .sf-textarea { min-height:
|
|
92
|
+
.sf-panel.is-floating .sf-textarea { min-height: 180px; }
|
|
84
93
|
.sf-panel.is-floating .sf-upload { height: 96px; padding-top: 10px; padding-bottom: 10px; }
|
|
85
94
|
.sf-panel.is-floating .sf-upload-illustration { gap: 6px; }
|
|
86
95
|
.sf-panel.is-floating .sf-upload-icon { width: 22px; height: 22px; }
|
|
@@ -89,4 +98,4 @@
|
|
|
89
98
|
[data-status="error"] { color: #dc2626; }
|
|
90
99
|
[data-status="warning"] { color: #d97706; }
|
|
91
100
|
[data-status="success"] { color: #16a34a; }
|
|
92
|
-
`,ht=.75;class de{constructor(e,t){c(this,"events",new _);c(this,"scanner");c(this,"ruleEngine",new J);c(this,"panel",null);c(this,"panels",[]);c(this,"panelStorageKeys",new Map);c(this,"registeredFields",[]);c(this,"adapters",[Y]);c(this,"scanResult",null);c(this,"autoApplyState",null);c(this,"formConfigVersion");c(this,"localPriorityEnabled",!1);c(this,"destroyed",!1);this.config=e,this.context=t,this.scanner=new ne(e.root||document),this.localPriorityEnabled=vt(),this.context.manager.add(this)}on(e,t){return this.events.on(e,t)}useAdapter(e){return this.assertAlive(),this.adapters.push(e),this}registerFields(e){this.assertAlive();const t=new Set;for(const s of e){const i=s.rowKey==null?s.fieldId:`${s.fieldId}:${s.rowKey}`;if(t.has(i))throw E("UNSUPPORTED_PAGE",`字段 ${i} 重复注册。`,"scan");t.add(i)}return this.registeredFields=e,this}unregisterFields(e){this.assertAlive(),this.registeredFields=e!=null&&e.length?this.registeredFields.filter(t=>!e.includes(t.fieldId)):[]}mount(e){this.assertAlive();const t=typeof e=="string"?document.querySelector(e):e;if(!t)throw E("UNSUPPORTED_PAGE","未找到智能录入挂载点。","ui");const s=pe("inline",xt(e,t)),i=he(s,!0);return this.createPanel("inline",s,i).mount(t),this}mountFloatingButton(){this.assertAlive();const e=pe("floating"),t=he(e,!1);return this.createPanel("floating",e,t).mount(document.body),this}createPanel(e,t,s){let i;return i=new dt({mode:e,initialOpen:s,messages:this.config.messages,localPriorityEnabled:this.localPriorityEnabled,onOpen:()=>this.open(i),onClose:()=>this.close(i),onRecognize:r=>(this.panel=i,this.recognize(r)),onLocalPriorityChange:r=>this.handleLocalPriorityChange(r,i)}),this.panels.push(i),this.panelStorageKeys.set(i,t),this.panel=i,i}handleLocalPriorityChange(e,t){this.localPriorityEnabled=e,wt(e);for(const s of this.panels)s!==t&&s.setLocalPriorityEnabled(e)}async open(e=this.panel){this.assertAlive(),e&&(this.context.manager.activate(this),this.panel=e,e.setOpen(!0),ge(this.panelStorageKeys.get(e),!0),await this.rescan())}close(e=this.panel){e&&(this.panel=e,e.setOpen(!1),ge(this.panelStorageKeys.get(e),!1))}async rescan(){var e;this.assertAlive();try{this.formConfigVersion=void 0;const t=this.registeredFields.length?this.registeredFields:void 0;if(this.scanResult=this.scanner.scan({registered:t,maxFields:this.config.maxFields}),!this.scanResult.fields.length)throw E("NO_FIELDS_FOUND","当前页面未找到可回填字段。","scan");return this.events.emit("scanCompleted",{scanToken:this.scanResult.scanToken,fieldCount:this.scanResult.fields.length}),(e=this.panel)==null||e.setStatus(`已扫描 ${this.scanResult.fields.length} 个字段。`),this.scanResult}catch(t){throw this.emitError(t,"scan"),t}}async recognize(e){var r,a,o;this.assertAlive();const t=this.scanResult||await this.rescan(),s=L("trace"),i=performance.now();this.events.emit("recognizing",{scanToken:t.scanToken,traceId:s}),(r=this.panel)==null||r.setBusy(!0,"识别中...");try{const d=t.fields.filter(y=>yt(y.localRuleMode,this.localPriorityEnabled)),l=t.fields.filter(y=>y.localRuleMode!=="only"),{text:u,usedOcr:m}=await this.context.client.resolveInputText({text:e.text,images:e.images,onStatusChange:y=>{var N,A,$;if(y==="image_uploading"){(N=this.panel)==null||N.setStatus("图片上传中...");return}if(y==="image_recognizing"){(A=this.panel)==null||A.setStatus("图片识别中...");return}($=this.panel)==null||$.setStatus("识别中...")}}),k=u?this.ruleEngine.recognize(u,d,t.scanToken):[];let w;if(!l.length)w=fe(t.scanToken,s,k,i,void 0,m);else try{const y=await this.context.client.recognize({scanToken:t.scanToken,formCode:this.config.formCode,configVersion:this.formConfigVersion,text:u,usedOcr:m,fields:l,onStatusChange:()=>{var A;(A=this.panel)==null||A.setStatus("识别中...")}});y.trace.durationMs=y.trace.durationMs||Math.round(performance.now()-i);const N=bt(k,y.suggestions.filter(A=>l.some($=>$.fieldId===A.fieldId)));w={...y,suggestions:N}}catch(y){if(!k.length)throw y;w=fe(t.scanToken,s,k,i,[m?"后端识别失败,已使用 OCR 文本触发本地识别继续回填。":"后端识别失败,已启用本地识别继续回填。"],m)}return this.autoApplyState=gt(w.scanToken,w.trace.traceId,w.suggestions,t,this.registeredFields),this.events.emit("recognized",w),(a=this.panel)==null||a.setAutoApplyState(this.autoApplyState),await this.applyAutoItems(this.autoApplyState),w}catch(d){throw this.emitError(d,"recognize"),d}finally{(o=this.panel)==null||o.setBusy(!1)}}async apply(e){var i;if(this.assertAlive(),!this.scanResult)throw E("SCAN_TOKEN_EXPIRED","请先扫描字段后再回填。","apply");this.events.emit("applying",{scanToken:e.scanToken,count:e.values.length});const s=await new z(this.scanResult.fields,this.registeredFields,this.adapters).apply(e);return this.events.emit("applied",s),(i=this.panel)==null||i.setApplyResult(s),s}async applyAutoItems(e){var o,d;if(!this.scanResult)throw E("SCAN_TOKEN_EXPIRED","请先扫描字段后再回填。","apply");const t=mt(e),s=e.items.filter(l=>ue(l)).map(l=>({fieldId:l.fieldId,value:l.value,source:l.source}));this.events.emit("applying",{scanToken:e.scanToken,count:s.length}),(o=this.panel)==null||o.setStatus("识别完成,正在自动回填...");const r=await new z(this.scanResult.fields,this.registeredFields,this.adapters).apply({scanToken:e.scanToken,values:s}),a={...r,skipped:[...t,...r.skipped],warnings:[...r.warnings||[],...t.length?["部分字段因置信度或风险策略被跳过。"]:[]]};return this.events.emit("applied",a),(d=this.panel)==null||d.setApplyResult(a),a}destroy(){if(!this.destroyed){this.destroyed=!0;for(const e of this.panels)e.destroy();this.panels.length=0,this.panelStorageKeys.clear(),this.panel=null,this.events.clear(),this.context.manager.remove(this)}}assertAlive(){if(this.destroyed)throw E("INSTANCE_DESTROYED","实例已销毁。","ui")}emitError(e,t){var i;const s=Ee(e,t);this.events.emit("error",s),(i=this.panel)==null||i.setError(s.message)}}function gt(n,e,t,s,i){return{scanToken:n,traceId:e,items:t.map(r=>{const a=s.fields.find(l=>l.fieldId===r.fieldId),o=i.find(l=>l.fieldId===r.fieldId),d=o!=null&&o.getValue?o.getValue():Et(a==null?void 0:a.element);return{applyItemId:`${r.fieldId}_${Math.random().toString(36).slice(2,8)}`,fieldId:r.fieldId,scanToken:n,groupId:r.groupId,label:r.label,value:r.value,currentValue:d,displayValue:r.displayValue||String(r.value??""),confidence:r.confidence,source:r.source,warnings:r.warnings,previousValue:d}})}}function ue(n){var e;return n.confidence>=ht&&!((e=n.warnings)!=null&&e.length)}function mt(n){return n.items.filter(e=>!ue(e)).map(e=>{var t,s;return{fieldId:e.fieldId,label:e.label,attemptedValue:e.value,reason:((t=e.warnings)==null?void 0:t.join(";"))||`置信度 ${Math.round(e.confidence*100)}% 低于自动回填阈值`,reasonCode:(s=e.warnings)!=null&&s.length?"AUTO_APPLY_WARNING":"LOW_CONFIDENCE"}})}function bt(n,e){const t=new Map;for(const s of e)t.set(s.fieldId,s);for(const s of n)t.has(s.fieldId)||t.set(s.fieldId,s);return[...t.values()]}function yt(n,e){return n==="only"?!0:n==="off"?!1:e}function fe(n,e,t,s,i,r=!1){return{scanToken:n,suggestions:t,warnings:i,trace:{traceId:e,usedOcr:r,usedAi:!1,durationMs:Math.round(performance.now()-s)}}}function Et(n){if(n)return n instanceof HTMLInputElement&&n.type==="checkbox"?n.checked:n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement?n.value:n.textContent}function pe(n,e="default"){const t=typeof location<"u"?location.pathname:"unknown-page",s=e.replace(/[^\w-]/g,"_")||"default";return`smart-fill:${n}:${t}:${s}:open`}function xt(n,e){if(typeof n=="string")return n;if(e.id)return`#${e.id}`;const t=typeof e.className=="string"?e.className.trim().split(/\s+/).filter(Boolean)[0]:"";return t?`.${t}`:e.tagName.toLowerCase()}function he(n,e){try{const t=window.localStorage.getItem(n);return t==null?e:t==="1"}catch{return e}}function ge(n,e){if(n)try{window.localStorage.setItem(n,e?"1":"0")}catch{}}function me(){return`smart-fill:${typeof location<"u"?location.pathname:"unknown-page"}:local-priority`}function vt(){try{return window.localStorage.getItem(me())==="1"}catch{return!1}}function wt(n){try{window.localStorage.setItem(me(),n?"1":"0")}catch{}}const f={status:"idle"},j=new _,be=new Ie;class ye{static async setup(e){if(typeof window>"u")return f.status="ready",St();if(f.status==="ready"&&f.apiKey===e.apiKey&&f.session)return f.session;if(f.status==="loading"&&f.apiKey===e.apiKey&&f.promise)return f.promise;f.apiKey&&f.apiKey!==e.apiKey&&be.destroyAll();const t=new xe(e);return f.status="loading",f.apiKey=e.apiKey,f.client=t,f.promise=t.createSession().then(s=>(console.log("SmartFill session created:",s),t.setAccessToken(s.apiKey),f.status="ready",f.session=s,j.emit("ready",{apiKey:e.apiKey}),s)).catch(s=>{throw f.status="error",s}),f.promise}static create(e={}){if(typeof window>"u")return T();if(f.status!=="ready"||!f.client)throw E("SDK_NOT_READY","请先 await SmartFill.setup({ apiKey })。","setup");return new de(e,{client:f.client,manager:be})}}c(ye,"on",j.on.bind(j));function St(){return{apiKey:"server-mock",accessToken:"server-mock",expiresIn:0,refreshBefore:0,features:{text:!1,image:!1,ai:!1,localRuleOnly:!0},rulesVersion:"server"}}function T(n){const e=()=>{};return{on:e,useAdapter:()=>T(),registerFields:()=>T(),unregisterFields:e,mount:()=>T(),mountFloatingButton:()=>T(),open:async()=>{},close:e,rescan:async()=>({scanToken:"server",fields:[]}),recognize:async()=>({scanToken:"server",suggestions:[],trace:{traceId:"server",usedOcr:!1,usedAi:!1,durationMs:0}}),apply:async()=>({applied:[],skipped:[]}),destroy:e}}const kt={name:"native",match:n=>n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement,getValue:n=>{const e=n.element;if(e instanceof HTMLInputElement&&e.type==="checkbox")return e.checked;if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)return e.value},setValue:(n,e)=>{const t=n.element;t instanceof HTMLInputElement&&t.type==="checkbox"?t.checked=!!e:(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&(t.value=String(e??"")),t==null||t.dispatchEvent(new Event("input",{bubbles:!0})),t==null||t.dispatchEvent(new Event("change",{bubbles:!0}))}};p.DEFAULT_BASE_URL=b,p.DomFiller=z,p.DomScanner=ne,p.ElementAdapter=Y,p.EventBus=_,p.LocalRuleEngine=J,p.NativeAdapter=kt,p.SmartFill=ye,p.SmartFillInstance=de,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})});
|
|
101
|
+
`,po=.75,ho=1800,ne=new Map;let re=0;const Ze="smart-fill:routechange",Vt="smart-fill:session-scan:";let Bt=!1;const Ut=new WeakMap;let go=0;function jt(){ne.clear(),nn(),re+=1}class Gt{constructor(t,n){d(this,"events",new Ke);d(this,"scanner");d(this,"ruleEngine",new Dt);d(this,"panel",null);d(this,"panels",[]);d(this,"panelStorageKeys",new Map);d(this,"registeredFields",[]);d(this,"adapters",[ze]);d(this,"scanResult",null);d(this,"autoApplyState",null);d(this,"formConfigVersion");d(this,"localPriorityEnabled",!1);d(this,"destroyed",!1);d(this,"scanCacheVersion",re);d(this,"floatingRouteSnapshot",null);d(this,"floatingLifecycleCleanup",null);d(this,"preScanTimer",null);this.config=t,this.context=n,this.scanner=new Nt(t.root||document),this.localPriorityEnabled=$o(),this.context.manager.add(this)}on(t,n){return this.events.on(t,n)}useAdapter(t){return this.assertAlive(),this.adapters.push(t),this}registerFields(t){this.assertAlive();const n=new Set;for(const r of t){const o=r.rowKey==null?r.fieldId:`${r.fieldId}:${r.rowKey}`;if(n.has(o))throw S("UNSUPPORTED_PAGE",`字段 ${o} 重复注册。`,"scan");n.add(o)}return this.registeredFields=t,this.scanResult=null,this.schedulePreScan(),this}unregisterFields(t){this.assertAlive(),this.registeredFields=t!=null&&t.length?this.registeredFields.filter(n=>!t.includes(n.fieldId)):[],this.scanResult=null,this.schedulePreScan()}mount(t){this.assertAlive();const n=typeof t=="string"?document.querySelector(t):t;if(!n)throw S("UNSUPPORTED_PAGE","未找到智能录入挂载点。","ui");const r=rn("inline",No(t,n)),o=on(r,!0);return this.createPanel("inline",r,o).mount(n),this.schedulePreScan(),this}mountFloatingButton(){this.assertAlive();const t=To(this.config),n=rn("floating"),r=on(n,!1);return this.createPanel("floating",n,r).mount(t),this.bindFloatingLifecycle(t),this.schedulePreScan(),this}createPanel(t,n,r){let o;return o=new co({mode:t,initialOpen:r,messages:this.config.messages,localPriorityEnabled:this.localPriorityEnabled,onOpen:()=>this.open(o),onClose:()=>this.close(o),onRecognize:i=>(this.panel=o,this.recognize(i)),onLocalPriorityChange:i=>this.handleLocalPriorityChange(i,o)}),this.panels.push(o),this.panelStorageKeys.set(o,n),this.panel=o,o}handleLocalPriorityChange(t,n){this.localPriorityEnabled=t,Ho(t);for(const r of this.panels)r!==n&&r.setLocalPriorityEnabled(t)}async open(t=this.panel){this.assertAlive(),this.syncScanCacheVersion(),t&&(this.context.manager.activate(this),this.panel=t,t.setOpen(!0),sn(this.panelStorageKeys.get(t),!0),this.scanResult||await this.rescan())}close(t=this.panel){t&&(this.panel=t,t.setOpen(!1),sn(this.panelStorageKeys.get(t),!1))}async rescan(){return this.assertAlive(),this.syncScanCacheVersion(),this.cancelPreScan(),this.runScan({dynamicOptions:!0,emitStatus:!0})}async preScan(){return this.assertAlive(),this.syncScanCacheVersion(),this.runScan({dynamicOptions:!1,emitStatus:!1})}async runScan(t){var n;try{this.formConfigVersion=void 0;const r=this.getCachedPageScanResult(t.dynamicOptions),o=this.registeredFields.length?this.registeredFields:void 0,i=o?this.scanner.scan({registered:o,maxFields:this.config.maxFields}):r??(t.dynamicOptions?await this.scanner.scanWithDynamicOptions({maxFields:this.config.maxFields}):this.scanner.scan({maxFields:this.config.maxFields}));if(this.scanResult=i,this.cachePageScanResult(i,t.dynamicOptions),!this.scanResult.fields.length)throw S("NO_FIELDS_FOUND","当前页面未找到可回填字段。","scan");return t.emitStatus&&(this.events.emit("scanCompleted",{scanToken:this.scanResult.scanToken,fieldCount:this.scanResult.fields.length}),(n=this.panel)==null||n.setStatus(`已扫描 ${this.scanResult.fields.length} 个字段。`)),this.scanResult}catch(r){throw t.emitStatus&&this.emitError(r,"scan"),r}}schedulePreScan(){this.destroyed||!this.panels.length||(this.preScanTimer!=null&&window.clearTimeout(this.preScanTimer),this.preScanTimer=window.setTimeout(()=>{this.preScanTimer=null,!(this.destroyed||this.scanResult)&&this.preScan().catch(()=>{})},ho))}cancelPreScan(){this.preScanTimer!=null&&(window.clearTimeout(this.preScanTimer),this.preScanTimer=null)}async recognize(t){var i,s,a,c,l,u;this.assertAlive(),this.syncScanCacheVersion(),(i=this.panel)==null||i.setBusy(!0,"扫描中..."),(s=this.panel)==null||s.setStatus("扫描中...");const n=await this.rescan(),r=ve("trace"),o=performance.now();this.events.emit("recognizing",{scanToken:n.scanToken,traceId:r}),(a=this.panel)==null||a.setBusy(!0,"识别中...");try{const p=n.fields.filter(m=>wo(m.localRuleMode,this.localPriorityEnabled)),y=n.fields.filter(m=>m.localRuleMode!=="only"),{text:M,usedOcr:ke}=await this.context.client.resolveInputText({text:t.text,images:t.images,onStatusChange:m=>{var Ae,N,Ce;if(m==="image_uploading"){(Ae=this.panel)==null||Ae.setStatus("图片上传中...");return}if(m==="image_recognizing"){(N=this.panel)==null||N.setStatus("图片识别中...");return}(Ce=this.panel)==null||Ce.setStatus("识别中...")}}),_e=M?this.ruleEngine.recognize(M,p,n.scanToken):[];let k;if(!y.length)k=Wt(n.scanToken,r,_e,o,void 0,ke);else try{const m=await this.context.client.recognize({scanToken:n.scanToken,formCode:this.config.formCode,configVersion:this.formConfigVersion,text:M,usedOcr:ke,fields:y,onStatusChange:()=>{var N;(N=this.panel)==null||N.setStatus("识别中...")}});m.trace.durationMs=m.trace.durationMs||Math.round(performance.now()-o);const Ae=vo(_e,m.suggestions.filter(N=>y.some(Ce=>Ce.fieldId===N.fieldId)));k={...m,suggestions:Ae}}catch(m){if(!_e.length)throw m;k=Wt(n.scanToken,r,_e,o,[ke?"后端识别失败,已使用 OCR 文本触发本地识别继续回填。":"后端识别失败,已启用本地识别继续回填。"],ke)}if(this.autoApplyState=bo(k.scanToken,k.trace.traceId,k.suggestions,n,this.registeredFields),this.events.emit("recognized",k),(c=this.panel)==null||c.setAutoApplyState(this.autoApplyState),this.config.apiEnable){const m=yo(k,this.autoApplyState,n);this.config.apiCallback&&await Promise.resolve(this.config.apiCallback(m)),(l=this.panel)==null||l.setStatus(`识别完成,已返回 ${m.fields.length} 个字段。`)}else await this.applyAutoItems(this.autoApplyState);return k}catch(p){throw this.clearScanStateOnTokenExpired(p),this.emitError(p,"recognize"),p}finally{(u=this.panel)==null||u.setBusy(!1)}}async apply(t){var o;if(this.assertAlive(),this.syncScanCacheVersion(),!this.scanResult)throw S("SCAN_TOKEN_EXPIRED","请先扫描字段后再回填。","apply");this.events.emit("applying",{scanToken:t.scanToken,count:t.values.length});const r=await new Be(this.scanResult.fields,this.registeredFields,this.adapters).apply(t);return this.events.emit("applied",r),(o=this.panel)==null||o.setApplyResult(r),r}async applyAutoItems(t){var a,c;if(!this.scanResult)throw S("SCAN_TOKEN_EXPIRED","请先扫描字段后再回填。","apply");const n=mo(t),r=t.items.filter(l=>Yt(l)).map(l=>({fieldId:l.fieldId,value:l.value,source:l.source}));this.events.emit("applying",{scanToken:t.scanToken,count:r.length}),(a=this.panel)==null||a.setStatus("识别完成,正在自动回填...");const i=await new Be(this.scanResult.fields,this.registeredFields,this.adapters).apply({scanToken:t.scanToken,values:r}),s={...i,skipped:[...n,...i.skipped],warnings:[...i.warnings||[],...n.length?["部分字段因置信度或风险策略被跳过。"]:[]]};return this.events.emit("applied",s),(c=this.panel)==null||c.setApplyResult(s),s}destroy(){if(!this.destroyed){this.destroyed=!0,this.cancelPreScan(),this.clearFloatingLifecycle();for(const t of this.panels)t.destroy();this.panels.length=0,this.panelStorageKeys.clear(),this.panel=null,this.events.clear(),this.context.manager.remove(this)}}assertAlive(){if(this.destroyed)throw S("INSTANCE_DESTROYED","实例已销毁。","ui")}emitError(t,n){var o;const r=Rt(t,n);this.events.emit("error",r),(o=this.panel)==null||o.setError(r.message)}getCachedPageScanResult(t){const n=this.getPageScanCacheKey();if(!n)return null;const r=ne.get(n);if(r&&(!t||r.dynamicOptionsReady)){const i=Eo(r.scanResult);if(!i)ne.delete(n);else return i}const o=this.getPersistedPageScanResult(t);return o?(this.cachePageScanResult(o.scanResult,o.dynamicOptionsReady),o.scanResult):null}cachePageScanResult(t,n){const r=this.getPageScanCacheKey();if(!r||!t.fields.length)return;const o=ne.get(r);o!=null&&o.dynamicOptionsReady&&!n||(ne.set(r,{scanResult:t,dynamicOptionsReady:(o==null?void 0:o.dynamicOptionsReady)||n}),this.persistPageScanResult(t,(o==null?void 0:o.dynamicOptionsReady)||n))}getPageScanCacheKey(){return this.registeredFields.length?null:_o(this.config)}getSessionPageScanCacheKey(){return this.registeredFields.length||!this.config.formCode?null:Ao(this.config)}clearScanStateOnTokenExpired(t){Rt(t,"recognize").code==="TOKEN_EXPIRED"&&(jt(),this.scanCacheVersion=re,this.scanResult=null,this.autoApplyState=null)}syncScanCacheVersion(){this.scanCacheVersion!==re&&(this.scanCacheVersion=re,this.scanResult=null,this.autoApplyState=null)}getPersistedPageScanResult(t){const n=this.getSessionPageScanCacheKey();if(!n)return null;const r=Po(n);if(!r||t&&!r.dynamicOptionsReady)return null;const o=this.scanner.scan({maxFields:this.config.maxFields}),i=xo(r,o);return i?{scanResult:i,dynamicOptionsReady:r.dynamicOptionsReady}:(nn(n),null)}persistPageScanResult(t,n){const r=this.getSessionPageScanCacheKey();!r||!t.fields.length||qo(r,{version:1,dynamicOptionsReady:n,fields:t.fields.map(({element:o,scanToken:i,...s})=>s)})}bindFloatingLifecycle(t){this.clearFloatingLifecycle(),this.floatingRouteSnapshot=Jt(),Co();const n=()=>{this.destroyed||Jt()!==this.floatingRouteSnapshot&&this.destroy()};window.addEventListener(Ze,n);const r=new MutationObserver(()=>{this.destroyed||t!==document.body&&!t.isConnected&&this.destroy()});r.observe(document.body,{childList:!0,subtree:!0}),this.floatingLifecycleCleanup=()=>{window.removeEventListener(Ze,n),r.disconnect(),this.floatingRouteSnapshot=null,this.floatingLifecycleCleanup=null}}clearFloatingLifecycle(){var t;(t=this.floatingLifecycleCleanup)==null||t.call(this)}}function yo(e,t,n){return{scanToken:e.scanToken,trace:e.trace,warnings:e.warnings,fields:t.items.map(r=>{const o=n.fields.find(i=>i.fieldId===r.fieldId);return{fieldId:r.fieldId,label:r.label,value:r.value,displayValue:r.displayValue||String(r.value??""),confidence:r.confidence,source:r.source,type:o==null?void 0:o.type,currentValue:r.currentValue,warnings:r.warnings}})}}function bo(e,t,n,r,o){return{scanToken:e,traceId:t,items:n.map(i=>{const s=r.fields.find(l=>l.fieldId===i.fieldId),a=o.find(l=>l.fieldId===i.fieldId),c=a!=null&&a.getValue?a.getValue():So(s==null?void 0:s.element);return{applyItemId:`${i.fieldId}_${Math.random().toString(36).slice(2,8)}`,fieldId:i.fieldId,scanToken:e,groupId:i.groupId,label:i.label,value:i.value,currentValue:c,displayValue:i.displayValue||String(i.value??""),confidence:i.confidence,source:i.source,warnings:i.warnings,previousValue:c}})}}function Yt(e){var t;return e.confidence>=po&&!((t=e.warnings)!=null&&t.length)}function mo(e){return e.items.filter(t=>!Yt(t)).map(t=>{var n,r;return{fieldId:t.fieldId,label:t.label,attemptedValue:t.value,reason:((n=t.warnings)==null?void 0:n.join(";"))||`置信度 ${Math.round(t.confidence*100)}% 低于自动回填阈值`,reasonCode:(r=t.warnings)!=null&&r.length?"AUTO_APPLY_WARNING":"LOW_CONFIDENCE"}})}function vo(e,t){const n=new Map;for(const r of t)n.set(r.fieldId,r);for(const r of e)n.has(r.fieldId)||n.set(r.fieldId,r);return[...n.values()]}function wo(e,t){return e==="only"?!0:e==="off"?!1:t}function Wt(e,t,n,r,o,i=!1){return{scanToken:e,suggestions:n,warnings:o,trace:{traceId:t,usedOcr:i,usedAi:!1,durationMs:Math.round(performance.now()-r)}}}function So(e){if(e)return e instanceof HTMLInputElement&&e.type==="checkbox"?e.checked:e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement?e.value:e.textContent}function Eo(e){const t=e.fields.map(n=>{if(n.source==="registered")return n;const r=ko(n);return r?{...n,element:r}:null});return t.some(n=>!n)?null:{...e,fields:t}}function xo(e,t){var s,a;const n=new Map(t.fields.map(c=>[c.fieldId,c])),r=[],o=new Set;for(const c of e.fields){const l=n.get(c.fieldId);if(!l)continue;o.add(c.fieldId);const u={...l,label:c.label||l.label,placeholder:c.placeholder??l.placeholder,name:c.name??l.name,id:c.id??l.id,section:c.section??l.section,options:(s=c.options)!=null&&s.length?c.options:l.options,required:c.required??l.required,readonly:c.readonly??l.readonly,disabled:c.disabled??l.disabled};u.fingerprint=te({...u,tagName:(a=u.element)==null?void 0:a.tagName.toLowerCase()}),r.push(u)}if(!r.length)return null;const i=t.fields.filter(c=>!o.has(c.fieldId));return{...t,fields:[...r,...i]}}function ko(e){var t;if((t=e.element)!=null&&t.isConnected)return e.element;try{return document.querySelector(`[data-smart-fill-id="${zo(e.fieldId)}"]`)}catch{return null}}function _o(e){const t=typeof location<"u"?`${location.origin}${location.pathname}${location.search}`:"unknown-page",n=Xt(e.root||document);return`smart-fill:${t}:${e.formCode||"default-form"}:${n}:${e.maxFields??200}:scan`}function Ao(e){const t=Xt(e.root||document);return`${Vt}${e.formCode||"default-form"}:${t}:${e.maxFields??200}`}function Xt(e){if(e===document)return"document";const t=Ut.get(e);if(t)return t;const n=e instanceof HTMLElement&&e.id?`el:${e.id}`:`root:${++go}`;return Ut.set(e,n),n}function Co(){if(Bt||typeof window>"u")return;Bt=!0;const e=()=>{window.dispatchEvent(new Event(Ze))};window.addEventListener("popstate",e),window.addEventListener("hashchange",e),Zt("pushState",e),Zt("replaceState",e)}function Zt(e,t){const n=window.history[e];window.history[e]=function(...o){const i=n.apply(this,o);return t(),i}}function Jt(){return typeof location>"u"?"unknown-route":`${location.pathname}${location.search}${location.hash}`}function To(e){const t=Lo(e.floatingContainer);if(t)return t;const n=Io(e.routeContainerSelector);return n||Mo()||document.body}function Lo(e){return e?e instanceof HTMLElement?e:Je(e):null}function Io(e){if(!e)return null;const t=Qt(),n=t?Je(e,t):null;return n||Je(e)}function Mo(){const e=Qt();if(!e)return null;const t=Ro(e);if(t)return t;const n=Fo(e);if(n)return n;const r=Oo(e);return r!==e?r:null}function Qt(){const e=["#app","#root","#__next","#nuxt","[data-reactroot]","[data-v-app]","[data-vue-app]","[data-app-root]","[data-router-root]"];for(const t of e){const n=document.querySelector(t);if(n&&xe(n))return n}return null}function Ro(e){const t=E(e),n=en(e).filter(o=>!Qe(o)).filter(o=>E(o)>=Math.max(t*.2,48e3)),r=n.filter(o=>Do(o));return r.length?r.sort((o,i)=>E(i)-E(o))[0]:n.length===1?n[0]:null}function Fo(e){const t=["[data-route-root]","[data-router-view]","[data-page-root]","[data-page-container]",".router-view",".route-view",".page-root",".page-container",".page",".layout-content",".app-main",".app-content","main",'[role="main"]'],n=tn(e),r=E(e);return t.flatMap(i=>Array.from(e.querySelectorAll(i))).filter(i=>xe(i)&&!Qe(i)).filter(i=>et(i,n)<=3).filter(i=>E(i)>=Math.max(r*.2,48e3)).sort((i,s)=>et(i,n)-et(s,n)||E(s)-E(i))[0]||null}function Oo(e){let t=e;for(;;){const n=en(t).filter(o=>!Qe(o));if(n.length!==1)return t;const[r]=n;if(E(r)<Math.max(E(t)*.25,48e3))return t;t=r}}function en(e){return Array.from(e.children).filter(t=>t instanceof HTMLElement).filter(t=>xe(t))}function Je(e,t=document){try{const n=t.querySelector(e);return n&&xe(n)?n:null}catch{return null}}function xe(e){const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||Number(t.opacity)===0)return!1;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}function Qe(e){const t=window.getComputedStyle(e);return t.position==="fixed"||t.position==="sticky"?!0:E(e)<24e3}function Do(e){if(e.tagName.toLowerCase()==="main"||e.getAttribute("role")==="main")return!0;const t=e.id||"",n=typeof e.className=="string"?e.className:"",r=`${t} ${n}`.toLowerCase();return/(page|layout|content|container|main|router|route|view)/.test(r)}function E(e){const t=e.getBoundingClientRect();return Math.max(0,t.width)*Math.max(0,t.height)}function tn(e){let t=0,n=e;for(;n&&n!==document.body;)t+=1,n=n.parentElement;return t}function et(e,t){return Math.max(0,tn(e)-t)}function Po(e){try{const t=window.sessionStorage.getItem(e);if(!t)return null;const n=JSON.parse(t);return(n==null?void 0:n.version)!==1||!Array.isArray(n.fields)?null:n}catch{return null}}function qo(e,t){try{window.sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function nn(e){try{if(e){window.sessionStorage.removeItem(e);return}const t=[];for(let n=0;n<window.sessionStorage.length;n+=1){const r=window.sessionStorage.key(n);r!=null&&r.startsWith(Vt)&&t.push(r)}for(const n of t)window.sessionStorage.removeItem(n)}catch{}}function rn(e,t="default"){const n=typeof location<"u"?location.pathname:"unknown-page",r=t.replace(/[^\w-]/g,"_")||"default";return`smart-fill:${e}:${n}:${r}:open`}function No(e,t){if(typeof e=="string")return e;if(t.id)return`#${t.id}`;const n=typeof t.className=="string"?t.className.trim().split(/\s+/).filter(Boolean)[0]:"";return n?`.${n}`:t.tagName.toLowerCase()}function on(e,t){try{const n=window.localStorage.getItem(e);return n==null?t:n==="1"}catch{return t}}function sn(e,t){if(e)try{window.localStorage.setItem(e,t?"1":"0")}catch{}}function an(){return`smart-fill:${typeof location<"u"?location.pathname:"unknown-page"}:local-priority`}function $o(){try{return window.localStorage.getItem(an())==="1"}catch{return!1}}function Ho(e){try{window.localStorage.setItem(an(),e?"1":"0")}catch{}}function zo(e){return typeof CSS<"u"&&CSS.escape?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}const h={status:"idle"},tt=new Ke,cn=new Lr;class ln{static async setup(t){if(typeof window>"u")return h.status="ready",Ko();if(h.status==="ready"&&h.apiKey===t.apiKey&&h.session)return h.session;if(h.status==="loading"&&h.apiKey===t.apiKey&&h.promise)return h.promise;h.apiKey&&h.apiKey!==t.apiKey&&(jt(),cn.destroyAll());const n=new xr(t);return h.status="loading",h.apiKey=t.apiKey,h.client=n,h.promise=n.createSession().then(r=>(console.log("SmartFill session created:",r),n.setAccessToken(r.apiKey),h.status="ready",h.session=r,tt.emit("ready",{apiKey:t.apiKey}),r)).catch(r=>{throw h.status="error",r}),h.promise}static create(t={}){if(typeof window>"u")return oe();if(h.status!=="ready"||!h.client)throw S("SDK_NOT_READY","请先 await SmartFill.setup({ apiKey })。","setup");return new Gt(t,{client:h.client,manager:cn})}}d(ln,"on",tt.on.bind(tt));function Ko(){return{apiKey:"server-mock",accessToken:"server-mock",expiresIn:0,refreshBefore:0,features:{text:!1,image:!1,ai:!1,localRuleOnly:!0},rulesVersion:"server"}}function oe(e){const t=()=>{};return{on:t,useAdapter:()=>oe(),registerFields:()=>oe(),unregisterFields:t,mount:()=>oe(),mountFloatingButton:()=>oe(),open:async()=>{},close:t,rescan:async()=>({scanToken:"server",fields:[]}),recognize:async()=>({scanToken:"server",suggestions:[],trace:{traceId:"server",usedOcr:!1,usedAi:!1,durationMs:0}}),apply:async()=>({applied:[],skipped:[]}),destroy:t}}g.DEFAULT_BASE_URL=It,g.DomFiller=Be,g.DomScanner=Nt,g.ElementAdapter=pr,g.EventBus=Ke,g.LocalRuleEngine=Dt,g.NativeAdapter=v,g.SmartFill=ln,g.SmartFillInstance=Gt,g.UiFrameworkAdapter=ze,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
export
|
|
1
|
+
/** @deprecated 请使用 UiFrameworkAdapter,保留 ElementAdapter 名称兼容旧接入 */
|
|
2
|
+
export { ElementAdapter, UiFrameworkAdapter } from './ui-framework';
|
|
3
3
|
//# sourceMappingURL=element.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element.d.ts","sourceRoot":"","sources":["../../../src/adapters/element.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"element.d.ts","sourceRoot":"","sources":["../../../src/adapters/element.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ui-framework.d.ts","sourceRoot":"","sources":["../../../src/adapters/ui-framework.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;AAIhD,eAAO,MAAM,kBAAkB,EAAE,gBAoDhC,CAAA;AAED,cAAc;AACd,eAAO,MAAM,cAAc,kBAAqB,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gateway-client.d.ts","sourceRoot":"","sources":["../../../src/client/gateway-client.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EACV,eAAe,EAEf,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,oBAAoB,EACrB,MAAM,UAAU,CAAC;AAmClB,KAAK,eAAe,GAAG,iBAAiB,GAAG,mBAAmB,GAAG,aAAa,CAAA;AAE9E,qBAAa,aAAa;IAMZ,OAAO,CAAC,QAAQ,CAAC,MAAM;IALnC,mCAAmC;IACnC,OAAO,CAAC,OAAO,CAAK;IACpB,iCAAiC;IACjC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAmB;gBAEd,MAAM,EAAE,oBAAoB;IAEzD,6CAA6C;IAC7C,cAAc,CAAC,KAAK,EAAE,MAAM;IAI5B;;;OAGG;IACG,aAAa,IAAI,OAAO,CAAC,eAAe,CAAC;IAiB/C,uCAAuC;IACjC,aAAa,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAU1E;;;;OAIG;IACG,gBAAgB,CAAC,OAAO,EAAE,IAAI,CAAC,gBAAgB,EAAE,MAAM,GAAG,QAAQ,CAAC,GAAG;QAC1E,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,CAAA;KACnD;;;;IAcD;;;;;;OAMG;IACG,SAAS,CAAC,OAAO,EAAE;QACvB,SAAS,EAAE,MAAM,CAAA;QACjB,IAAI,CAAC,EAAE,MAAM,CAAA;QACb,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,QAAQ,CAAC,EAAE,MAAM,CAAA;QACjB,aAAa,CAAC,EAAE,MAAM,CAAA;QACtB,MAAM,EAAE,eAAe,EAAE,CAAA;QACzB,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,CAAA;KACnD,GAAG,OAAO,CAAC,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"gateway-client.d.ts","sourceRoot":"","sources":["../../../src/client/gateway-client.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EACV,eAAe,EAEf,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,oBAAoB,EACrB,MAAM,UAAU,CAAC;AAmClB,KAAK,eAAe,GAAG,iBAAiB,GAAG,mBAAmB,GAAG,aAAa,CAAA;AAE9E,qBAAa,aAAa;IAMZ,OAAO,CAAC,QAAQ,CAAC,MAAM;IALnC,mCAAmC;IACnC,OAAO,CAAC,OAAO,CAAK;IACpB,iCAAiC;IACjC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAmB;gBAEd,MAAM,EAAE,oBAAoB;IAEzD,6CAA6C;IAC7C,cAAc,CAAC,KAAK,EAAE,MAAM;IAI5B;;;OAGG;IACG,aAAa,IAAI,OAAO,CAAC,eAAe,CAAC;IAiB/C,uCAAuC;IACjC,aAAa,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAU1E;;;;OAIG;IACG,gBAAgB,CAAC,OAAO,EAAE,IAAI,CAAC,gBAAgB,EAAE,MAAM,GAAG,QAAQ,CAAC,GAAG;QAC1E,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,CAAA;KACnD;;;;IAcD;;;;;;OAMG;IACG,SAAS,CAAC,OAAO,EAAE;QACvB,SAAS,EAAE,MAAM,CAAA;QACjB,IAAI,CAAC,EAAE,MAAM,CAAA;QACb,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,QAAQ,CAAC,EAAE,MAAM,CAAA;QACjB,aAAa,CAAC,EAAE,MAAM,CAAA;QACtB,MAAM,EAAE,eAAe,EAAE,CAAA;QACzB,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,CAAA;KACnD,GAAG,OAAO,CAAC,eAAe,CAAC;IAqC5B,2DAA2D;YAC7C,eAAe;IAqB7B,6DAA6D;YAC/C,OAAO;CA+BtB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaults.d.ts","sourceRoot":"","sources":["../../../src/config/defaults.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,
|
|
1
|
+
{"version":3,"file":"defaults.d.ts","sourceRoot":"","sources":["../../../src/config/defaults.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,+BAA+B,CAAA"}
|
|
@@ -8,6 +8,7 @@ type InternalContext = {
|
|
|
8
8
|
client: GatewayClient;
|
|
9
9
|
manager: InstanceManager<SmartFillInstance>;
|
|
10
10
|
};
|
|
11
|
+
export declare function clearSmartFillPageScanCache(): void;
|
|
11
12
|
export declare class SmartFillInstance {
|
|
12
13
|
private readonly config;
|
|
13
14
|
private readonly context;
|
|
@@ -37,6 +38,14 @@ export declare class SmartFillInstance {
|
|
|
37
38
|
private localPriorityEnabled;
|
|
38
39
|
/** 实例是否已 destroy,销毁后所有公开方法抛 INSTANCE_DESTROYED */
|
|
39
40
|
private destroyed;
|
|
41
|
+
/** 页面扫描缓存代际快照;变化时说明缓存已被全局清空 */
|
|
42
|
+
private scanCacheVersion;
|
|
43
|
+
/** 悬浮挂载时记录当前路由快照,路由切换后自动销毁实例 */
|
|
44
|
+
private floatingRouteSnapshot;
|
|
45
|
+
/** 悬浮挂载生命周期清理函数:移除路由监听和容器 observer */
|
|
46
|
+
private floatingLifecycleCleanup;
|
|
47
|
+
/** mount 后预扫描定时器 */
|
|
48
|
+
private preScanTimer;
|
|
40
49
|
constructor(config: SmartFillCreateConfig, context: InternalContext);
|
|
41
50
|
/** 订阅实例事件,返回取消订阅函数 */
|
|
42
51
|
on<K extends keyof SmartFillEventMap>(event: K, handler: (payload: SmartFillEventMap[K]) => void): () => void;
|
|
@@ -52,7 +61,7 @@ export declare class SmartFillInstance {
|
|
|
52
61
|
unregisterFields(fieldIds?: string[]): void;
|
|
53
62
|
/** 将面板嵌入指定容器(inline 模式) */
|
|
54
63
|
mount(target: string | HTMLElement): this;
|
|
55
|
-
/** 挂载右下角悬浮按钮 + 弹框(floating
|
|
64
|
+
/** 挂载右下角悬浮按钮 + 弹框(floating 模式),优先挂到当前子路由页面顶层容器 */
|
|
56
65
|
mountFloatingButton(): this;
|
|
57
66
|
/**
|
|
58
67
|
* 创建面板并登记到 panels。
|
|
@@ -71,6 +80,11 @@ export declare class SmartFillInstance {
|
|
|
71
80
|
* 扫描成功 emit scanCompleted,失败 emit error。
|
|
72
81
|
*/
|
|
73
82
|
rescan(): Promise<ScanResult>;
|
|
83
|
+
private preScan;
|
|
84
|
+
private runScan;
|
|
85
|
+
/** mount 成功后先静默扫描保存;registerFields 存在时仍只扫注册字段 */
|
|
86
|
+
private schedulePreScan;
|
|
87
|
+
private cancelPreScan;
|
|
74
88
|
/**
|
|
75
89
|
* 识别入口:文本/图片 → 本地规则 + 后端网关 → 合并 → 自动回填。
|
|
76
90
|
*
|
|
@@ -100,6 +114,16 @@ export declare class SmartFillInstance {
|
|
|
100
114
|
destroy(): void;
|
|
101
115
|
private assertAlive;
|
|
102
116
|
private emitError;
|
|
117
|
+
private getCachedPageScanResult;
|
|
118
|
+
private cachePageScanResult;
|
|
119
|
+
private getPageScanCacheKey;
|
|
120
|
+
private getSessionPageScanCacheKey;
|
|
121
|
+
private clearScanStateOnTokenExpired;
|
|
122
|
+
private syncScanCacheVersion;
|
|
123
|
+
private getPersistedPageScanResult;
|
|
124
|
+
private persistPageScanResult;
|
|
125
|
+
private bindFloatingLifecycle;
|
|
126
|
+
private clearFloatingLifecycle;
|
|
103
127
|
}
|
|
104
128
|
export {};
|
|
105
129
|
//# sourceMappingURL=smart-fill-instance.d.ts.map
|