@agentprismform/agent-plugin 0.0.0-stage → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -2
- package/README.zh-CN.md +12 -0
- package/bin/form-agent-mcp.cjs +17913 -0
- package/bin/form-agent.cjs +6300 -0
- package/bin/install-host.cjs +90 -0
- package/package.json +35 -4
- package/preview/assets/index-I07pgrbZ.js +62 -0
- package/preview/assets/skill-preview-DMg9HJ6e.js +153 -0
- package/preview/assets/skill-preview-Dq7qZ9HF.css +8 -0
- package/preview/modern-preview.css +1 -0
- package/preview/modern-preview.html +13 -0
- package/preview/modern-preview.iife.js +25 -0
- package/preview/skill-preview.html +14 -0
- package/skills/form-schema-author/SKILL.md +119 -0
- package/skills/form-schema-author/scripts/form-agent.cjs +29 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import{i as Mt,E as je,e as as,p as ls,v as z,C as cs,V as us,a as ds,b as fs,c as gs}from"./skill-preview-DMg9HJ6e.js";import{P as an,d as ln,f as cn,g as un,h as dn,T as fn,j as gn,k as pn,l as hn,m as mn,n as yn,o as kn,q as _n,r as bn,s as vn,t as In,u as Sn,w as An,x as En,y as Rn,z as wn,A as Tn,B as On,D as xn,F as Cn,G as Nn,H as Dn,I as $n,J as Mn}from"./skill-preview-DMg9HJ6e.js";function ps(t,e){const s=String(t).trim(),i=s.startsWith("return")?s:`return ${s}`,n=Object.keys(e),r=Object.values(e);return new Function(...n,i)(...r)}function hs(t,e={},s={}){const i=s.trust??"untrusted",n=s.dialect??(i==="untrusted"?"safe-v1":"legacy");if(i==="untrusted"&&n==="legacy")throw new je("UNTRUSTED_LEGACY","不可信路径禁止执行 legacy 表达式;请转换为 safe-v1 或标记为可信环境");if(n==="safe-v1"||i==="untrusted")return as(t,e,{maxLength:s.maxLength,maxDepth:s.maxDepth});try{return ps(t,e)}catch(r){throw r instanceof je?r:new je("LEGACY_EVAL_FAILED",(r==null?void 0:r.message)||"legacy 表达式执行失败")}}function ve(t){if(typeof t!="string"||!t.trim())return{kind:"legacy/untrusted",convertible:!1,reason:"空表达式"};if(Mt(t))return{kind:"safe-v1",convertible:!0,safeExpression:t};const e=ms(t);return e.ok?{kind:"legacy/convertible",convertible:!0,safeExpression:e.expression,reason:"可自动转换为 safe-v1"}:{kind:"legacy/untrusted",convertible:!1,reason:e.reason}}function ms(t){if(typeof t!="string")return{ok:!1,reason:"表达式不是字符串"};const e=t.trim();if(!e)return{ok:!1,reason:"空表达式"};if(/\b(Function|eval|globalThis|window|process|require|constructor|__proto__|prototype)\b|\=\>|new\s+|=>|\[[^\]]*\]|\.\s*[A-Za-z_$]/.test(e))return{ok:!1,reason:"包含不可转换的危险或成员访问语法"};const i=e.replace(/\s*===\s*/g," === ").replace(/\s*!==\s*/g," !== ").replace(/\s*==\s*/g," == ").replace(/\s*!=\s*/g," != ").replace(/\s*&&\s*/g," && ").replace(/\s*\|\|\s*/g," || ").replace(/\s+/g," ").trim();if(!Mt(i))return{ok:!1,reason:"无法解析为 safe-v1"};try{ls(i)}catch(n){return{ok:!1,reason:(n==null?void 0:n.message)||"解析失败"}}return{ok:!0,expression:i}}function Lt(t){const e=[];return!t||!Array.isArray(t.groups)||t.groups.forEach((s,i)=>{const n=s==null?void 0:s.items;Array.isArray(n)&&n.forEach((r,a)=>{const o=`groups[${i}].items[${a}]`;(r==null?void 0:r.defaultValueMode)!=="literal"&&typeof(r==null?void 0:r.defaultValue)=="string"&&ys(r.defaultValue)&&e.push({path:`${o}.defaultValue`,expression:r.defaultValue,classification:ve(r.defaultValue)}),typeof(r==null?void 0:r.showValueTemplate)=="string"&&e.push({path:`${o}.showValueTemplate`,expression:r.showValueTemplate,classification:ve(r.showValueTemplate)}),Array.isArray(r==null?void 0:r.rules)&&r.rules.forEach((l,c)=>{(l==null?void 0:l.type)==="logic"&&typeof l.logic=="string"&&e.push({path:`${o}.rules[${c}].logic`,expression:l.logic,classification:ve(l.logic)})}),Array.isArray(r==null?void 0:r.relations)&&r.relations.forEach((l,c)=>{typeof(l==null?void 0:l.logic)=="string"&&e.push({path:`${o}.relations[${c}].logic`,expression:l.logic,classification:ve(l.logic)})})})}),e}function ys(t){return/[!=<>]|&&|\|\||\?|:|return\s|function\s|\(/.test(t)}function Cr(t,e){try{const s=e.trim(),i=s.startsWith("return")?s:`return ${s}`;return new Function(...t,i)}catch{return()=>{}}}function Ee(t,e,s){try{return hs(e,t||{},{trust:(s==null?void 0:s.trust)??"trusted",dialect:(s==null?void 0:s.dialect)??"legacy",maxLength:s==null?void 0:s.maxLength,maxDepth:s==null?void 0:s.maxDepth})}catch{return}}function ks(t){return t==null?0:(typeof t!="string"&&(t=String(t)),t.replace(/[^\x00-\xff]/g,"01").length)}function le(t){try{return JSON.parse(JSON.stringify(t))}catch{return t}}function ut(t){return!(t==null||Array.isArray(t)&&t.length===0)}function Xe(t,e){switch(e){case"number":return Number(t)||0;case"string":return String(t??"");case"boolean":return t==="0"?!1:!!t;case"object":return t&&typeof t=="object"?t:{};case"array":return Array.isArray(t)?t:[];case"no":default:return t}}function Nr(t,e){function s(i,n){const r=[...n,{code:i.code,name:i.name}];if(i.code===e)return r;if(i.child)for(const a of i.child){const o=s(a,r);if(o)return o}return null}for(const i of t){const n=s(i,[]);if(n)return n}return[]}function re(t){return t==null||typeof t=="string"&&t===""||Array.isArray(t)&&t.length===0}function _s(t){return t.type==="collection"&&t.collectionType==="unique-within-items"}function bs(t){var e,s;return t.type==="logic"&&(((e=t.repeatableRelation)==null?void 0:e.type)==="not-equal"||((s=t.repeatableRelation)==null?void 0:s.type)==="unique-within-items")}function xe(t){if(typeof t=="number"&&Number.isNaN(t))return"number:NaN";try{return`${typeof t}:${JSON.stringify(t)}`}catch{return`${typeof t}:${String(t)}`}}function vs(t,e,s,i="submit",n={}){var o;if(t.type!=="list"||!Array.isArray(s))return[];const r=(t.rules??[]).filter(l=>_s(l)&&(i==="submit"||l.trigger!=="submit")),a=[];for(const l of r){const c=(o=t.subItems)==null?void 0:o.find(d=>d.key===l.fieldKey);if(!c)continue;const u=new Map;s.forEach((d,f)=>{if(!d||typeof d!="object"||Array.isArray(d))return;const g=d[l.fieldKey];if(re(g)||c.required===!1&&l.includeOptionalFields===!1||c.visible===!1&&l.includeHiddenFields!==!0)return;const y=xe(g),_=u.get(y)??[];_.push(f),u.set(y,_)});for(const d of u.values())if(!(d.length<2))for(const f of d)a.push({path:`${e}[${f}].${l.fieldKey}`,listKey:e,itemIndex:f,fieldKey:l.fieldKey,message:l.message})}for(const l of t.subItems??[]){const c=(l.rules??[]).filter(u=>bs(u)&&(i==="submit"||u.trigger!=="submit"));for(const u of c){const d=u.repeatableRelation;if(d.type==="unique-within-items"){const f=new Map;s.forEach((g,y)=>{if(!g||typeof g!="object"||Array.isArray(g))return;const _=g[d.fieldKey];if(re(_)||l.required===!1&&d.includeOptionalFields===!1||l.visible===!1&&d.includeHiddenFields!==!0)return;const m=xe(_);f.set(m,[...f.get(m)??[],y])});for(const g of f.values())if(!(g.length<2))for(const y of g)a.push({path:`${e}[${y}].${d.fieldKey}`,listKey:e,itemIndex:y,fieldKey:d.fieldKey,message:u.message});continue}s.forEach((f,g)=>{if(!f||typeof f!="object"||Array.isArray(f))return;const y=f[d.fieldKey];if(re(y))return;const _=d.right,m=_.scope==="form"?n[_.runtimeKey??_.businessFieldId]:f[_.fieldKey];re(m)||xe(y)===xe(m)&&a.push({path:`${e}[${g}].${d.fieldKey}`,listKey:e,itemIndex:g,fieldKey:d.fieldKey,message:u.message})})}}return[...new Map(a.map(l=>[`${l.path}:${l.message}`,l])).values()]}function Ce(t){var l,c;const{item:e,value:s,formValues:i={},expressionOptions:n}=t;let r="",a="";const o=re(s);if(e.required&&o&&(r=((c=(l=e.rules)==null?void 0:l.find(u=>u.type==="required"))==null?void 0:c.message)||"字段不能为空"),e.required===!1&&o)return{errMsg:r,popMsg:a,value:s};if(!r&&e.rules)for(const u of e.rules){if(u.type==="required")continue;const d=dt(u,s,i,n);if(d){r=d;break}}if(e.warningRules)for(const u of e.warningRules){const d=dt(u,s,i,n);if(d){a=d;break}}return{errMsg:r,popMsg:a,value:s}}function dt(t,e,s,i){switch(t.type){case"regex":{if(!t.regex)return null;const n=e!=null?String(e):"";return new RegExp(t.regex).test(n)?null:t.message||"格式不正确"}case"logic":{if(!t.logic)return null;try{const n={...s,value:e};return Ee(n,t.logic,i)?null:t.message||"校验不通过"}catch{return t.message||"校验异常"}}case"byteLength":return t.byteLength&&ks(e)>t.byteLength?t.message||`不得超过${t.byteLength}字节`:null;default:return null}}function Vt(t){const{sourceKey:e,value:s,formSnapshot:i,relations:n,expressionOptions:r}=t,a=[];for(const o of n){if(o.type==="remote")continue;const l=o.target;if(!l||l===e)continue;const c=i[l]||{value:void 0},u={...Is(i),value:s,[e]:s,target:c.value};if(o.effect==="value"&&o.logic)try{const d=Ee(u,o.logic,r);d!==void 0&&a.push({target:l,effect:"value",newValue:d})}catch{}if(o.effect==="visible"&&o.logic)try{const d=Ee(u,o.logic,r);typeof d=="boolean"&&a.push({target:l,effect:"visible",newValue:d})}catch{}if(o.effect==="disabled"&&o.logic)try{const d=Ee(u,o.logic,r);typeof d=="boolean"&&a.push({target:l,effect:"disabled",newValue:d})}catch{}}return a}function Is(t){const e={};for(const s of Object.keys(t)){const i=t[s];e[s]=i.value}return e}function Dr(t,e,s,i,n){const r=[],a=new Set;let o=[{key:t,value:e}];for(;o.length>0;){const l=[];for(const c of o){const u=s[c.key]||[],d=Vt({sourceKey:c.key,value:c.value,formSnapshot:i,relations:u,expressionOptions:n});for(const f of d){const g=`${f.target}.${f.effect}`;a.has(g)||(a.add(g),r.push(f),f.effect==="value"&&l.push({key:f.target,value:f.newValue}))}}o=l}return r}const Ss={get:()=>({}),set:()=>{},remove:()=>{}};class As{constructor(e,s,i){this._fields={},this._itemMap={},this._relationsMap={},this._listeners=new Map,this._isInit=!1,this._dirtyTracking=!1,this._queue=[],this._pendingAsyncTasks=[],this._isProcessing=!1,this._lastRelationTrace=null,this._lastValidateFails=[],this.schema=e,this._storage=s||Ss,this._expressionOptions=i??{trust:"trusted",dialect:"legacy"};for(const n of e.groups)for(const r of n.items)this._itemMap[r.key]=r,r.relations&&r.relations.length>0&&(this._relationsMap[r.key]=r.relations)}get fields(){return this._fields}get isInit(){return this._isInit}getItem(e){return this._itemMap[e]}getLastRelationTrace(){return this._lastRelationTrace?le(this._lastRelationTrace):null}getLastValidateFails(){return le(this._lastValidateFails)}clearDebugTraces(){this._lastRelationTrace=null,this._lastValidateFails=[]}explainField(e){const s=this._itemMap[e],i=this._fields[e];if(!s)return{key:e,exists:!1,asSource:[],asTarget:[]};const n=this._relationsMap[e]?le(this._relationsMap[e]):[],r=[];for(const[a,o]of Object.entries(this._relationsMap))for(const l of o)l.target===e&&r.push({sourceKey:a,relation:le(l)});return{key:e,exists:!0,type:s.type,label:s.label,value:i==null?void 0:i.value,visible:i==null?void 0:i.visible,disabled:i==null?void 0:i.disabled,errMsg:(i==null?void 0:i.errMsg)||"",warningMsg:(i==null?void 0:i.warningMsg)||"",required:s.required===!0,dataKey:e,rules:(s.rules||[]).map(a=>({type:a.type,message:a.message,trigger:a.trigger})),asSource:n,asTarget:r}}_evalLogic(e,s){return Ee(e,s,this._expressionOptions)}_recordValidateFail(e){const s={...e,at:Date.now()};this._lastValidateFails=this._lastValidateFails.filter(i=>i.key!==e.key),this._lastValidateFails.push(s)}async init(e){var d,f,g,y;const s=this.schema.storageKey;this._global={SL:{},selectors:{},admittanceData:[]};const i=["enumeration","payback","admittance"],n=(this.schema.apis||[]).filter(_=>i.includes(_.scene));let r={},a={},o=[];for(const _ of n)try{const m=await this._fetchAPI(_);_.scene==="enumeration"&&m?r={...r,...m}:_.scene==="payback"&&m?a={...a,...m}:_.scene==="admittance"&&m&&(o=Array.isArray(m)?m:[m])}catch{}this._admittanceData=o,this._enumData=r;const l=(this.schema.apis||[]).filter(_=>_.scene==="localData"),c={};for(const _ of l)try{const m=_.params||[];for(const S of m)(S.source==="inject"||S.key)&&(c[S.name]=this._storage.get(S.key||S.name))}catch{}this._global={SL:c,selectors:r,admittanceData:o};let u={};s&&(u=this._storage.get(s)||{});for(const _ of this.schema.groups)for(const m of _.items){const S=m.key;let h;if((e==null?void 0:e[S])!==void 0?h=e[S]:u[S]!==void 0?h=u[S]:a[S]!==void 0&&(h=a[S]),h===void 0&&m.defaultValue!==void 0&&(h=m.defaultValue,typeof h=="string"&&m.defaultValueMode!=="literal"))try{const A=h.startsWith("return ")?h:"return "+h,v=this._evalLogic({...this._global||{}},A);h=v!==void 0?v:h}catch{}if(h===void 0&&(h=this._resolveSelectDefault(m)),m.backfillable===!1&&u[S]!==void 0&&(h=m.defaultValue),m.initOptions&&m.initOptions.length>0&&h!=null&&h!==""&&typeof h=="object"&&!m.isJustValidate){const A=m.initOptions,v=((d=m.props)==null?void 0:d.isSingle)!==!1,k=(f=m.extra)==null?void 0:f.defaultMultiStepCodes,w=(g=m.extra)==null?void 0:g.defaultSelectCode;if(k||w)if(Array.isArray(h)&&k){let P=A,E=!0;for(const V of h){const j=P.findIndex(q=>q.code===V.code&&q.name===V.name);if(j===-1){E=!1;break}P=((y=P[j])==null?void 0:y.child)||[]}h=E?h:""}else Array.isArray(h)&&w&&!v?h=h.every(E=>A.some(V=>V.code===E.code&&V.name===E.name))?h:"":h=A.some(P=>P.code===h.code&&P.name===h.name)?h:""}let b="";if(h!=null&&h!==""&&m.showValueTemplate)try{const A={...this._buildFormValues(),value:h,global:this._global};b=String(this._evalLogic(A,m.showValueTemplate)||"")}catch{}if(!b&&h!=null&&h!==""&&(Array.isArray(h)?b=h.map(A=>A.name||A).join(""):b=String(h)),this._fields[S]={value:h!==void 0?h:"",showValue:b,visible:m.visible!==!1,disabled:m.disabled===!0,focused:!1,errMsg:"",warningMsg:"",valueType:m.valueType,defaultValue:m.defaultValue},m.extra){for(const A of Object.keys(m.extra))if(A.startsWith("init")&&typeof m.extra[A]=="string")try{const v=this._evalLogic({...this._buildFormValues(),global:this._global,value:h},m.extra[A]);v!==void 0&&(this._fields[S][A.replace(/^init/,"")]=v)}catch{}}}for(const _ of this.schema.groups)for(const m of _.items){const S=this._fields[m.key];if(!S)continue;if(m.initRelationsAtStart&&this._relationsMap[m.key]&&(S.visible||m.relationsWhenHidden)&&!S.errMsg){const b=S.value;ut(b)?this._trackAsync(this._applyRelations(m.key,b)):this._trackAsync(this._applyRelations(m.key,b,!0))}}for(;this._pendingAsyncTasks.length>0;){const _=this._pendingAsyncTasks.splice(0);await Promise.all(_)}this._isInit=!0,this._dirtyTracking=!0,await this._emit("afterInit",le(this._fields))}setControlData(e,s,i){var a;if(!this._fields[e]&&!this._itemMap[e])return;const n=["inputChange","inputFocus","pickShow"];if(i!=null&&i.eventType&&n.includes(i.eventType)&&!(((a=this._itemMap[e])==null?void 0:a.type)==="list"&&i.eventType==="inputChange")){this._emit("controlAction",{key:e,eventType:i.eventType,value:s});return}(i==null?void 0:i.eventType)==="searchChange"&&(i={...i,skipRelation:!0});const r=()=>{var c,u;const o=this._itemMap[e];if((i==null?void 0:i.changeType)==="clear"){const d=(o==null?void 0:o.extra)||{},f=d.clearBoth,g=d.clearValue;if(s=g!==void 0?g:(o==null?void 0:o.defaultValue)??"",Array.isArray(f))for(const y of f)this._fields[y]&&(this._dirtyTracking&&this._fields[y].value!==""&&(this._fields[y]._dirty=!0),this._fields[y].value="",this._fields[y].showValue="",this._fields[y].errMsg="")}if(this._dirtyTracking&&this._fields[e]&&this._fields[e].value!==s&&(this._fields[e]._dirty=!0),i!=null&&i.extraFields&&Object.assign(this._fields[e],i.extraFields),this._fields[e].value=s,this._computeShowValue(e,s,o),!(i!=null&&i.skipVerify)&&(o==null?void 0:o.type)==="list"&&((i==null?void 0:i.eventType)===void 0||i.eventType==="inputChange"||i.eventType==="inputBlur"||i.eventType==="confirm")&&this._validateListCollections(e,s,"blur",!0),!(i!=null&&i.skipVerify)){const d=(o==null?void 0:o.rules)&&o.rules.length>0,f=(o==null?void 0:o.warningRules)&&o.warningRules.length>0,g=o==null?void 0:o.required;if(d||f||g){const y=Ce({expressionOptions:this._expressionOptions,item:o,value:s,formValues:this._buildFormValues()}),_=(o==null?void 0:o.rules)&&o.rules.length>0&&o.rules.every(m=>m.trigger==="submit");_?this._fields[e]._pendingErrMsg=y.errMsg:(this._fields[e].errMsg=y.errMsg,this._fields[e].warningMsg=y.popMsg),y.errMsg||y.popMsg?(this._recordValidateFail({key:e,errMsg:y.errMsg,popMsg:y.popMsg,value:s,rules:((o==null?void 0:o.rules)||[]).filter(m=>!_||m.trigger==="submit").map(m=>({type:m.type,message:m.message,trigger:m.trigger}))}),this._emit("checkFail",{key:e,errMsg:y.errMsg,popMsg:y.popMsg,value:s,rules:((o==null?void 0:o.rules)||[]).map(m=>({type:m.type,message:m.message,trigger:m.trigger}))})):this._lastValidateFails=this._lastValidateFails.filter(m=>m.key!==e)}}this._persistField(e),!(i!=null&&i.skipRelation)&&(this._fields[e].visible||(o==null?void 0:o.relationsWhenHidden))&&this._trackAsync(this._applyRelations(e,s)),this._emit("afterChange",{key:e,value:s}),(o==null?void 0:o.type)==="task"&&!(i!=null&&i.skipJump)&&this._emit("controlJump",{key:e,value:s,taskType:(c=o.props)==null?void 0:c.taskType,taskCategory:(u=o.props)==null?void 0:u.taskCategory,props:o.props})};this._queue.push(r),this._isProcessing||this._drainQueue()}validateAll(){let e=!1;for(const s of Object.keys(this._fields)){const i=this._fields[s],n=this._itemMap[s];if(!n||!i.visible||n.type==="agreement"||!n.label)continue;i._pendingErrMsg&&(i.errMsg=i._pendingErrMsg,delete i._pendingErrMsg);const r=Ce({expressionOptions:this._expressionOptions,item:n,value:i.value,formValues:this._buildFormValues()});r.errMsg?(i.errMsg=r.errMsg,e=!0):i.errMsg="",i.warningMsg=r.popMsg,(r.errMsg||r.popMsg)&&this._emit("checkFail",{key:s,errMsg:r.errMsg,popMsg:r.popMsg,value:i.value}),n.type==="list"&&this._validateListCollections(s,i.value,"submit",!0)&&(e=!0)}return this._emit("afterChange",{validateAll:!0,hasError:e}),!e}getControlData(e){return this._fields[e]?le(this._fields[e]):void 0}collectFormData(e){const s={},i=[];for(const n of Object.keys(this._fields)){const r=this._fields[n],a=this._itemMap[n];if(a){if(!r.visible){const o=a.collectWhenHidden?r.value:a.defaultValue;if(ut(o)&&(s[n]=o),!s[n]||Array.isArray(s[n])&&!s[n].length){delete s[n];continue}}r.visible&&i.push(n)}}for(const n of i)(()=>{const a=this._fields[n],o=this._itemMap[n];if(o){if(!(e!=null&&e.skipVerify)&&o.rules&&o.rules.length>0){const l=Ce({expressionOptions:this._expressionOptions,item:o,value:a.value,formValues:this._buildFormValues()});a.errMsg=l.errMsg,a.warningMsg=l.popMsg}!(e!=null&&e.skipVerify)&&o.type==="list"&&this._validateListCollections(n,a.value,"submit",!0)}})();for(const n of i){const r=this._fields[n],a=this._itemMap[n];if(a&&a.submittable!==!1){if(!(e!=null&&e.skipVerify)){if(r._pendingErrMsg&&(r.errMsg=r._pendingErrMsg,delete r._pendingErrMsg),r.errMsg)throw new Error(`字段校验失败: ${n}, 错误信息: ${r.errMsg}`);const o=r.collectionErrors,l=o&&Object.entries(o)[0];if(l)throw new Error(`字段校验失败: ${l[0]}, 错误信息: ${l[1]}`)}s[n]=a.emptyValuePolicy==="preserve"&&re(r.value)?r.value:Xe(r.value,a.valueType)}}return this._emit("fetchFormFields",s),s}async collectFormDataAsync(e){var i;const s={};for(const n of Object.keys(this._fields)){const r=this._fields[n],a=this._itemMap[n];if(a&&!(!r.visible&&!a.collectWhenHidden)&&a.submittable!==!1){if(!(e!=null&&e.skipVerify)){if(r._pendingErrMsg)throw r.errMsg=r._pendingErrMsg,delete r._pendingErrMsg,new Error(`字段校验失败: ${n}, ${r.errMsg}`);const o=Ce({expressionOptions:this._expressionOptions,item:a,value:r.value,formValues:this._buildFormValues()});if(o.errMsg)throw r.errMsg=o.errMsg,new Error(`字段校验失败: ${n}, ${o.errMsg}`);if(a.type==="list"&&this._validateListCollections(n,r.value,"submit",!0)){const l=r.collectionErrors,c=Object.entries(l)[0];throw new Error(`字段校验失败: ${c[0]}, ${c[1]}`)}if(a.serverValidate&&(a.required!==!1||!re(r.value)))try{const l=(this.schema.apis||[]).find(c=>c.id===a.serverValidate);if(l){const c=await this._fetchAPI(l,{key:n,value:r.value});if(c&&c.code!==0)throw r.errMsg=c.msg||"服务端校验不通过",new Error(`字段校验失败: ${n}, ${r.errMsg}`)}}catch(l){if((i=l.message)!=null&&i.includes("字段校验失败"))throw l}}s[n]=a.emptyValuePolicy==="preserve"&&re(r.value)?r.value:Xe(r.value,a.valueType)}}return this._emit("fetchFormFields",s),s}async submitForm(e){let s=await this.collectFormDataAsync(e);const i=await this._emitAsync("beforeSubmit",s);i!==void 0&&(s=i);let n,r;try{const a=(this.schema.apis||[]).find(o=>o.id===this.schema.submitApi);a&&(n=await this._fetchAPI(a,{submitData:s}))}catch(a){r=a}if(await this._emitAsync("afterSubmit",{response:n,err:r}),e!=null&&e.isClearStore&&this.clearStore(),r)throw r;return n}clearStore(){this.schema.storageKey&&this._storage.remove(this.schema.storageKey)}on(e,s){const i=this._listeners.get(e)||[];i.push(s),this._listeners.set(e,i)}off(e,s){const i=this._listeners.get(e)||[];this._listeners.set(e,i.filter(n=>n!==s))}destroy(){this._listeners.clear(),this._fields={},this._itemMap={},this._relationsMap={}}async fetchApi(e,s){let i;return typeof e=="string"?i=(this.schema.apis||[]).find(n=>n.id===e):i=e,i?this._fetchAPI(i,s):this._emitAsync("fetchAPI",{id:typeof e=="string"?e:e.id,scene:"other",extraParams:s||{},injects:{...this._buildFormValues(),global:this._global,...s}})}flush(){for(;this._queue.length>0;){const e=this._queue.shift();if(e)try{e()}catch{}}this._isProcessing=!1}async flushAsync(){for(this.flush();this._pendingAsyncTasks.length>0;){const e=this._pendingAsyncTasks.splice(0);await Promise.all(e)}}collectDirtyData(e){const s=[];for(const i of e){const n=i.item_key,r=this._fields[n];if(!r||!r._dirty||!r.visible)continue;const a=this._formatInterruptAnswer(n,r.value);if(a.answer===i.answer)continue;const o={...i,answer:a.answer,answered:!0};(i.answer_items!==void 0||a.answerItems!==void 0)&&(o.answer_items=a.answerItems||i.answer_items),(i.answer_extra_json!==void 0||a.extraJson!==void 0)&&(o.answer_extra_json=a.extraJson||i.answer_extra_json),s.push(o)}return s}resetDirty(e){if(e)this._fields[e]&&delete this._fields[e]._dirty;else for(const s of Object.keys(this._fields))delete this._fields[s]._dirty}_trackAsync(e){this._pendingAsyncTasks.push(e),e.finally(()=>{const s=this._pendingAsyncTasks.indexOf(e);s>=0&&this._pendingAsyncTasks.splice(s,1)})}_drainQueue(){if(!this._isProcessing){for(this._isProcessing=!0;this._queue.length>0;){const e=this._queue.shift();if(e)try{e()}catch{}}this._isProcessing=!1}}_computeShowValue(e,s,i){var r,a,o;const n=i||this._itemMap[e];if(n!=null&&n.showValueTemplate&&s!=null&&s!=="")try{const l={...this._buildFormValues(),value:s,global:this._global};this._fields[e].showValue=String(this._evalLogic(l,n.showValueTemplate)||"")}catch{}else Array.isArray(s)&&s.length>0?(this._fields[e].showValue=s.map(l=>l.name||l).join(""),(r=s[0])!=null&&r.adcode&&(this._fields[e].province=s[0].name,this._fields[e].province_code=s[0].adcode),(a=s[1])!=null&&a.adcode&&(this._fields[e].city=s[1].name,this._fields[e].city_code=s[1].adcode),(o=s[2])!=null&&o.adcode&&(this._fields[e].country=s[2].name,this._fields[e].country_code=s[2].adcode),this._computeExtraJson(e)):s!=null&&s!==""?typeof s=="object"&&s.name?this._fields[e].showValue=s.name:this._fields[e].showValue=String(s):this._fields[e].showValue=""}_computeExtraJson(e){const s=this._fields[e];s&&(s.extraJson=JSON.stringify({province_code:s.province_code||"",province_name:s.province||"",city_code:s.city_code||"",city_name:s.city||"",district_code:s.country_code||"",district_name:s.country||"",rd_code:"",rd_name:"",location:"",town_code:"",town_name:""}))}async _applyRelations(e,s,i=!1){var y,_,m,S;const n=(y=this._relationsMap[e])==null?void 0:y.filter(h=>!i||h.type==="local"&&(h.effect==="visible"||h.effect==="disabled"));if(!n||n.length===0)return;const r=new Map,a=n.filter(h=>{let b=!0;if(!h.when)b=!0;else if(typeof h.when=="boolean")b=h.when;else if(typeof h.when=="object"&&"logic"in h.when)try{b=!!this._evalLogic({...this._buildFormValues(),value:s},h.when.logic)}catch{b=!1}return r.set(h,b),b}),o=a.filter(h=>h.type==="local"),l=a.filter(h=>h.type==="remote");let c={};for(const h of l)if(h.api)try{const b=(this.schema.apis||[]).find(A=>A.id===h.api);if(b){const A=await this._fetchAPI(b,{sourceKey:e,value:s});A&&(c={...c,...A})}}catch{}const u=this._buildSnapshot();for(const h of Object.keys(c))u[h]&&(u[h].value=c[h]);const d=Vt({sourceKey:e,value:s,formSnapshot:u,relations:o}),f=[];for(const h of l){const b=h.target;if(!b||!this._fields[b])continue;const A=this._fields[b];switch(h.effect){case"value":{const v=A.value,k=(_=u[b])==null?void 0:_.value;k!==void 0&&k!==v&&(this._dirtyTracking&&(A._dirty=!0),A.value=k,this._computeShowValue(b,k),this._persistField(b),this._emit("afterChange",{key:b,value:k}),f.push({target:b,effect:"value",type:"remote",oldValue:v,newValue:k,logic:h.logic}));break}case"visible":if(typeof((m=u[b])==null?void 0:m.visible)=="boolean"){const v=A.visible,k=u[b].visible;A.visible=k,v!==k&&f.push({target:b,effect:"visible",type:"remote",oldValue:v,newValue:k,logic:h.logic})}break;case"disabled":if(typeof((S=u[b])==null?void 0:S.disabled)=="boolean"){const v=A.disabled,k=u[b].disabled;A.disabled=k,v!==k&&f.push({target:b,effect:"disabled",type:"remote",oldValue:v,newValue:k,logic:h.logic})}break}}for(const h of d){const b=this._fields[h.target];if(!b)continue;const A=h.effect==="value"?b.value:h.effect==="visible"?b.visible:b.disabled;switch(h.effect){case"value":this._dirtyTracking&&(b._dirty=!0),b.value=h.newValue,this._computeShowValue(h.target,h.newValue),this._persistField(h.target),this._emit("afterChange",{key:h.target,value:h.newValue});break;case"visible":b.visible=h.newValue;break;case"disabled":b.disabled=h.newValue;break}if(A!==h.newValue){const v=o.find(k=>k.target===h.target&&k.effect===h.effect);f.push({target:h.target,effect:h.effect,type:"local",oldValue:A,newValue:h.newValue,logic:v==null?void 0:v.logic})}}const g={sourceKey:e,sourceValue:s,at:Date.now(),evaluated:n.map(h=>({target:h.target,effect:h.effect,type:h.type,whenActive:r.get(h)!==!1,logic:h.logic})),applied:f};this._lastRelationTrace=g,this._emit("relationTrace",le(g))}_persistField(e){var n;const s=this._itemMap[e];if(!s||s.persistable===!1||!this.schema.storageKey)return;const i=this._storage.get(this.schema.storageKey)||{};i[e]=(n=this._fields[e])==null?void 0:n.value,this._storage.set(this.schema.storageKey,i)}_buildSnapshot(){const e={};for(const s of Object.keys(this._fields)){const i=this._fields[s];e[s]={value:i.value,visible:i.visible,disabled:i.disabled}}return e}_buildFormValues(){const e={};for(const s of Object.keys(this._fields))e[s]=this._fields[s].value;return e}_buildFormValuesWithBusinessFields(){var s,i;const e=this._buildFormValues();for(const n of Object.keys(this._fields)){const r=(i=(s=this._itemMap[n])==null?void 0:s.extra)==null?void 0:i.businessField;typeof r=="string"&&!(r in e)&&(e[r]=this._fields[n].value)}return e}_validateListCollections(e,s,i,n){const r=this._itemMap[e],a=this._fields[e];if(!r||!a||r.type!=="list")return!1;const o=vs(r,e,s,i,this._buildFormValuesWithBusinessFields()),l={};for(const c of o)l[c.path]=c.message,n&&this._emit("checkFail",{key:c.path,errMsg:c.message,popMsg:"",value:s});return Object.keys(l).length>0?a.collectionErrors=l:delete a.collectionErrors,o.length>0}_formatInterruptAnswer(e,s){var a,o,l,c,u,d,f;const i=this._itemMap[e],n=(i==null?void 0:i.type)||"input",r={answer:""};if(/^address/.test(n)&&Array.isArray(s)&&s.length>0){const g=s.map(_=>_.name||"").filter(Boolean);r.answer=g.join("");const y={province_code:((a=s[0])==null?void 0:a.adcode)||"",province_name:((o=s[0])==null?void 0:o.name)||"",city_code:((l=s[1])==null?void 0:l.adcode)||"",city_name:((c=s[1])==null?void 0:c.name)||"",district_code:((u=s[2])==null?void 0:u.adcode)||"",district_name:((d=s[2])==null?void 0:d.name)||"",rd_code:"",rd_name:"",location:"",town_code:"",town_name:""};return r.extraJson=JSON.stringify(y),r}return(n==="select"||n==="cascader"||n==="search")&&s!=null&&typeof s=="object"&&!Array.isArray(s)&&s.code!==void 0?(r.answer=`${s.code}: ${s.name||""}`,r.answerItems=[{code:String(s.code),name:s.name||""}],r):(n==="select"||n==="cascader")&&Array.isArray(s)&&s.length>0&&((f=s[0])==null?void 0:f.code)!==void 0?(r.answer=s.map(g=>`${g.code}: ${g.name||""}`).join(", "),r.answerItems=s.map(g=>({code:String(g.code),name:g.name||""})),r):(s!=null&&s!==""&&(typeof s=="object"&&s.name?r.answer=String(s.name):r.answer=String(s)),r)}_resolveSelectDefault(e){var i,n;const s=e.extra||{};return s.defaultSelectCode!==void 0||((i=e.props)==null?void 0:i.defaultSelectCode)!==void 0?this._normalSelectDefault(e):s.defaultMultiStepCodes!==void 0||((n=e.props)==null?void 0:n.defaultMultiStepCodes)!==void 0?this._multiStepSelectDefault(e):e.initOptions&&e.initOptions.length>0?[]:e.defaultValue}_normalSelectDefault(e){var a,o,l;const s=String(((a=e.extra)==null?void 0:a.defaultSelectCode)??((o=e.props)==null?void 0:o.defaultSelectCode)??""),i=s.trim().split(","),n=e.initOptions||[];return((l=e.props)==null?void 0:l.isSingle)!==!1?n.find(c=>c.code===s)||null:n.filter(c=>i.includes(String(c.code)))}_multiStepSelectDefault(e){var o,l;const i=String(((o=e.extra)==null?void 0:o.defaultMultiStepCodes)??((l=e.props)==null?void 0:l.defaultMultiStepCodes)??"").trim().split(",");if(i.length<2)return[];const r=(e.initOptions||[]).find(c=>c.code===i[0]);if(!r||!Array.isArray(r.child))return[];const a=r.child.find(c=>c.code===i[1]);return a?[{code:r.code,name:r.name},{code:a.code,name:a.name}]:[]}async _fetchAPI(e,s){const i={...this._buildFormValues(),global:this._global,...s};let n={};if(e.additionParams)try{const l=this._evalLogic(i,e.additionParams);l&&typeof l=="object"&&(n=l)}catch{}if(e.params&&e.params.length>0)for(const l of e.params){if(n[l.name]!==void 0)continue;const c=await this._emitAsync("addApiParam",{api:e,paramName:l.name,defaultValue:l.default,injects:i});c!==void 0?n[l.name]=c:l.default!==void 0&&(n[l.name]=l.default)}let r,a;try{r=await this._emitAsync("fetchAPI",{id:e.id,scene:e.scene,api:e,extraParams:n,injects:i})}catch(l){a=l}if(a||r===void 0){if(e.failback)try{return this._evalLogic(i,e.failback)}catch{}if(a)throw a;return}let o=r;if(e.interptor)try{const l=this._evalLogic({...i,res:r},e.interptor);l!==void 0&&(o=l)}catch{}if(e.extraLogic)try{this._evalLogic({...i,response:o},e.extraLogic)}catch{}return o}_emit(e,...s){const i=this._listeners.get(e)||[];for(const n of i)try{n(...s)}catch{}}async _emitAsync(e,...s){const i=this._listeners.get(e)||[];let n;for(const r of i)try{const a=await r(...s);a!==void 0&&(n=a)}catch{}return n}}function $r(t,e){var o;const s=(e==null?void 0:e.nodes)??t.nodes,i=s?ws(s):{},n={};if(e!=null&&e.datasets)for(const l of e.datasets)l.id&&(n[l.id]=l);const r=t.components.filter(l=>l!=null).map(l=>{var g,y;const c=l.sourcePath.replace(/^form\./,""),u=i[c]||i[l.id||""]||{},d={...e==null?void 0:e.componentTypeHints,...u.typeHint?{[c]:u.typeHint}:{}},f=((g=e==null?void 0:e.taskTypeHints)==null?void 0:g[c])||((y=e==null?void 0:e.taskTypeHints)==null?void 0:y[l.id||""]);return Es(l,d,u.label,f,u.description,u.nodeProps)});let a;if(s){const l=Ts(s,r.length);l.length>0?a=l.map(c=>({key:c.key,title:c.title||void 0,description:c.description,items:r.slice(c.startIndex,c.endIndex+1)})):a=[{key:"default",title:e==null?void 0:e.groupTitle,items:r}]}else a=[{key:"default",title:e==null?void 0:e.groupTitle,items:r}];return{version:"2.0",storageKey:e==null?void 0:e.storageKey,groups:a,apis:(t.apis||[]).map(l=>Ms(l,n[l.id])),submitApi:(o=(t.apis||[]).find(l=>l.scene==="submit"))==null?void 0:o.id}}function Es(t,e,s,i,n,r){var u,d,f,g,y,_;const a=t.sourcePath.replace(/^form\./,""),o=(e==null?void 0:e[a])||(e==null?void 0:e[t.id||""])||Os(t),l=i?"task":o,c={key:a,type:l,label:s||"",description:n||((u=t.extra)==null?void 0:u.description),labelPosition:"top",visible:t.defaultShow!==!1,disabled:t.defaultDisable===!0,defaultValue:t.defaultValue,valueType:t.valueType,showValueTemplate:t.showValueLogic,required:t.required===!0,placeholder:(d=t.extra)==null?void 0:d.placeholder,help:(f=t.extra)==null?void 0:f.help,rules:xs(t),warningRules:Cs(t),serverValidate:t.serverValidate,persistable:t.isStore!==!1,backfillable:!((g=t.extra)!=null&&g.needless),submittable:!((y=t.extra)!=null&&y.submitless),collectWhenHidden:t.needDataWhenNotShow===!0,autoFill:(_=t.extra)==null?void 0:_.need_auto_fill,initRelationsAtStart:t.needInitRelations===!0,relationsWhenHidden:t.needRelationsWhenNotShow===!0,relations:Ns(t.relations),initOptions:Ft(t.initOptions),props:Ds(t,l,i),extra:t.extra};return r&&Object.keys(r).length>0&&$s(c,r),c}function Ft(t){if(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return}}}const Rs={base_form_input:"input",base_form_textarea:"textarea",base_form_select:"select",base_input_search:"search",base_form_search:"search",base_address_map:"address",base_form_address:"address",base_form_date:"date",base_form_date_range:"dateRange",base_form_verify_code:"verifyCode",base_form_image_upload:"imageUpload",base_form_slider:"slider",base_form_agreement:"agreement",base_form_agreement_read:"agreement"};function ws(t){const e={};function s(i){var n;if(i){if(i.name==="custom_comp"&&i.attrs){const r=i.attrs[":prop_target"],a=(i.attrs[":prop_source_path"]||"").replace(/^form\./,""),o=r||a;if(o){const l=i.attrs[":prop_title"],c=i.attrs[":prop_description"]||i.attrs[":prop_desc"],u={};for(const f of Object.keys(i.attrs))if(f.startsWith(":prop_")){const g=f.slice(6);u[g]=i.attrs[f]}const d=Rs[i.attrs.name]||(u.agreementlist?"agreement":void 0);(l||d||c||Object.keys(u).length>0)&&(e[o]={...e[o],...l?{label:l}:{},...d?{typeHint:d}:{},...c?{description:c}:{},nodeProps:{...(n=e[o])==null?void 0:n.nodeProps,...u}})}}Array.isArray(i.children)&&i.children.forEach(s)}}return t.forEach(s),e}function Ts(t,e){const s=[];let i=0;function n(r){if(r){if(r.name==="custom_comp"&&r.attrs){const a=r.attrs.name;if(a==="base_form_title"){const o=r.attrs[":prop_title"]||"",l=r.attrs[":prop_description"]||r.attrs[":prop_desc"]||void 0;s.push({title:o,key:`group_${s.length+1}`,startIndex:i,endIndex:0,description:l})}else a!=="base_form_submit_button"&&a!=="base_form_agreement_read"&&i++}Array.isArray(r.children)&&r.children.forEach(n)}}t.forEach(n);for(let r=0;r<s.length;r++){const a=r+1<s.length?s[r+1].startIndex:e;s[r].endIndex=a-1}return s.filter(r=>r.startIndex<=r.endIndex)}function Os(t){var s,i,n,r,a;if(t.formItemType==="timePicker")return"date";if(t.searchApi)return"search";if(t.uploadApiId)return"imageUpload";if(t.linkageUrl)return((s=t.extra)==null?void 0:s.map_level)===5||t.mapLevel===5?"address5":((i=t.extra)==null?void 0:i.pinyin)===!0?"addressPinyin":"address";const e=Ft(t.initOptions);return e&&e.length>0?e.some(l=>l.child&&l.child.length>0)?"cascader":"select":t.verifyText||t.countTime||t.reVerifyText?"verifyCode":(n=t.extra)!=null&&n.step||((r=t.extra)==null?void 0:r.min)!==void 0?"slider":(a=t.extra)!=null&&a.agreementType||t.formItemType==="agreement"?"agreement":"input"}function xs(t){const e=[];if(t.required&&e.push({type:"required",message:t.requiredMsg||"请填写此字段",trigger:Ze(t)}),t.frontValidate&&t.frontValidate.length>0)for(const s of t.frontValidate){if(!s)continue;const i=Kt(s,t);i&&e.push(i)}return t.needByteCheck&&t.byteLenth&&e.push({type:"byteLength",byteLength:t.byteLenth,message:t.byteReminder||`不得超过${t.byteLenth}字节`,trigger:"blur"}),e.length>0?e:void 0}function Cs(t){if(!t.warningValidate||t.warningValidate.length===0)return;const e=[];for(const s of t.warningValidate){if(!s)continue;const i=Kt(s,t);i&&e.push(i)}return e.length>0?e:void 0}function Kt(t,e){const s=Number(t.type);return s===0&&t.reg?{type:"regex",regex:t.reg,message:t.msg||"格式不正确",trigger:Ze(e)}:s===1&&t.logic?{type:"logic",logic:t.logic,message:t.msg||"校验不通过",trigger:Ze(e)}:null}function Ze(t){return t.exportErrorTime&&t.exportErrorTime.length===1&&t.exportErrorTime[0]==="submit"?"submit":"blur"}function Ns(t){if(!(!t||t.length===0))return t.filter(e=>e!=null).map(e=>{let s="value";switch(e.field){case"isShow":s="visible";break;case"isDisabled":s="disabled";break;case"value":default:s="value";break}return{target:(e.sourcePath||"").replace(/^form\./,""),effect:s,type:e.type===1?"remote":"local",logic:e.logic,api:e.api}})}function Ds(t,e,s){var n,r,a,o,l,c,u,d,f,g,y,_,m,S,h,b,A,v;const i={};switch(t.maxlength&&(i.maxlength=t.maxlength),(n=t.extra)!=null&&n.minlength&&(i.minlength=t.extra.minlength),e){case"input":case"textarea":case"number":case"idcard":case"phone":case"bankCard":t.maxlength&&(i.maxlength=t.maxlength),(r=t.extra)!=null&&r.autocomplete&&(i.autocomplete=t.extra.autocomplete),(a=t.extra)!=null&&a.formatter&&(i.formatter=t.extra.formatter);break;case"select":t.isSingle!==void 0&&(i.isSingle=t.isSingle),(o=t.extra)!=null&&o.dialogtitle&&(i.dialogTitle=t.extra.dialogtitle),(l=t.extra)!=null&&l.confirmtext&&(i.confirmText=t.extra.confirmtext);break;case"cascader":break;case"address":case"address5":case"addressPinyin":t.linkageUrl&&(i.linkageUrl=t.linkageUrl),t.requestConfig&&(i.requestConfig=t.requestConfig),(c=t.extra)!=null&&c.map_level&&(i.mapLevel=t.extra.map_level),t.isV2!==void 0&&(i.requestConfig={...i.requestConfig,isV2:t.isV2});break;case"date":case"dateRange":t.startDate&&(i.startDate=t.startDate),t.endDate&&(i.endDate=t.endDate),(u=t.extra)!=null&&u.prop_date_format&&(i.dateFormat=t.extra.prop_date_format),(d=t.extra)!=null&&d.prop_custom_separator&&(i.customSeparator=t.extra.prop_custom_separator);break;case"search":t.searchApi&&(i.searchApi=t.searchApi),t.reqExtraKey&&(i.reqExtraKeys=t.reqExtraKey),t.valueCustomKey&&(i.valueCustomKey=t.valueCustomKey),t.extraResKeys&&(i.extraResKeys=t.extraResKeys),(f=t.extra)!=null&&f.select_type&&(i.searchType=t.extra.select_type);break;case"verifyCode":(t.verifyApi||(g=t.extra)!=null&&g.verifyApi)&&(i.verifyApi=t.verifyApi||((y=t.extra)==null?void 0:y.verifyApi)),t.countTime&&(i.countTime=t.countTime),t.verifyText&&(i.verifyText=t.verifyText),t.reVerifyText&&(i.reVerifyText=t.reVerifyText),(_=t.extra)!=null&&_.mobileFrom&&(i.mobileFrom=t.extra.mobileFrom),(m=t.extra)!=null&&m.mobileKey&&(i.mobileKey=t.extra.mobileKey);break;case"imageUpload":t.uploadApiId&&(i.uploadApi=t.uploadApiId),t.maxCount&&(i.maxCount=t.maxCount),t.sourceType&&(i.sourceType=t.sourceType),t.quality&&(i.quality=t.quality),t.fileRemark&&(i.fileRemark=t.fileRemark),t.addExtraParam&&(i.addExtraParam=t.addExtraParam),t.addIcon&&(i.addIcon=t.addIcon),t.deleteIcon&&(i.deleteIcon=t.deleteIcon);break;case"slider":((S=t.extra)==null?void 0:S.min)!==void 0&&(i.min=t.extra.min),((h=t.extra)==null?void 0:h.max)!==void 0&&(i.max=t.extra.max),((b=t.extra)==null?void 0:b.step)!==void 0&&(i.step=t.extra.step),(A=t.extra)!=null&&A.active_color&&(i.activeColor=t.extra.active_color);break;case"agreement":(v=t.extra)!=null&&v.agreementType&&(i.agreementType=t.extra.agreementType);break;case"task":s!=null&&s.taskType&&(i.taskType=s.taskType),s!=null&&s.taskCategory&&(i.taskCategory=s.taskCategory);const k=t.extra||{};k.needParams!==void 0&&(i.needParams=k.needParams),k.pageId!==void 0&&(i.pageId=k.pageId),k.contractType!==void 0&&(i.contractType=k.contractType),k.isBackAfterSubmit!==void 0&&(i.isBackAfterSubmit=k.isBackAfterSubmit),k.withAntifraud!==void 0&&(i.withAntifraud=k.withAntifraud),k.needSubmit!==void 0&&(i.needSubmit=k.needSubmit),k.h5link!==void 0&&(i.h5link=k.h5link),k.appendageTaskType!==void 0&&(i.appendageTaskType=k.appendageTaskType),k.taxLink!==void 0&&(i.taxLink=k.taxLink),k.authTip!==void 0&&(i.authTip=k.authTip),k.productName!==void 0&&(i.productName=k.productName),k.faceSceneId!==void 0&&(i.faceSceneId=k.faceSceneId),k.faceVerifyApi!==void 0&&(i.faceVerifyApi=k.faceVerifyApi),k.bankOptions!==void 0&&(i.bankOptions=k.bankOptions),k.collectCount!==void 0&&(i.collectCount=k.collectCount),k.initWhenCallback!==void 0&&(i.initWhenCallback=k.initWhenCallback);break}return Object.keys(i).length>0?i:void 0}function $s(t,e){e.placeholder!==void 0&&(t.placeholder=e.placeholder),e.hintdetail!==void 0&&(t.help=e.hintdetail),e.title!==void 0&&!t.label&&(t.label=e.title),e.description!==void 0&&!t.description&&(t.description=e.description),e.desc!==void 0&&!t.description&&(t.description=e.desc);const s=t.props||{};let i=!1;e.maxlength!==void 0&&(s.maxlength=Number(e.maxlength),i=!0),e.minlength!==void 0&&(s.minlength=Number(e.minlength),i=!0),e.dialogtitle!==void 0&&(s.dialogTitle=e.dialogtitle,i=!0),e.confirmtext!==void 0&&(s.confirmText=e.confirmtext,i=!0),e.canceltext!==void 0&&(s.cancelText=e.canceltext,i=!0),e.select_type!==void 0&&(s.searchType=e.select_type,i=!0),e.guidetext!==void 0&&(s.guideText=e.guidetext,i=!0),e.type!==void 0&&(s.keyboardType=e.type,i=!0),e.task_type!==void 0&&(s.taskType=e.task_type,i=!0),i&&(t.props=s);const n=["showhintimg","showexample","no_map","remind_text","show_reminder","importimg","customer_title","customertitlestyle","showtitlebtn","customer_title","prop_id","reminderstyle","importimg"],r={};for(const o of n)e[o]!==void 0&&(r[o]=e[o]);const a=new Set(["title","description","desc","placeholder","hintdetail","maxlength","minlength","dialogtitle","confirmtext","canceltext","guidetext","select_type","type","task_type","source_path","target",...n]);for(const o of Object.keys(e))a.has(o)||(r[o]=e[o]);Object.keys(r).length>0&&(t.extra={...t.extra,nodeProps:r})}function Ms(t,e){let s;const i=(e==null?void 0:e.request)||t.request;if(i)try{const o=typeof i=="string"?JSON.parse(i):i;o&&o.url&&(s={url:o.url,method:o.method||"POST",headers:o.headers,options:o.options})}catch{}const n=(e==null?void 0:e.params)||t.params,r=n==null?void 0:n.map(o=>({name:o.name,source:o.source||"fixed",default:o.default,required:o.required}));let a=t.scene||"other";return((e==null?void 0:e.service_reference_name)==="read_local_storage"||(e==null?void 0:e.reference_name)==="read_local_storage")&&(a="localData"),{id:t.id,scene:a,additionParams:t.additionParams,extraLogic:t.extraLogic,failback:t.failback,interptor:t.interptor,request:s,params:r,accessMode:(e==null?void 0:e.access_mode)||t.access_mode,isAsync:(e==null?void 0:e.is_async)??t.is_async}}function Ls(t){const e=i=>i.type!=="regex"||!i.regex?!1:i.regex.length>200&&/\(\?:.*2奶|4风.*\)/.test(i.regex),s=t.filter(i=>!e(i)&&i.type!=="required").map(i=>i.message);return s.length>0?s.join("; "):void 0}function Mr(t){const e=[];let s=0;for(const i of t.groups){const n=[];for(const r of i.items){if(r.type==="agreement")continue;s++;const a={key:r.key,question:r.label||r.key,question_seq:s,type:r.type,required:r.required};if(r.description&&(a.description=r.description),r.initOptions&&r.initOptions.length>0&&(a.options=r.initOptions),r.rules&&r.rules.length>0){const o=Ls(r.rules);o&&(a.validation=o)}n.push(a)}e.push({key:i.key,title:i.title,description:i.description,fields:n})}return e}function ft(t){const e=new Map;for(const s of t.groups)s.items.forEach((i,n)=>{e.set(i.key,{groupKey:s.key,item:i,index:n})});return e}function gt(t){return new Map(t.groups.map(e=>[e.key,e]))}function Vs(t,e){const s=new Set([...Object.keys(t),...Object.keys(e)]);for(const i of s)if(JSON.stringify(t[i])!==JSON.stringify(e[i]))return!0;return!1}function Fs(t,e){const s=[],i=ft(t),n=ft(e),r=gt(t),a=gt(e);for(const[o,l]of r)a.has(o)||s.push({kind:"remove",path:`groups.${o}`,groupKey:o,before:l});for(const[o,l]of a)if(!r.has(o))s.push({kind:"add",path:`groups.${o}`,groupKey:o,after:l});else{const c=r.get(o),{items:u,...d}=c,{items:f,...g}=l;Vs(d,g)&&s.push({kind:"update",path:`groups.${o}`,groupKey:o,before:d,after:g})}for(const[o,l]of i)n.has(o)||s.push({kind:"remove",path:`fields.${o}`,fieldKey:o,groupKey:l.groupKey,before:l.item});for(const[o,l]of n){const c=i.get(o);if(!c){s.push({kind:"add",path:`fields.${o}`,fieldKey:o,groupKey:l.groupKey,after:l.item});continue}(c.groupKey!==l.groupKey||c.index!==l.index)&&s.push({kind:"move",path:`fields.${o}`,fieldKey:o,before:{groupKey:c.groupKey,index:c.index},after:{groupKey:l.groupKey,index:l.index}}),JSON.stringify(c.item)!==JSON.stringify(l.item)&&s.push({kind:"update",path:`fields.${o}`,fieldKey:o,groupKey:l.groupKey,before:c.item,after:l.item})}return t.storageKey!==e.storageKey&&s.push({kind:"update",path:"storageKey",before:t.storageKey,after:e.storageKey}),JSON.stringify(t.apis||[])!==JSON.stringify(e.apis||[])&&s.push({kind:"update",path:"apis",before:t.apis,after:e.apis}),{entries:s}}const _e=/(idcard|id_?no|identity|passport|phone|mobile|tel|bank|card.?no|password|pwd|secret|salary|income|ssn|身份证|手机|银行卡|密码|收入)/i;function pt(t){const e=new Map;for(const s of t.groups)for(const i of s.items)e.set(i.key,i);return e}function ht(t){return t?t.required?!0:(t.rules||[]).some(e=>e.type==="required"):!1}function Ks(t,e){const s=ht(t),i=ht(e);if(s&&!i)return!0;const n=t.rules||[],r=e.rules||[];if(n.length>r.length)return!0;const a=new Set(r.map(o=>JSON.stringify(o)));for(const o of n)if(!a.has(JSON.stringify(o)))return!0;return!1}function Ps(t,e,s){const i=(t.relations||[]).filter(r=>s.includes(r.effect)),n=(e.relations||[]).filter(r=>s.includes(r.effect));return JSON.stringify(i)!==JSON.stringify(n)}function Pt(t,e,s){const i=[],n=pt(t),r=pt(e);for(const c of s.entries)c.kind==="remove"&&c.fieldKey&&i.push({code:"DELETE_FIELD",severity:"high",message:`删除字段 ${c.fieldKey}`,path:c.path}),c.kind==="remove"&&c.groupKey&&!c.fieldKey&&i.push({code:"DELETE_GROUP",severity:"high",message:`删除分组 ${c.groupKey}`,path:c.path});t.storageKey!==e.storageKey&&i.push({code:"CHANGE_STORAGE_KEY",severity:"high",message:"修改 storageKey",path:"storageKey"});for(const[c,u]of n){const d=r.get(c);d&&(u.key!==d.key&&i.push({code:"CHANGE_KEY",severity:"high",message:"字段 key 变更",path:`fields.${c}`}),u.type!==d.type&&i.push({code:"CHANGE_TYPE",severity:"high",message:`字段 ${c} type: ${u.type} → ${d.type}`,path:`fields.${c}.type`}),u.valueType!==d.valueType&&i.push({code:"CHANGE_VALUE_TYPE",severity:"high",message:`字段 ${c} valueType: ${u.valueType} → ${d.valueType}`,path:`fields.${c}.valueType`}),Ks(u,d)&&i.push({code:"RELAX_REQUIRED",severity:"high",message:`字段 ${c} 放宽必填或校验规则`,path:`fields.${c}.rules`}),Ps(u,d,["visible","disabled","value"])&&i.push({code:"CHANGE_RELATION",severity:"high",message:`字段 ${c} 修改显隐/禁用/赋值联动`,path:`fields.${c}.relations`}),(u.type==="task"||d.type==="task")&&(JSON.stringify(u.props)!==JSON.stringify(d.props)||u.type!==d.type)&&i.push({code:"MODIFY_TASK",severity:"high",message:`字段 ${c} 新增或修改 task`,path:`fields.${c}`}),(_e.test(c)||_e.test(String(u.label||""))||_e.test(String(d.label||"")))&&JSON.stringify(u)!==JSON.stringify(d)&&i.push({code:"SENSITIVE_FIELD",severity:"high",message:`修改敏感字段 ${c}`,path:`fields.${c}`}))}for(const[c,u]of r)!n.has(c)&&u.type==="task"&&i.push({code:"ADD_TASK",severity:"high",message:`新增 task 字段 ${c}`,path:`fields.${c}`}),!n.has(c)&&(_e.test(c)||_e.test(String(u.label||"")))&&i.push({code:"SENSITIVE_FIELD",severity:"high",message:`新增敏感字段 ${c}`,path:`fields.${c}`});JSON.stringify(t.apis||[])!==JSON.stringify(e.apis||[])&&i.push({code:"MODIFY_API",severity:"high",message:"新增或修改 API",path:"apis"});const a=s.entries.filter(c=>(c.kind==="add"||c.kind==="remove")&&(c.fieldKey!=null||c.groupKey!=null&&!c.fieldKey)).length,o=n.size;o>0&&a>=Math.max(3,Math.ceil(o*.5))&&i.push({code:"LARGE_STRUCTURAL_REPLACE",severity:"high",message:`大面积结构替换(${a} 处增删)`,path:""});const l=new Set;return i.filter(c=>{const u=`${c.code}|${c.path||""}`;return l.has(u)?!1:(l.add(u),!0)})}function ue(t){return JSON.parse(JSON.stringify(t))}function L(t,e,s){return{code:t,path:e,message:s}}function Ge(t,e){for(let s=0;s<t.groups.length;s++){const i=t.groups[s].items;for(let n=0;n<i.length;n++)if(i[n].key===e)return{groupIndex:s,itemIndex:n,item:i[n]}}return null}function pe(t,e){return t.groups.findIndex(s=>s.key===e)}function Be(t){return t.groups.flatMap(e=>e.items.map(s=>s.key))}const qs=new Set(["subItems"]);function Us(t,e,s){switch(e.op){case"addGroup":{if(!e.group||typeof e.group!="object"||!e.group.key)return L("INVALID_GROUP","operations.addGroup","addGroup 缺少合法 group");if(pe(t,e.group.key)>=0)return L("DUPLICATE_GROUP_KEY",`groups.${e.group.key}`,`分组 key=${e.group.key} 已存在`);const i={...ue(e.group),items:Array.isArray(e.group.items)?ue(e.group.items):[]};for(const r of i.items)if(Be(t).includes(r.key))return L("DUPLICATE_FIELD_KEY",`fields.${r.key}`,`字段 key=${r.key} 重复`);const n=e.index==null||e.index<0||e.index>t.groups.length?t.groups.length:e.index;return t.groups.splice(n,0,i),null}case"updateGroup":{const i=pe(t,e.groupKey);if(i<0)return L("GROUP_NOT_FOUND",`groups.${e.groupKey}`,`分组 ${e.groupKey} 不存在`);if(!e.changes||typeof e.changes!="object")return L("INVALID_CHANGES",`groups.${e.groupKey}`,"updateGroup.changes 必须是对象");if("key"in e.changes&&e.changes.key&&e.changes.key!==e.groupKey&&pe(t,e.changes.key)>=0)return L("DUPLICATE_GROUP_KEY",`groups.${e.changes.key}`,`分组 key=${e.changes.key} 已存在`);if("items"in e.changes)return L("DISALLOWED_PATH",`groups.${e.groupKey}.items`,"不允许通过 updateGroup 直接替换 items");const{key:n,items:r,...a}=e.changes;return Object.assign(t.groups[i],ue(a)),e.changes.key&&e.changes.key!==e.groupKey&&(t.groups[i].key=e.changes.key),null}case"removeGroup":{const i=pe(t,e.groupKey);return i<0?L("GROUP_NOT_FOUND",`groups.${e.groupKey}`,`分组 ${e.groupKey} 不存在`):(t.groups.splice(i,1),null)}case"addField":{const i=pe(t,e.groupKey);if(i<0)return L("GROUP_NOT_FOUND",`groups.${e.groupKey}`,`分组 ${e.groupKey} 不存在`);if(!e.field||typeof e.field!="object"||!e.field.key)return L("INVALID_FIELD","operations.addField","addField 缺少合法 field");if(Be(t).includes(e.field.key))return L("DUPLICATE_FIELD_KEY",`fields.${e.field.key}`,`字段 key=${e.field.key} 重复`);const n=ue(e.field),r=t.groups[i].items,a=e.index==null||e.index<0||e.index>r.length?r.length:e.index;return r.splice(a,0,n),null}case"updateField":{const i=Ge(t,e.fieldKey);if(!i)return L("FIELD_NOT_FOUND",`fields.${e.fieldKey}`,`字段 ${e.fieldKey} 不存在`);if(!e.changes||typeof e.changes!="object")return L("INVALID_CHANGES",`fields.${e.fieldKey}`,"updateField.changes 必须是对象");for(const r of Object.keys(e.changes))if(qs.has(r))return L("DISALLOWED_PATH",`fields.${e.fieldKey}.${r}`,`不允许通过 updateField 修改 ${r}`);if("key"in e.changes&&e.changes.key&&e.changes.key!==e.fieldKey&&Be(t).includes(e.changes.key))return L("DUPLICATE_FIELD_KEY",`fields.${e.changes.key}`,`字段 key=${e.changes.key} 重复`);const n={...i.item,...ue(e.changes)};return t.groups[i.groupIndex].items[i.itemIndex]=n,null}case"moveField":{const i=Ge(t,e.fieldKey);if(!i)return L("FIELD_NOT_FOUND",`fields.${e.fieldKey}`,`字段 ${e.fieldKey} 不存在`);const n=pe(t,e.targetGroupKey);if(n<0)return L("GROUP_NOT_FOUND",`groups.${e.targetGroupKey}`,`目标分组 ${e.targetGroupKey} 不存在`);const[r]=t.groups[i.groupIndex].items.splice(i.itemIndex,1),a=t.groups[n].items,o=e.index==null||e.index<0||e.index>a.length?a.length:e.index;return a.splice(o,0,r),null}case"removeField":{const i=Ge(t,e.fieldKey);return i?(t.groups[i.groupIndex].items.splice(i.itemIndex,1),null):L("FIELD_NOT_FOUND",`fields.${e.fieldKey}`,`字段 ${e.fieldKey} 不存在`)}case"setTheme":return!e.changes||typeof e.changes!="object"?L("INVALID_THEME","operations.setTheme","setTheme.changes 必须是对象"):(Object.assign(s,ue(e.changes)),null);default:return L("UNKNOWN_OP","operations",`未知操作 ${e.op}`)}}function ne(t,e,s={}){const i=g=>({ok:!1,diff:{entries:[]},risks:[],errors:g});if(!t||typeof t!="object")return i([L("SCHEMA_NOT_OBJECT","","currentSchema 不是合法对象")]);if(!e||typeof e!="object")return i([L("CHANGESET_INVALID","","changeSet 不是合法对象")]);if(!Array.isArray(e.operations))return i([L("OPERATIONS_NOT_ARRAY","operations","operations 必须是数组")]);const n=s.expectedVersion??t.version;if(e.baseVersion!==n)return i([L("STALE_BASE_VERSION","baseVersion",`baseVersion=${e.baseVersion} 与当前版本 ${n} 不匹配`)]);const r=s.seenRequestIds;if(r){if(e.requestId&&r.has(e.requestId))return i([L("DUPLICATE_REQUEST_ID","requestId",`requestId=${e.requestId} 已处理`)]);if(e.idempotencyKey&&r.has(e.idempotencyKey))return i([L("DUPLICATE_REQUEST_ID","idempotencyKey",`idempotencyKey=${e.idempotencyKey} 已处理`)])}const a=ue(t),o={},l=[];for(let g=0;g<e.operations.length;g++){const y=e.operations[g],_=Us(a,y,o);if(_){l.push({..._,path:_.path||`operations[${g}]`,message:`operations[${g}]: ${_.message}`});break}}if(l.length>0)return i(l);const c=z(a,{allowEmpty:!0});if(!c.valid)return i(c.issues);const u=Fs(t,a),d=Pt(t,a,u),f={ok:!0,nextSchema:a,diff:u,risks:d,errors:[],appliedRequestId:e.requestId};return Object.keys(o).length>0&&(f.meta={themeChanges:o}),f}function js(t){var e,s;switch(t.op){case"addField":return`新增字段 ${((e=t.field)==null?void 0:e.key)||"?"}`;case"updateField":return`更新字段 ${t.fieldKey}`;case"removeField":return`删除字段 ${t.fieldKey}`;case"moveField":return`移动字段 ${t.fieldKey}`;case"addGroup":return`新增分组 ${((s=t.group)==null?void 0:s.key)||"?"}`;case"updateGroup":return`更新分组 ${t.groupKey}`;case"removeGroup":return`删除分组 ${t.groupKey}`;case"setTheme":return"更新主题";default:return"变更"}}function qt(t,e,s){var a,o;const i=new Set(t.impactedFields||[]);for(const l of((a=e.diff)==null?void 0:a.entries)||[])l.fieldKey&&i.add(l.fieldKey);for(const l of t.operations||[])"fieldKey"in l&&l.fieldKey&&i.add(l.fieldKey),l.op==="addField"&&((o=l.field)!=null&&o.key)&&i.add(l.field.key);const n=(t.operations||[]).map(js),r=t.rationale||[t.intentSummary,n.length?`操作:${n.join(";")}`:""].filter(Boolean).join("。");return{...t,rationale:r,impactedFields:Array.from(i),rollback:t.rollback||{fromVersion:s,summary:`回滚到版本 ${s}(撤销:${t.intentSummary||"最近提案"})`}}}function mt(t,e){if(!(t!=null&&t.groups))return e;for(const s of t.groups)for(const i of s.items||[])if(i.key===e)return String(i.label||i.key);return e}function yt(t){const e=new Set;if(!(t!=null&&t.groups))return e;for(const s of t.groups)for(const i of s.items||[]){const n=i.relations;Array.isArray(n)&&n.length&&e.add(i.key)}return e}function kt(t){return((t==null?void 0:t.apis)||[]).map(e=>String(e.id||e.key||"")).filter(Boolean)}function Lr(t){var w,P,E,V,j,q,oe,X;const e=t.appliedSchema||null,s=((w=t.dryRun)==null?void 0:w.nextSchema)||null,i=qt(t.changeSet,t.dryRun,t.baseVersion||t.changeSet.baseVersion||"0"),n=t.systemRisks||((P=t.dryRun)==null?void 0:P.risks)||[],r=n.some(R=>(R==null?void 0:R.severity)==="high"),a=((V=(E=t.dryRun)==null?void 0:E.diff)==null?void 0:V.entries)||[],o=[],l=new Set;let c=0,u=0;for(const R of a){const ge=R.fieldKey||((j=R.path)==null?void 0:j.split(".").pop())||R.path||"?";R.fieldKey&&l.add(R.fieldKey);const te=mt(s||e,String(ge)),p=String(R.path||"");/relations/i.test(p)?(c+=1,o.push({dimension:"relation",kind:R.kind==="add"||R.kind==="remove"||R.kind==="update"?R.kind:"update",label:`联动 · ${te}`,detail:p,fieldKey:R.fieldKey})):/rules|validate|warningRules/i.test(p)?(u+=1,o.push({dimension:"validation",kind:R.kind==="add"||R.kind==="remove"||R.kind==="update"?R.kind:"update",label:`校验 · ${te}`,detail:p,fieldKey:R.fieldKey})):/groups\.[^.]+\.title|groups\.[^.]+\.key/.test(p)&&!/items/.test(p)?o.push({dimension:"group",kind:R.kind==="add"||R.kind==="remove"||R.kind==="update"?R.kind:"update",label:`分组 · ${te}`,detail:p}):o.push({dimension:"field",kind:R.kind==="add"||R.kind==="remove"||R.kind==="update"?R.kind:"update",label:te,detail:p,fieldKey:R.fieldKey})}for(const R of i.impactedFields||[])l.has(R)||(l.add(R),o.push({dimension:"field",kind:"update",label:mt(s||e,R),fieldKey:R}));const d=kt(e).sort().join(","),f=kt(s).sort().join(","),g=(e==null?void 0:e.submitApi)||null,y=(s==null?void 0:s.submitApi)||null,_=g===y,m=d===f;_?o.push({dimension:"submit",kind:"retain",label:"提交接口保持不变",detail:y?String(y):"未配置 submitApi"}):o.push({dimension:"submit",kind:"update",label:"提交接口发生变化",detail:`${g||"∅"} → ${y||"∅"}`}),m&&o.push({dimension:"api",kind:"retain",label:"接口声明保持不变"});const S=yt(e),h=yt(s);let b=0;for(const R of h)S.has(R)||(b+=1);for(const R of S)h.has(R)||(b+=1);c===0&&b>0&&(c=b);const A=!!((q=t.dryRun)!=null&&q.ok),v=((oe=t.dryRun)==null?void 0:oe.errors)||[],k=[{id:"schema",status:A&&v.length===0?"pass":"fail",label:"Schema 结构",detail:A?void 0:v.map(R=>R.message||String(R)).join(";")},{id:"fieldRefs",status:A?"pass":"fail",label:"字段引用"},{id:"relations",status:c>0||b>0?"needs_confirm":"unchanged",label:"联动变化",detail:c>0||b>0?`涉及 ${Math.max(c,b)} 处联动相关变更`:"无联动变更"},{id:"submitApi",status:_?"unchanged":"needs_confirm",label:"提交接口",detail:_?"未修改":"已修改,请确认"}];return{title:i.intentSummary||"提案影响分析",intentSummary:i.intentSummary||i.rationale||"",highRisk:r,counts:{modifications:a.length||((X=i.operations)==null?void 0:X.length)||0,fieldsImpacted:l.size,relations:Math.max(c,b),validations:u},assumptions:i.assumptions||[],items:o,checks:k,risks:n,retainedSubmitApi:_}}const Ie="form-architect-v2",_t="ai-changeset-v1",bt="form-schema-draft-v1";class Q extends Error{constructor(e,s,i){super(s),this.name="ArchitectError",this.code=e,this.details=i}}const Ut="form-knowledge-v1";function Gs(t){const e=JSON.stringify(t);let s=2166136261;for(let i=0;i<e.length;i++)s^=e.charCodeAt(i),s=Math.imul(s,16777619);return`map_${(s>>>0).toString(16)}`}function jt(t){return!t||typeof t!="object"?[]:"api"in t&&typeof t.api=="string"?[t.api]:"conditions"in t&&Array.isArray(t.conditions)?t.conditions.flatMap(jt):[]}function Bs(t){var e,s,i;return[...new Set([t.serverValidate,(e=t.props)==null?void 0:e.searchApi,(s=t.props)==null?void 0:s.verifyApi,(i=t.props)==null?void 0:i.faceVerifyApi,...jt(t.visibilityLogic),...(t.relations||[]).map(n=>n.api)].filter(n=>typeof n=="string"&&n.length>0))]}function Gt(t){const e=[],s=[],i=(a,o,l,c,u)=>{e.push({key:a.key,label:a.label||a.key,groupKey:o,index:l,path:c,...u?{parentKey:u}:{},type:a.type,required:a.required===!0||(a.rules||[]).some(d=>d.type==="required"),ruleTypes:[...new Set((a.rules||[]).map(d=>d.type))],hasVisibilityLogic:a.visibilityLogic!=null,apiRefs:Bs(a)});for(const d of a.relations||[])s.push({sourceKey:a.key,targetKey:d.target,effect:d.effect,type:d.type,...d.api?{apiId:d.api}:{}});for(const[d,f]of(a.subItems||[]).entries())i(f,o,d,`${c}.subItems[${d}]`,a.key)},n=(t.groups||[]).map((a,o)=>{for(const[l,c]of(a.items||[]).entries())i(c,a.key,l,`groups[${o}].items[${l}]`);return{key:a.key,title:a.title||a.key,index:o,fieldKeys:(a.items||[]).map(l=>l.key),hasVisibilityLogic:a.visible!=null}}),r=(t.apis||[]).map(a=>({id:a.id,scene:a.scene,formParamKeys:(a.params||[]).filter(o=>o.source==="form"&&typeof o.key=="string").map(o=>o.key),usedBy:e.filter(o=>o.apiRefs.includes(a.id)).map(o=>o.key),isSubmit:t.submitApi===a.id}));return{knowledgeVersion:Ut,snapshotId:Gs(t),schemaVersion:t.version,groups:n,fields:e,relations:s,apis:r,...t.submitApi?{submitApi:t.submitApi}:{}}}function Ys(t=[]){const e=t.length?Object.entries(cs).filter(([s])=>t.includes(s)):[];return{knowledgeVersion:Ut,executableSource:"FormSchema",designSource:"FormBrief",proposal:"AiChangeSet",controlTypes:[...fs],ruleTypes:[...ds],relationEffects:[...us],patchOperations:["addGroup","updateGroup","removeGroup","addField","updateField","moveField","removeField","setTheme"],semantics:{fieldKey:"formData 中的稳定标识;label 是给人看的名称",groupItems:"数组顺序即表单显示顺序;指定前后位置时必须给 addField.index 或 moveField.index",required:"required 属性或 required 校验规则表示必填",relation:"source 字段通过 relation 对 target 字段的 value/visible/disabled 产生影响",api:"字段或联动以 API id 引用接口;submitApi 是提交入口",provenance:"FormBrief 记录目标和来源;不要把推测的业务含义写入 FormSchema"},platforms:e.map(([s,i])=>({id:s,version:i.version,previewLayer:i.layer,controls:i.controls,features:i.features}))}}function Js(t,e=[]){return[["web",/\bweb\b|网页|浏览器/i],["vue-h5",/vue\s*-?\s*h5/i],["taro-h5",/taro\s*-?\s*h5/i],["miniapp",/小程序|miniapp/i],["rn",/\brn\b|react\s*native/i]].filter(([i,n])=>e.some(r=>r===i||n.test(r))||n.test(t)).map(([i])=>i)}function Hs(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qs(t,e){const s=e.groups.flatMap(n=>[n.title,n.key].filter(r=>t.includes(r)).map(r=>({key:n.key,name:r}))).sort((n,r)=>r.name.length-n.name.length),i=s[0];if(i)return s.every(n=>n.key===i.key||i.name.includes(n.name))?i.key:void 0}function Ws(t,e,s){const i=[];for(const a of e.fields)if(!(a.parentKey||s&&a.groupKey!==s))for(const o of new Set([a.label,a.key])){const l=Hs(o);for(const[c,u]of[["after","后"],["before","前"]]){const d=new RegExp(`${l}\\s*(?:字段)?\\s*(?:之)?${u}(?:面)?`,"g");for(const f of t.matchAll(d)){const g=f.index||0;i.push({fieldKey:a.key,position:c,start:g,end:g+f[0].length,nameLength:o.length})}}}const n=i.filter(a=>!i.some(o=>o!==a&&o.nameLength>a.nameLength&&o.start<=a.start&&o.end>=a.end)),r=n.filter((a,o)=>n.findIndex(l=>l.fieldKey===a.fieldKey&&l.position===a.position)===o);return r.length===1?{fieldKey:r[0].fieldKey,position:r[0].position}:void 0}function Bt(t,e){const s=/不修改任何已有字段|不修改原有字段|其他字段.{0,8}不变|保持原有字段.{0,8}不变|规则和接口.{0,8}不变/.test(t),i=/新增|添加|增加|插入/.test(t),n=/一个|一项|1\s*个/.test(t),r=[...t.matchAll(/(?:字段|表单项)\s*[“‘"']([^”’"']{1,80})[”’"']/g)],a=i&&n&&r.length===1?r[0][1].trim():void 0;if(!a)return{kind:s?"preserve-only":"unscoped",preserveExisting:s};const o=Qs(t,e),l=Ws(t,e,o),c=/非必填|不必填|选填/.test(t)?!1:/必填|必须填写/.test(t)?!0:void 0,u=/单行文本|单行输入|文本输入框/.test(t)?"input":void 0;return{kind:"add-one-field",fieldLabel:a,...o?{groupKey:o}:{},...l?{anchor:l}:{},...u?{type:u}:{},...c===void 0?{}:{required:c},preserveExisting:s}}function zs(t){return t.required===!0||(t.rules||[]).some(e=>e.type==="required")}function Xs(t,e){if(JSON.stringify(t.apis||[])!==JSON.stringify(e.apis||[])||t.submitApi!==e.submitApi||t.storageKey!==e.storageKey||t.groups.length!==e.groups.length)return!0;for(const[s,i]of t.groups.entries()){const n=e.groups[s];if(!n||n.key!==i.key)return!0;const{items:r,...a}=i,{items:o,...l}=n;if(JSON.stringify(a)!==JSON.stringify(l))return!0;const c=new Set(r.map(d=>d.key)),u=o.filter(d=>c.has(d.key));if(JSON.stringify(r)!==JSON.stringify(u))return!0}return!1}function Zs(t,e,s){if(s.kind==="unscoped")return{status:"unscoped",coverage:"explicit-only",issues:[]};const i=[];if(s.preserveExisting&&Xs(t,e)&&i.push({code:"EXISTING_CONTENT_CHANGED",message:"用户要求保留的已有字段、分组或接口发生了变化"}),s.kind==="add-one-field"){const n=new Set(t.groups.flatMap(o=>o.items.map(l=>l.key))),r=e.groups.flatMap(o=>o.items.filter(l=>!n.has(l.key)).map(l=>({item:l,group:o})));r.length!==1&&i.push({code:"ADD_FIELD_COUNT_MISMATCH",message:`用户要求新增一个字段,实际新增 ${r.length} 个`});const a=r.find(({item:o})=>o.label===s.fieldLabel);if(!a)i.push({code:"ADD_FIELD_LABEL_MISMATCH",message:`未新增名称为「${s.fieldLabel}」的字段`});else if(s.groupKey&&a.group.key!==s.groupKey&&i.push({code:"ADD_FIELD_GROUP_MISMATCH",message:"新增字段不在指定分组中"}),s.type&&a.item.type!==s.type&&i.push({code:"ADD_FIELD_TYPE_MISMATCH",message:"新增字段类型与明确要求不符"}),s.required!==void 0&&zs(a.item)!==s.required&&i.push({code:"ADD_FIELD_REQUIRED_MISMATCH",message:"新增字段的必填设置与明确要求不符"}),s.anchor){const o=a.group.items.findIndex(u=>{var d;return u.key===((d=s.anchor)==null?void 0:d.fieldKey)}),l=a.group.items.findIndex(u=>u.key===a.item.key),c=o+(s.anchor.position==="after"?1:-1);(o<0||l!==c)&&i.push({code:"ADD_FIELD_POSITION_MISMATCH",message:"新增字段未放在指定字段的前后位置"})}}return{status:i.length?"failed":"passed",coverage:"explicit-only",issues:i}}const ei="edit-task-v1";function vt(t,e,s){return t.includes(e)||s!==e&&t.includes(s)}function Yt(t,e,s){const i=e.groups.filter(o=>vt(t,o.key,o.title)),n=e.fields.filter(o=>vt(t,o.key,o.label)),r=new Map;for(const o of n)r.set(o.label,(r.get(o.label)||0)+1);const a=i.length===0&&n.length===0?"form":i.length>1||n.length>1?"multi-target":n.length===1?"field":"group";return{version:ei,schemaSnapshotId:e.snapshotId,userGoal:t,scope:a,candidateGroupKeys:i.map(o=>o.key),candidateFieldPaths:n.map(o=>o.path),ambiguousLabels:[...r.entries()].filter(([,o])=>o>1).map(([o])=>o),explicitConstraints:Bt(t,e),briefContext:s?{goals:s.goals,requirements:s.requirements,constraints:s.constraints,nonGoals:s.nonGoals,platforms:s.platforms,answers:s.answers}:null}}const ot={姓名:"customerName",真实姓名:"realName",申请人姓名:"applicantName",客户姓名:"customerName",手机号:"mobile",手机:"mobile",电话:"mobile",联系电话:"mobile",身份证:"idNumber",身份证号:"idNumber",证件号码:"idNumber",证件类型:"idType",邮箱:"email",邮件:"email",电子邮箱:"email",地址:"address",居住地址:"address",备注:"remark",说明:"note",婚姻状况:"maritalStatus",配偶姓名:"spouseName",配偶证件号:"spouseIdNumber",工作单位:"employer",单位名称:"companyName",收入:"income",月收入:"monthlyIncome","月收入(元)":"monthlyIncome",性别:"gender",就业状态:"employmentStatus",职位:"jobTitle",紧急联系人:"emergencyName",是否填写紧急联系人:"hasEmergency",住房性质:"residenceType",是否有车辆:"vehicleOwned",车牌号:"plateNumber",用户协议:"agreementAccept",接收产品通知:"marketingOptIn",短信验证码:"verifyCode",统一社会信用代码:"creditCode",微信号:"wechatId",微信:"wechatId",昵称:"nickname",关系:"relationship",与本人关系:"relationship",电话号码:"phoneNumber",紧急联系人电话:"emergencyMobile",紧急联系人姓名:"emergencyName"};function ti(t){let e=0;for(let s=0;s<t.length;s++)e=e*31+t.charCodeAt(s)|0;return Math.abs(e).toString(36)}function Ne(t){const e=String(t||"").trim();if(!e)return{label:""};const s=e.match(/^([A-Za-z_][\w]*)\s*[\/|/]\s*(.+)$/);if(s)return{key:s[1],label:s[2].replace(/字段$/,"").trim()};const i=e.match(/^(.*?)[\s((]*?(?:key\s*[=::]\s*|键名\s*[=::]\s*|字段key\s*[=::]\s*)([A-Za-z_][\w]*)[\s))]*$/i);if(i&&i[1].replace(/[((]\s*$/,"").trim())return{label:i[1].replace(/[((]\s*$/,"").replace(/字段$/,"").trim(),key:i[2]};const n=e.match(/^(.+?)[((]\s*([A-Za-z_][\w]*)\s*[))]\s*$/);return n?{label:n[1].replace(/字段$/,"").trim(),key:n[2]}:{label:e.replace(/字段$/,"").trim()}}function at(t,e){const s=String(e||"").trim();if(s&&/^[A-Za-z_][\w]*$/.test(s))return s.slice(0,40);const i=ot[t];if(i)return i;const n=t.replace(/[^\w]+/g,"_").replace(/^_|_$/g,"");return n?n.slice(0,24):`field_${ti(t).slice(0,8)}`}function si(t=40){return Object.entries(ot).slice(0,t).map(([e,s])=>`${e}→${s}`).join("、")}const ii=`你是 Form Architect。根据用户业务目标输出结构化 JSON(不要 Markdown 围栏),字段:
|
|
2
|
+
{
|
|
3
|
+
"intentSummary": "string",
|
|
4
|
+
"assumptions": ["string"],
|
|
5
|
+
"clarifyingQuestions": ["string"],
|
|
6
|
+
"schema": { "version": "2.0", "storageKey": "...", "groups": [ ... ] }
|
|
7
|
+
}
|
|
8
|
+
规则:
|
|
9
|
+
- 表达式只能使用 safe-v1(字段比较、布尔组合、白名单函数 isEmpty/len/includes/min/max/abs/str/num/bool)
|
|
10
|
+
- 禁止 Function/eval/window/process/constructor/成员访问
|
|
11
|
+
- 控件 type 仅允许枚举值
|
|
12
|
+
- 信息不足时填写 clarifyingQuestions,并在 assumptions 列出假设,不要静默编造关键业务事实
|
|
13
|
+
- 输出必须是单个 JSON 对象`,ri=`你是 Form Architect 增量编辑器。根据当前 schema 与用户指令输出 AiChangeSet JSON(不要 Markdown 围栏):
|
|
14
|
+
{
|
|
15
|
+
"requestId": "string",
|
|
16
|
+
"baseVersion": "string(必须等于输入 baseVersion)",
|
|
17
|
+
"intentSummary": "string",
|
|
18
|
+
"assumptions": ["string"],
|
|
19
|
+
"clarifyingQuestions": ["string(仅存在歧义时)"],
|
|
20
|
+
"operations": [ FormPatch... ],
|
|
21
|
+
"riskFlags": [{ "code": "string", "severity": "low|medium|high", "message": "string" }],
|
|
22
|
+
"suggestedTests": [{ "name": "string" }]
|
|
23
|
+
}
|
|
24
|
+
FormPatch ops: addGroup|updateGroup|removeGroup|addField|updateField|moveField|removeField|setTheme
|
|
25
|
+
规则:
|
|
26
|
+
- 只返回变更,不要返回完整 schema
|
|
27
|
+
- FormSchema 是唯一可执行真相;FormBrief 是目标与来源,表单画像只是从 Schema 提取的索引
|
|
28
|
+
- 字段稳定标识是 key(英文标识符),label 只是展示文案;引用已有字段必须用 schema 中的真实 key
|
|
29
|
+
- 新增字段时必须同时给出 key 与 label;若用户写了 key=xxx / (wechatId)/ wechatId/微信号,则 key 必须用用户指定值;否则优先用常用映射表(如 手机号→mobile)
|
|
30
|
+
- 先结合领域知识、当前表单画像和 FormBrief 理解整张表;不得把字段 label 当成稳定 key,也不得凭空编造业务含义
|
|
31
|
+
- 整体描述可以涉及多个分组;先检查相关字段、联动、API 和提交影响,不要求用户点选字段
|
|
32
|
+
- 用户指定字段前后位置时,addField/moveField 必须设置正确的 index;未要求改变的字段、规则和接口保持原样
|
|
33
|
+
- 明确约束是验收条件,不得用模型自报置信度替代;若目标字段或业务含义无法唯一确定,返回 clarifyingQuestions
|
|
34
|
+
- 表达式必须是 safe-v1
|
|
35
|
+
- 未要求删除的字段不得删除
|
|
36
|
+
- baseVersion 必须原样回传
|
|
37
|
+
- 输出必须是单个 JSON 对象`;function ni(t,e){const s=`【不可信用户需求开始】
|
|
38
|
+
${t}
|
|
39
|
+
【不可信用户需求结束】`;return e?`${s}
|
|
40
|
+
|
|
41
|
+
上次输出未通过确定性校验:${e}
|
|
42
|
+
请只修复结构化问题后重新输出 JSON。`:s}function oi(t){var o;const e=Gt(t.schema),s=Array.isArray((o=t.brief)==null?void 0:o.platforms)?t.brief.platforms:[],i=Ys(Js(t.instruction,s)),n=Yt(t.instruction,e,t.brief),r=si(),a=`baseVersion=${t.baseVersion}
|
|
43
|
+
【常用 label→key 映射(无显式 key 时优先)】
|
|
44
|
+
${r}
|
|
45
|
+
【FormSchema 领域知识 ${i.knowledgeVersion}】
|
|
46
|
+
${JSON.stringify(i)}
|
|
47
|
+
【不可信当前表单画像 ${e.snapshotId};仅作结构索引】
|
|
48
|
+
${JSON.stringify(e)}
|
|
49
|
+
【编辑任务契约:候选引用仅为线索,explicitConstraints 才是直接证据】
|
|
50
|
+
${JSON.stringify(n)}
|
|
51
|
+
【不可信当前 Schema JSON 开始】
|
|
52
|
+
${JSON.stringify(t.schema)}
|
|
53
|
+
【不可信当前 Schema JSON 结束】
|
|
54
|
+
【不可信修改指令开始】
|
|
55
|
+
${t.instruction}
|
|
56
|
+
【不可信修改指令结束】`;return t.repairError?`${a}
|
|
57
|
+
|
|
58
|
+
上次 ChangeSet 未通过确定性校验:${t.repairError}
|
|
59
|
+
请修复后重新输出 AiChangeSet JSON。`:a}function Jt(){return`brief_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function de(t){return`${t}_${Math.random().toString(36).slice(2,8)}`}function me(t={}){const e=new Date().toISOString();return{id:t.id||Jt(),goals:t.goals,sourceRefs:t.sourceRefs||[],platforms:t.platforms||[],nonGoals:t.nonGoals||[],constraints:t.constraints||[],requirements:t.requirements||(t.goals?[String(t.goals)]:[]),assumptions:t.assumptions||[],unresolvedQuestions:t.unresolvedQuestions||[],answers:t.answers||{},provenance:t.provenance||{source:"user_intent",updatedAt:e}}}function et(t,e){const s=String(t||"").trim(),i=(e==null?void 0:e.answers)||{},n=((e==null?void 0:e.unresolvedQuestions)||[]).filter(g=>!i[g.id]).length;if(n>0&&Object.keys(i).length===0)return{clear:!1,questions:(e.unresolvedQuestions||[]).map(g=>({id:g.id,prompt:g.prompt,reason:g.reason}))};if(Object.keys(i).length>0&&n===0&&s.length>=4)return{clear:!0};const r=[];(!s||s.length<4)&&r.push({id:de("q_empty"),prompt:"请用一句话描述要采集哪些字段或业务目标?",reason:"empty_or_too_short"}),(/^(做个表|帮我|随便|表单|生成表单|改一下|优化一下)[\s。.!!]*$/i.test(s)||/不确定|再说|随便设计|你看着办/.test(s)||/表单/.test(s)&&s.length<10&&!/姓名|手机|字段|采集|进件/.test(s))&&r.push({id:de("q_vague"),prompt:"目标不够具体:需要采集哪些关键字段?适用哪些平台?",reason:"vague_goal"});const o=/只要姓名|需要姓名|保留姓名|采集姓名/.test(s),l=/不要姓名|删除姓名|去掉姓名|移除姓名/.test(s);o&&l&&r.push({id:de("q_contradict_name"),prompt:"需求同时要求保留与删除「姓名」,请明确最终是否采集姓名?",reason:"contradiction"});const c=/只要手机|需要手机|保留手机|采集手机/.test(s),u=/不要手机|删除手机|去掉手机|移除手机/.test(s);c&&u&&r.push({id:de("q_contradict_mobile"),prompt:"需求同时要求保留与删除「手机号」,请明确最终是否采集手机号?",reason:"contradiction"}),/既要删除.*又要保留|又要删除.*又要保留|删除全部.*保留全部/.test(s)&&r.push({id:de("q_contradict_retain"),prompt:"删除与保留指令冲突,请列出必须保留与可以删除的字段清单。",reason:"contradiction"}),/或者|还是|不确定是/.test(s)&&/贷款|进件|表单|字段/.test(s)&&r.push({id:de("q_or"),prompt:"存在互斥选项(“或者/还是”),请选定一种业务场景再继续。",reason:"ambiguous_alternative"});const d=new Set(Object.keys(i).map(g=>{const y=((e==null?void 0:e.unresolvedQuestions)||[]).find(_=>_.id===g);return y==null?void 0:y.reason}).filter(Boolean)),f=r.filter(g=>!d.has(g.reason)&&!i[g.id]);if(f.length===0)return{clear:!0};if(Object.keys(i).length>0&&!f.some(g=>g.reason==="contradiction")){const g=f.filter(y=>y.reason==="contradiction");if(g.length===0&&s.length>=8)return{clear:!0};if(g.length>0)return{clear:!1,questions:g}}return{clear:!1,questions:f}}function ai(t,e){const s=t.unresolvedQuestions||[],i={...t.answers||{},...e},n=s.filter(o=>{const l=i[o.id];return!(l!=null&&String(l).trim()!=="")}),r=new Date().toISOString(),a=[...t.requirements||[]];for(const[o,l]of Object.entries(e))l&&String(l).trim()&&a.push(`answer:${o}=${String(l).trim()}`);return{...t,id:t.id||Jt(),requirements:Array.from(new Set(a)),answers:i,unresolvedQuestions:n,provenance:{source:"clarification_answers",updatedAt:r,parentBriefId:t.id}}}function It(t,e="model_clarification"){return(t||[]).map((s,i)=>({id:de(`q_model_${i}`),prompt:String(s),reason:e}))}const li="clarification-v1";function be(t){const e={...t.brief,unresolvedQuestions:t.questions.map(s=>({id:s.id,prompt:s.prompt,reason:s.reason})),provenance:{source:"intent_clarifier",updatedAt:new Date().toISOString(),parentBriefId:t.brief.id}};return{kind:"clarification_required",questions:t.questions,brief:e,meta:{requestId:t.requestId,promptVersion:Ie,model:t.model||"none",outputSchemaVersion:li,latencyMs:t.latencyMs||0,retryCount:t.retryCount||0,status:"error",errorCode:"AMBIGUOUS_REQUEST"}}}const ci={maxInputChars:1e5,maxRetries:2,timeoutMs:6e4,maxTokens:4e3};function St(t){const e=String(t||"").trim(),s=e.match(/```(?:json)?\s*([\s\S]*?)```/),i=s?s[1].trim():e,n=i.indexOf("{"),r=i.lastIndexOf("}");if(n===-1||r===-1||r<=n)throw new Q("INVALID_STRUCTURE","输出中未找到 JSON 对象");try{return JSON.parse(i.slice(n,r+1))}catch(a){throw new Q("INVALID_STRUCTURE",`JSON 解析失败: ${a.message}`)}}function Ye(t,e){if(t.length>e.maxInputChars)throw new Q("INPUT_TOO_LARGE",`输入超过 ${e.maxInputChars} 字符,P0 不静默截断`,{length:t.length})}function At(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}class Vr{constructor(e,s=ci){this.llm=e,this.budgets=s}async generate(e,s={}){Ye(e,this.budgets);const i=At(),n=s.brief?{...s.brief}:me({goals:e});if(!s.skipIntentGate){const l=et(e,n);if(!l.clear)return be({requestId:i,questions:l.questions,brief:n,model:"intent-clarifier",latencyMs:0})}let r="",a=0,o=null;for(let l=0;l<=this.budgets.maxRetries;l++){l>0&&(a=l);const c=ni(e,l===0?void 0:r),u=Date.now();let d;try{d=await this.llm.complete({messages:[{role:"system",content:ii},{role:"user",content:c}],temperature:.2,maxTokens:this.budgets.maxTokens,timeoutMs:this.budgets.timeoutMs})}catch(m){if(m instanceof Q){if(l>=this.budgets.maxRetries)return{kind:"generate",schema:null,assumptions:[],clarifyingQuestions:[],intentSummary:"",validationIssues:[],meta:{requestId:i,promptVersion:Ie,model:"unknown",outputSchemaVersion:bt,latencyMs:Date.now()-u,retryCount:a,status:"error",errorCode:m.code}};r=m.message;continue}throw m}o={requestId:i,promptVersion:Ie,model:d.model,outputSchemaVersion:bt,latencyMs:d.latencyMs,promptTokens:d.promptTokens,completionTokens:d.completionTokens,costEstimate:d.costEstimate,retryCount:a,status:"ok"};let f;try{f=St(d.content)}catch(m){if(r=m.message,l>=this.budgets.maxRetries)return{kind:"generate",schema:null,assumptions:[],clarifyingQuestions:[],intentSummary:"",validationIssues:[],meta:{...o,status:"error",errorCode:"INVALID_STRUCTURE"}};continue}const g=Array.isArray(f.clarifyingQuestions)?f.clarifyingQuestions.filter(m=>String(m||"").trim()):[];if(g.length>0)return be({requestId:i,questions:It(g),brief:n,model:d.model,latencyMs:d.latencyMs,retryCount:a});const y=f.schema,_=z(y,{allowEmpty:!0,untrustedExpressions:!0});if(!_.valid){if(r=_.issues.map(m=>`${m.code}:${m.path}:${m.message}`).join("; "),l>=this.budgets.maxRetries)return{kind:"generate",schema:y,assumptions:Array.isArray(f.assumptions)?f.assumptions:[],clarifyingQuestions:[],intentSummary:String(f.intentSummary||""),validationIssues:_.issues,meta:{...o,status:"partial",errorCode:"VALIDATION_FAILED"},brief:n};continue}return{kind:"generate",schema:y,assumptions:Array.isArray(f.assumptions)?f.assumptions:[],clarifyingQuestions:[],intentSummary:String(f.intentSummary||""),validationIssues:[],meta:o,brief:n}}throw new Q("RETRY_EXHAUSTED","生成重试耗尽")}async edit(e){Ye(e.instruction+JSON.stringify(e.schema),this.budgets);const s=Gt(e.schema),i=Bt(e.instruction,s),n=e.requestId||At(),r=e.brief?{...e.brief}:me({goals:e.instruction});if(!e.skipIntentGate){const c=et(e.instruction,r);if(!c.clear)return be({requestId:n,questions:c.questions,brief:r,model:"intent-clarifier"})}const a=Yt(e.instruction,s,r);if(a.ambiguousLabels.length>0){const c=a.ambiguousLabels.join("、"),u=s.fields.filter(d=>a.ambiguousLabels.includes(d.label)).map(d=>`「${d.label}」(${d.key})`).join("、");return be({requestId:n,questions:[{id:`ambig_${n}`,prompt:`「${c}」对应多个字段:${u}。请指定完整标签或 key。`,reason:"field_reference_ambiguous"}],brief:r,model:"edit-task-contract"})}let o="",l=0;for(let c=0;c<=this.budgets.maxRetries;c++){c>0&&(l=c);const u=oi({schema:e.schema,instruction:e.instruction,baseVersion:e.baseVersion,brief:r,repairError:c===0?void 0:o});Ye(u,this.budgets);const d=Date.now();let f;try{f=await this.llm.complete({messages:[{role:"system",content:ri},{role:"user",content:u}],temperature:.2,maxTokens:this.budgets.maxTokens,timeoutMs:this.budgets.timeoutMs})}catch(v){if(v instanceof Q&&c>=this.budgets.maxRetries)return{kind:"edit",changeSet:null,systemRisks:[],modelRiskFlags:[],meta:{requestId:n,promptVersion:Ie,model:"unknown",outputSchemaVersion:_t,latencyMs:Date.now()-d,retryCount:l,status:"error",errorCode:v.code,errorMessage:v.message||v.code}};o=(v==null?void 0:v.message)||String(v);continue}const g={requestId:n,promptVersion:Ie,model:f.model,outputSchemaVersion:_t,latencyMs:f.latencyMs,promptTokens:f.promptTokens,completionTokens:f.completionTokens,costEstimate:f.costEstimate,retryCount:l,status:"ok"};let y;try{y=St(f.content)}catch(v){if(o=v.message,c>=this.budgets.maxRetries)return{kind:"edit",changeSet:null,systemRisks:[],modelRiskFlags:[],meta:{...g,status:"error",errorCode:"INVALID_STRUCTURE",errorMessage:o||"INVALID_STRUCTURE"}};continue}const _=Array.isArray(y.clarifyingQuestions)?y.clarifyingQuestions.filter(v=>String(v||"").trim()):[];if(_.length>0||y.kind==="clarification_required")return be({requestId:n,questions:It(_.length?_:(y.questions||[]).map(v=>v.prompt||v)),brief:r,model:f.model,latencyMs:f.latencyMs,retryCount:l});const m={requestId:String(y.requestId||n),baseVersion:String(y.baseVersion||e.baseVersion),intentSummary:String(y.intentSummary||""),assumptions:Array.isArray(y.assumptions)?y.assumptions:[],operations:Array.isArray(y.operations)?y.operations:[],riskFlags:Array.isArray(y.riskFlags)?y.riskFlags:[],suggestedTests:Array.isArray(y.suggestedTests)?y.suggestedTests:[],idempotencyKey:y.idempotencyKey,briefId:r.id,requirementIds:r.requirements};if(m.baseVersion!==e.baseVersion){if(o=`baseVersion 不匹配: got=${m.baseVersion} expected=${e.baseVersion}`,c>=this.budgets.maxRetries)return{kind:"edit",changeSet:m,systemRisks:[],modelRiskFlags:m.riskFlags,partial:!0,meta:{...g,status:"partial",errorCode:"VALIDATION_FAILED",errorMessage:o||"VALIDATION_FAILED"}};continue}const S=ne(e.schema,m,{expectedVersion:e.baseVersion});if(!S.ok||!S.nextSchema){if(o=(S.errors||[]).map(v=>typeof v=="string"?v:(v==null?void 0:v.message)||JSON.stringify(v)).join("; "),c>=this.budgets.maxRetries)return{kind:"edit",changeSet:m,dryRun:S,systemRisks:S.risks,modelRiskFlags:m.riskFlags,partial:!0,meta:{...g,status:"partial",errorCode:"CHANGESET_APPLY_FAILED",errorMessage:o||"CHANGESET_APPLY_FAILED"}};continue}const h=z(S.nextSchema,{allowEmpty:!0,untrustedExpressions:!0});if(!h.valid){if(o=h.issues.map(v=>v.message).join("; "),c>=this.budgets.maxRetries)return{kind:"edit",changeSet:m,dryRun:S,systemRisks:[...S.risks,...h.issues.map(v=>({code:v.code,severity:"high",message:v.message,path:v.path}))],modelRiskFlags:m.riskFlags,partial:!0,meta:{...g,status:"partial",errorCode:"VALIDATION_FAILED",errorMessage:o||"VALIDATION_FAILED"}};continue}const b=Zs(e.schema,S.nextSchema,i);if(b.status==="failed"){if(o=b.issues.map(v=>`${v.code}:${v.message}`).join("; "),c>=this.budgets.maxRetries)return{kind:"edit",changeSet:m,dryRun:S,systemRisks:[...S.risks,...b.issues.map(v=>({code:v.code,severity:"high",message:v.message}))],modelRiskFlags:m.riskFlags,explicitConstraintCheck:b,partial:!0,meta:{...g,status:"partial",errorCode:"VALIDATION_FAILED",errorMessage:o||"VALIDATION_FAILED"}};continue}const A=Pt(e.schema,S.nextSchema,S.diff);return{kind:"edit",changeSet:m,dryRun:S,systemRisks:A,modelRiskFlags:m.riskFlags,explicitConstraintCheck:b,meta:g}}throw new Q("RETRY_EXHAUSTED","编辑重试耗尽")}}class Fr{constructor(e=[]){this.turns=e,this.cursor=0}reset(){this.cursor=0}async complete(e){var n;const s=((n=[...e.messages].reverse().find(r=>r.role==="user"))==null?void 0:n.content)||"",i=this.turns.find(r=>r.match?typeof r.match=="string"?s.includes(r.match):r.match.test(s):!1)||this.turns[this.cursor++]||this.turns[this.turns.length-1];if(!i)throw new Q("PROVIDER_FAILED","fixture LLM 无可用响应");if(i.error)throw new Q(i.error.code,i.error.message);if(i.content==null)throw new Q("PROVIDER_FAILED","fixture LLM 缺少 content");return{content:i.content,model:i.model||e.model||"fixture-llm",latencyMs:i.latencyMs??1,promptTokens:i.promptTokens??Math.ceil(s.length/4),completionTokens:i.completionTokens??Math.ceil(i.content.length/4),costEstimate:i.costEstimate??0}}}function Kr(t,e="external"){return{async complete(s){var a;const i=((a=s.messages.find(o=>o.role==="system"))==null?void 0:a.content)||"",n=s.messages.filter(o=>o.role==="user").map(o=>o.content).join(`
|
|
60
|
+
`),r=Date.now();try{return{content:await t({system:i,user:n,temperature:s.temperature,maxTokens:s.maxTokens}),model:s.model||e,latencyMs:Date.now()-r}}catch(o){const l=(o==null?void 0:o.message)||String(o);throw/abort|timeout/i.test(l)?new Q("TIMEOUT",l):new Q("PROVIDER_FAILED",l)}}}}function Ke(t){let e="";return{update(s,i){return typeof s=="string"?e+=s:e+=Array.from(s,n=>String.fromCharCode(n)).join(""),this},digest(s){let i=2166136261;for(let n=0;n<e.length;n++)i^=e.charCodeAt(n),i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0").repeat(8).slice(0,64)}}}const Ht=/^(prompt|messages|rawOutput|content|password|secret|token|authorization|idcard|mobile|phone|bank)$/i,Et=new Set(["requestId","briefId","requirementIds","provider","model","promptHash","promptVersion","outputSchemaVersion","latencyMs","promptTokens","completionTokens","costEstimate","decision","confidence","riskSummary","outcome","createdAt"]),ui=/(\d{15,18})|(1[3-9]\d{9})|(密码|身份证|银行卡)/;function di(t){return Ke().update(String(t||""),"utf8").digest("hex")}function Le(t,e){if(e&&Et.has(e))return t;if(typeof t=="string")return ui.test(t)||t.length>200?"[redacted]":t;if(Array.isArray(t))return t.map(s=>Le(s));if(t&&typeof t=="object"){const s={};for(const[i,n]of Object.entries(t)){if(Ht.test(i)&&!Et.has(i)){s[i]="[redacted]";continue}s[i]=Le(n,i)}return s}return t}function Pr(t){const e={requestId:t.meta.requestId,briefId:t.briefId,requirementIds:t.requirementIds,provider:t.provider||"fixture",model:t.meta.model,promptHash:di(t.promptContent),promptVersion:t.meta.promptVersion,outputSchemaVersion:t.meta.outputSchemaVersion,latencyMs:t.meta.latencyMs,promptTokens:t.meta.promptTokens,completionTokens:t.meta.completionTokens,costEstimate:t.meta.costEstimate,decision:t.decision,confidence:t.confidence,riskSummary:t.riskSummary,outcome:t.outcome,createdAt:new Date().toISOString()},s=Le(e);if(delete s.prompt,delete s.rawOutput,delete s.messages,delete s.content,t.extra){const i=Le(t.extra);for(const n of Object.keys(i))Ht.test(n)}return s}function qr(t,e=[]){const s=JSON.stringify(t);if(/"prompt"\s*:/.test(s)||/"rawOutput"\s*:/.test(s)||/"messages"\s*:/.test(s))throw new Error("redacted record contains forbidden raw fields");for(const i of e)if(i&&s.includes(i))throw new Error("redacted record leaked sensitive substring")}function Se(t){const e=String(t||"d0"),s=/^d(\d+)$/.exec(e);return`d${(s?Number(s[1]):0)+1}`}function tt(t){return{draftId:t||`draft_${Date.now()}`,draftRevision:"d0",origins:[],pendingSuggestion:null}}const fi={$schemaComment:"Runtime catalog loaded via catalogBuiltin.ts. No production URLs or secrets.",catalogVersion:"2026-09-18.design.1",entries:[{id:"control.select",version:"1.0.0",kind:"control",status:"available",title:{"zh-CN":"下拉选择",aliases:["选择","单选"]},purpose:"基础下拉。选项为本地示例,不是生产字典。",parameters:{label:{type:"string",default:"请选择"}},keyContract:{preferredKey:"choice",onConflict:"suffix"},emits:{item:{type:"select",label:"{{label}}",required:!1,options:[{label:"选项一",value:"a"},{label:"选项二",value:"b"}]}},dependencies:{data:"none"},capabilities:{controls:["select"],trial:"ok-local"},maintainer:"repo-static"},{id:"control.phone",version:"1.0.0",kind:"control",status:"available",title:{"zh-CN":"手机号",aliases:["电话","手机"]},purpose:"基础手机号控件。必填默认关闭。",parameters:{label:{type:"string",default:"手机号"},required:{type:"boolean",default:!1}},keyContract:{preferredKey:"mobile",onConflict:"suffix"},emits:{item:{type:"phone",label:"{{label}}",required:"{{required}}",placeholder:"请输入手机号"}},dependencies:{data:"none"},capabilities:{controls:["phone"],trial:"ok-local"},maintainer:"repo-static"},{id:"control.input",version:"1.0.0",kind:"control",status:"available",title:{"zh-CN":"单行输入",aliases:["文本框","输入框"]},purpose:"基础单行文本控件,无业务数据依赖。",parameters:{label:{type:"string",default:"文本"}},keyContract:{preferredKey:"textField",onConflict:"suffix"},emits:{item:{type:"input",label:"{{label}}",required:!1,placeholder:"请输入"}},dependencies:{data:"none"},capabilities:{controls:["input"],trial:"ok-local"},maintainer:"repo-static"},{id:"field.email",version:"1.0.0",kind:"field",status:"available",title:{"zh-CN":"邮箱录入",aliases:["电子邮箱","邮件"]},purpose:"采集联系邮箱;格式规则为建议项,是否必填由作者决定。",parameters:{required:{type:"boolean",default:!1},label:{type:"string",default:"邮箱"}},keyContract:{preferredKey:"email",onConflict:"suffix"},emits:{item:{type:"input",label:"{{label}}",required:"{{required}}",placeholder:"请输入邮箱",rules:[{type:"regex",regex:"^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$",message:"请输入有效邮箱",trigger:"blur",policy:"suggested"}]}},dependencies:{data:"none"},capabilities:{controls:["input"],trial:"ok-local"},examples:[{input:"user@example.com",expect:"pass"},{input:"bad@",expect:"fail"}],maintainer:"docs/design/fixtures"},{id:"field.occupation",version:"1.0.0",kind:"field",status:"available",title:{"zh-CN":"职业选择",aliases:["职业","工种"]},purpose:"从受控选项中选择职业;真实字典 API 为 TBD,首版仅本地模拟选项。",parameters:{required:{type:"boolean",default:!1},label:{type:"string",default:"职业"}},keyContract:{preferredKey:"occupation",onConflict:"suffix"},emits:{item:{type:"select",label:"{{label}}",required:"{{required}}",placeholder:"请选择职业",props:{options:[{label:"受雇",value:"employed"},{label:"自雇",value:"self_employed"},{label:"学生",value:"student"},{label:"其他",value:"other"}]}}},dependencies:{data:"mock-local",note:"真实职业字典 TBD;禁止 AI 编造为已确认业务枚举"},capabilities:{controls:["select"],trial:"ok-mock"},examples:[{input:"employed",expect:"pass"}],maintainer:"docs/design/fixtures"},{id:"module.basicProfile",version:"1.0.0",kind:"module",status:"available",title:{"zh-CN":"基本信息",aliases:["申请人基本信息"]},purpose:"常用身份与联系候选字段;加入前可去掉 suggested 项;必填不自动判定。",parameters:{includeAddress:{type:"boolean",default:!0,policy:"suggested"},includeOccupation:{type:"boolean",default:!0,policy:"suggested"}},keyContract:{groupKey:"g_basic_profile",onConflict:"suffix"},emits:{group:{key:"g_basic_profile",title:"基本信息",items:[{ref:"inline",key:"applicantName",type:"input",label:"姓名",required:!1,policy:"suggested"},{ref:"inline",key:"mobile",type:"phone",label:"手机号",required:!1,policy:"suggested"},{ref:"inline",key:"address",type:"address",label:"住址",required:!1,policy:"suggested",whenParam:"includeAddress",dependencies:{data:"needs-config"}},{refCatalog:"field.occupation@1.0.0",whenParam:"includeOccupation"}]}},dependencies:{data:"mixed",note:"住址真实级联 TBD → needs-config 时标不可试填"},capabilities:{controls:["input","phone","address","select"],trial:"partial"},examples:[],maintainer:"docs/design/fixtures"},{id:"module.emergencyContact",version:"1.0.0",kind:"module",status:"available",title:{"zh-CN":"紧急联系人",aliases:["紧急联络人"]},purpose:"固定三人字段(姓名、关系、电话)。多个联系人请用 list 预设,勿与本模块混称。",parameters:{},keyContract:{groupKey:"g_emergency",keyPrefix:"emergency",onConflict:"suffix"},emits:{group:{key:"g_emergency",title:"紧急联系人",items:[{key:"emergencyName",type:"input",label:"姓名",required:!1},{key:"emergencyRelationship",type:"select",label:"关系",required:!1,props:{options:[{label:"配偶",value:"spouse"},{label:"父母",value:"parent"},{label:"子女",value:"child"},{label:"朋友",value:"friend"},{label:"其他",value:"other"}]}},{key:"emergencyMobile",type:"phone",label:"电话号码",required:!1}]}},dependencies:{data:"none"},capabilities:{controls:["input","select","phone"],trial:"ok-local"},not:["list-repeatable"],examples:[],maintainer:"docs/design/fixtures"},{id:"module.companySearch",version:"0.1.0",kind:"module",status:"available",title:{"zh-CN":"公司搜索",aliases:["企业搜索","单位查询"]},purpose:"搜索公司并可能回填信用代码等;多输出值契约。真实 API TBD。",parameters:{includeCreditCode:{type:"boolean",default:!0}},keyContract:{groupKey:"g_company",onConflict:"suffix"},emits:{group:{key:"g_company",title:"单位信息",items:[{key:"companyName",type:"search",label:"公司名称",required:!1,props:{searchApi:null},dependencies:{data:"needs-config"}},{key:"creditCode",type:"input",label:"统一社会信用代码",required:!1,whenParam:"includeCreditCode",valueContract:"filled-by-search-selection"}]}},dependencies:{data:"needs-config",note:"首版卡片可加入结构,试填显示不可试填;禁止生产 URL"},capabilities:{controls:["search","input"],trial:"blocked-until-config"},examples:[],maintainer:"docs/design/fixtures"}]},Qt=fi;let fe=[];const Pe=new Map;function Wt(t,e){return`${t}@${e}`}function Rt(t){const e=Pe.get(Wt(t.id,t.version));return e?{...t,status:e}:t}function Ur(){return Qt}function jr(){return fe.map(t=>({...t}))}function Gr(t){if(t.status==="available"||t.status==="retired")throw new Error("LOCAL_DRAFT_CANNOT_SET_AVAILABLE");const e={...t,status:"draft"},s=fe.findIndex(i=>i.id===e.id&&i.version===e.version);return s>=0?fe[s]=e:fe.push(e),{...e}}function zt(t){const e=!!(t!=null&&t.includeRetired);return[...Qt.entries.map(Rt).filter(i=>e||i.status!=="retired"),...fe.map(Rt)]}function Re(t,e){const s=zt({includeRetired:!0});if(e)return s.find(a=>a.id===t&&a.version===e)||null;const i=s.filter(a=>a.id===t);if(!i.length)return null;const n=i.filter(a=>a.status==="available");return(n.length?n:i).slice().sort((a,o)=>String(o.version).localeCompare(String(a.version)))[0]||null}function gi(t){var s,i,n,r;const e=((s=t.capabilities)==null?void 0:s.trial)||((i=t.dependencies)==null?void 0:i.data)||"unknown";return e==="blocked-until-config"||e==="needs-config"||((n=t.dependencies)==null?void 0:n.data)==="needs-config"?"不可试填 · 待配置":e==="ok-mock"||((r=t.dependencies)==null?void 0:r.data)==="mock-local"?"可试填 · 本地模拟":e==="partial"?"部分可试填":e==="ok-local"?"可试填 · 本地":String(e)}function Br(t,e){var a,o;const s=String(t||"").trim().toLowerCase(),i=e==null?void 0:e.kinds,n=zt({includeRetired:!1}).filter(l=>!(l.status==="retired"||l.status==="draft"&&!(e!=null&&e.includeDraft)||l.status!=="available"&&l.status!=="draft"&&l.status!=="reviewed"||!(e!=null&&e.includeDraft)&&l.status!=="available"||i&&!i.includes(l.kind))),r=[];for(const l of n){const c=((a=l.title)==null?void 0:a["zh-CN"])||"",u=((o=l.title)==null?void 0:o.aliases)||[],d=[l.id,c,l.purpose,...u].join(" ").toLowerCase();let f=0;if(!s)f=1;else if(l.id.toLowerCase()===s)f=100;else if(c.toLowerCase()===s)f=90;else if(d.includes(s))f=50;else continue;r.push({entry:l,score:f,trialLabel:gi(l)})}return r.sort((l,c)=>c.score-l.score||l.entry.id.localeCompare(c.entry.id))}function pi(t,e,s){return t.status==="retired"&&e!=="retired"?{ok:!1,code:"RETIRED_IMMUTABLE",message:"已停用条目不可恢复为可新建"}:e==="available"&&!(s!=null&&s.allowPromoteAvailable)?{ok:!1,code:"PROMOTE_REQUIRES_REPO",message:"本地不可将条目设为 available;须经仓库审查"}:e==="retired"?{ok:!0,entry:{...t,status:"retired"}}:{ok:!0,entry:{...t,status:e}}}function Yr(t,e){const s=pi(t,e);if(!s.ok)return s;Pe.set(Wt(s.entry.id,s.entry.version),s.entry.status);const i=fe.findIndex(n=>n.id===s.entry.id&&n.version===s.entry.version);return i>=0&&(fe[i]={...s.entry}),hi(),s}const Xt="formstudio.catalog.localStatusOverlay.v1";function hi(t){const e=t||(typeof globalThis<"u"&&globalThis.localStorage?globalThis.localStorage:null);if(!e)return;const s={};for(const[i,n]of Pe.entries())s[i]=n;try{e.setItem(Xt,JSON.stringify(s))}catch{}}function Jr(t){const e=t||(typeof globalThis<"u"&&globalThis.localStorage?globalThis.localStorage:null);if(e)try{const s=e.getItem(Xt);if(!s)return;const i=JSON.parse(s);for(const[n,r]of Object.entries(i||{}))(r==="retired"||r==="draft"||r==="reviewed"||r==="available")&&Pe.set(n,r)}catch{}}function st(t){return JSON.parse(JSON.stringify(t))}function Ve(t,e){if(!e.has(t))return t;let s=2;for(;e.has(`${t}_${s}`);)s+=1;return`${t}_${s}`}function mi(t){const e=new Set;for(const s of(t==null?void 0:t.groups)||[]){s!=null&&s.key&&e.add(String(s.key));for(const i of(s==null?void 0:s.items)||[])i!=null&&i.key&&e.add(String(i.key))}return e}function we(t,e){if(t==null)return t;if(typeof t=="string"){const s=/^\{\{(\w+)\}\}$/.exec(t);if(s){const i=s[1];return Object.prototype.hasOwnProperty.call(e,i)?e[i]:""}return t.replace(/\{\{(\w+)\}\}/g,(i,n)=>{const r=e[n];return r==null?"":String(r)})}if(Array.isArray(t))return t.map(s=>we(s,e));if(typeof t=="object"){const s={};for(const[i,n]of Object.entries(t))i!=="policy"&&(s[i]=we(n,e));return s}return t}function wt(t){t.required==="true"&&(t.required=!0),t.required==="false"&&(t.required=!1),t.disabled==="true"&&(t.disabled=!0),t.disabled==="false"&&(t.disabled=!1),t.readonly==="true"&&(t.readonly=!0),t.readonly==="false"&&(t.readonly=!1)}function Zt(t){const e={},s=t.parameters||{};for(const[i,n]of Object.entries(s))n&&typeof n=="object"&&"default"in n&&(e[i]=n.default);return e}function Tt(t,e,s){var r,a;if(t!=null&&t.whenParam&&!e[t.whenParam])return null;if(t!=null&&t.refCatalog){const[o,l]=String(t.refCatalog).split("@"),c=Re(o,l);if(!c)throw Object.assign(new Error(`嵌套目录缺失: ${t.refCatalog}`),{code:"NESTED_CATALOG_MISSING"});if(c.status!=="available")throw Object.assign(new Error(`嵌套目录不可用: ${t.refCatalog} (${c.status})`),{code:"NESTED_CATALOG_NOT_AVAILABLE"});if(c.version!==l)throw Object.assign(new Error(`嵌套目录版本不匹配: ${t.refCatalog}`),{code:"NESTED_CATALOG_VERSION_MISMATCH"});const u={...Zt(c),...e},d=(r=c.emits)==null?void 0:r.item;if(!d)throw Object.assign(new Error(`嵌套目录缺少 emits.item: ${t.refCatalog}`),{code:"NESTED_CATALOG_EMIT_MISSING"});const f=we(st(d),u),g=((a=c.keyContract)==null?void 0:a.preferredKey)||f.key||c.id.replace(/\W+/g,"_");return f.key=Ve(String(g),s),s.add(f.key),delete f.policy,wt(f),f}const i=we(st(t),e),n=i.key||"field";return i.key=Ve(String(n),s),s.add(i.key),delete i.policy,delete i.ref,delete i.whenParam,delete i.refCatalog,delete i.dependencies,delete i.valueContract,wt(i),i}function es(t){var d,f,g,y,_,m,S;const e=Re(t.catalog.catalogId,t.catalog.catalogVersion);if(!e)return{ok:!1,code:"CATALOG_NOT_FOUND",message:"目录条目不存在"};if(e.status==="retired")return{ok:!1,code:"CATALOG_RETIRED",message:"已停用条目不可新建"};if(e.status!=="available")return{ok:!1,code:"CATALOG_NOT_AVAILABLE",message:`条目状态为 ${e.status},不可实例化到草稿`};if(e.version!==t.catalog.catalogVersion)return{ok:!1,code:"CATALOG_VERSION_MISMATCH",message:`请求版本 ${t.catalog.catalogVersion} 与解析版本 ${e.version} 不一致`};const s={...Zt(e),...t.params||{}},i=new Set((t.omitPreferredKeys||[]).map(String)),n=t.schema?st(t.schema):{version:"1",groups:[],apis:[]};Array.isArray(n.groups)||(n.groups=[]),Array.isArray(n.apis)||(n.apis=[]),n.groups=n.groups.filter(h=>Array.isArray(h.items)&&h.items.length>0);const r=mi(n),a=[],o=[],l=new Date().toISOString(),c={catalogId:e.id,catalogVersion:e.version};if((((d=e.dependencies)==null?void 0:d.data)==="needs-config"||((f=e.capabilities)==null?void 0:f.trial)==="blocked-until-config")&&o.push("待配置数据源:结构可加入,试填不可用,未声明生产 API"),e.kind==="field"||e.kind==="control"){const h=(g=e.emits)==null?void 0:g.item;if(!h)return{ok:!1,code:"CATALOG_EMIT_MISSING",message:"字段条目缺少 emits.item"};let b;try{b=Tt({...h,key:(y=e.keyContract)==null?void 0:y.preferredKey},s,r)}catch(v){return{ok:!1,code:(v==null?void 0:v.code)||"NESTED_CATALOG_ERROR",message:(v==null?void 0:v.message)||"字段实例化失败"}}if(!b)return{ok:!1,code:"CATALOG_EMIT_EMPTY",message:"字段实例为空"};let A=t.targetGroupKey?n.groups.find(v=>v.key===t.targetGroupKey):n.groups[0];if(!A){const v=Ve("g_main",r);r.add(v),A={key:v,title:"表单",items:[]},n.groups.push(A)}A.items=[...A.items||[],b],a.push({target:{kind:"field",key:b.key},catalog:c,params:s,insertedAt:l})}else if(e.kind==="module"){const h=(_=e.emits)==null?void 0:_.group;if(!h)return{ok:!1,code:"CATALOG_EMIT_MISSING",message:"模块条目缺少 emits.group"};const b=((m=e.keyContract)==null?void 0:m.groupKey)||h.key||e.id.replace(/\W+/g,"_"),A=Ve(String(b),r);r.add(A);const v=[];for(const w of h.items||[]){const P=w!=null&&w.refCatalog?String(w.refCatalog).split("@")[0]:String(w.key||""),E=w!=null&&w.refCatalog?(S=Re(String(w.refCatalog).split("@")[0],String(w.refCatalog).split("@")[1]))==null?void 0:S.keyContract:void 0,V=(E==null?void 0:E.preferredKey)||w.key||P;if(V&&i.has(String(V)))continue;if(w!=null&&w.refCatalog){const q=String(w.refCatalog).split("@")[0];if(i.has(q))continue}let j;try{j=Tt(w,s,r)}catch(q){return{ok:!1,code:(q==null?void 0:q.code)||"NESTED_CATALOG_ERROR",message:(q==null?void 0:q.message)||"嵌套目录解析失败"}}j&&(v.push(j),a.push({target:{kind:"field",key:j.key},catalog:c,params:s,insertedAt:l}))}const k={key:A,title:we(h.title||e.title["zh-CN"],s),items:v};n.groups.push(k),a.push({target:{kind:"group",key:A},catalog:c,params:s,insertedAt:l})}else return{ok:!1,code:"CATALOG_KIND_UNSUPPORTED",message:`不支持的目录类型: ${e.kind}`};const u=z(n,{allowEmpty:!0});return u.valid?{ok:!0,nextSchema:n,origins:a,warnings:o}:{ok:!1,code:"SCHEMA_INVALID",message:(u.issues||[]).map(h=>h.message||h.code).join("; ")||"Schema 校验失败"}}function Hr(t){var r,a,o,l,c,u,d,f,g,y,_,m,S,h,b,A;const e=es({schema:{version:"1",groups:[],apis:[]},catalog:t.catalog,params:t.params});if(!e.ok)return e;const s=Re(t.catalog.catalogId,t.catalog.catalogVersion);if(!s)return{ok:!1,code:"CATALOG_NOT_FOUND",message:"目录条目不存在"};const i=[];if(s.kind==="module"){const v=(r=s.emits)==null?void 0:r.group;for(const k of(v==null?void 0:v.items)||[])if(k!=null&&k.refCatalog){const[w,P]=String(k.refCatalog).split("@"),E=Re(w,P),V=((a=E==null?void 0:E.keyContract)==null?void 0:a.preferredKey)||w.replace(/\W+/g,"_"),j=(E==null?void 0:E.parameters)&&typeof E.parameters.required=="object"&&((o=E.parameters.required)==null?void 0:o.default);i.push({preferredKey:String(V),label:String(((l=E==null?void 0:E.title)==null?void 0:l["zh-CN"])||V),type:String(((u=(c=E==null?void 0:E.emits)==null?void 0:c.item)==null?void 0:u.type)||"input"),required:j===!0,suggested:!0,fromRef:String(k.refCatalog),omitKey:String(V)})}else i.push({preferredKey:String(k.key||"field"),label:String(k.label||k.key||"field"),type:String(k.type||"input"),required:k.required===!0,suggested:!0,omitKey:String(k.key||"field")})}else{const v=((d=s.keyContract)==null?void 0:d.preferredKey)||((g=(f=s.emits)==null?void 0:f.item)==null?void 0:g.key)||s.id.replace(/\W+/g,"_");i.push({preferredKey:String(v),label:String(((y=s.title)==null?void 0:y["zh-CN"])||v),type:String(((m=(_=s.emits)==null?void 0:_.item)==null?void 0:m.type)||"input"),required:!1,suggested:!0,omitKey:String(v)})}const n=((S=s.dependencies)==null?void 0:S.data)==="needs-config"||((h=s.capabilities)==null?void 0:h.trial)==="blocked-until-config"?"不可试填 · 待配置":((b=s.dependencies)==null?void 0:b.data)==="mock-local"?"可试填 · 本地模拟":"可试填 · 本地";return{ok:!0,preview:{catalogId:s.id,catalogVersion:s.version,title:((A=s.title)==null?void 0:A["zh-CN"])||s.id,purpose:s.purpose,trialLabel:n,warnings:e.warnings,candidates:i,objectCount:i.length+(s.kind==="module"?1:0),dependencies:s.dependencies}}}function it(t){return JSON.parse(JSON.stringify(t))}function yi(t){t.pendingSuggestion&&t.pendingSuggestion.status==="active"&&t.pendingSuggestion.baseDraftRevision!==t.draftRevision&&(t.pendingSuggestion.status="stale")}function ce(t){return t.draftRevision=Se(t.draftRevision),yi(t),t.draftRevision}function ki(t,e){var n,r;const s=it(t.meta);let i=t.schema?it(t.schema):null;if(e.type==="discardSuggestion")return s.pendingSuggestion=null,{ok:!0,draftRevision:s.draftRevision,schema:i,meta:s};if(e.type==="recomputeSuggestion")return s.pendingSuggestion&&(s.pendingSuggestion=null),{ok:!0,draftRevision:s.draftRevision,schema:i,meta:s};if(e.type==="insertCatalogEntry"){const a=es({schema:i,catalog:e.catalog,params:e.params,targetGroupKey:e.targetGroupKey,omitPreferredKeys:e.omitPreferredKeys});return a.ok?(i=a.nextSchema,s.origins=[...s.origins,...a.origins],{ok:!0,draftRevision:ce(s),schema:i,meta:s}):{ok:!1,code:a.code,message:a.message}}if(e.type==="addGroup"){i||(i={version:"1",groups:[],apis:[]});const a=new Set;for(const u of i.groups||[]){u.key&&a.add(u.key);for(const d of u.items||[])d.key&&a.add(d.key)}let o=e.groupKey||"g_main";if(a.has(o)){let u=2;for(;a.has(`${o}_${u}`);)u+=1;o=`${o}_${u}`}i.groups=[...i.groups||[],{key:o,title:e.title||"分组",items:[]}];const l=z(i,{allowEmpty:!0});return l.valid?{ok:!0,draftRevision:ce(s),schema:i,meta:s}:{ok:!1,code:"SCHEMA_INVALID",message:(l.issues||[]).map(u=>u.message||u.code).join("; ")}}if(e.type==="addField"){if(!i)return{ok:!1,code:"NO_SCHEMA",message:"当前没有草稿 Schema"};const a=(i.groups||[]).find(f=>f.key===e.groupKey);if(!a)return{ok:!1,code:"GROUP_NOT_FOUND",message:`分组不存在: ${e.groupKey}`};const o=new Set;for(const f of i.groups||[])for(const g of f.items||[])g.key&&o.add(g.key);let l=String(e.item.key||e.item.type||"field");if(o.has(l)){let f=2;for(;o.has(`${l}_${f}`);)f+=1;l=`${l}_${f}`}const c={...e.item,key:l,type:e.item.type,label:e.item.label||l,required:e.item.required===!0};a.items=[...a.items||[],c];const u=z(i,{allowEmpty:!0});return u.valid?{ok:!0,draftRevision:ce(s),schema:i,meta:s}:{ok:!1,code:"SCHEMA_INVALID",message:(u.issues||[]).map(f=>f.message||f.code).join("; ")}}if(e.type==="patchField"){if(!i)return{ok:!1,code:"NO_SCHEMA",message:"当前没有草稿 Schema"};let a=!1;for(const c of i.groups||[]){const u=c.items||[];for(let d=0;d<u.length;d++)if(u[d].key===e.fieldKey){u[d]={...u[d],...e.patch,key:u[d].key},a=!0;break}if(a)break}if(!a)return{ok:!1,code:"FIELD_NOT_FOUND",message:`字段不存在: ${e.fieldKey}`};const o=z(i,{allowEmpty:!0});return o.valid?{ok:!0,draftRevision:ce(s),schema:i,meta:s}:{ok:!1,code:"SCHEMA_INVALID",message:(o.issues||[]).map(c=>c.message||c.code).join("; ")}}if(e.type==="patchGroup"){if(!i)return{ok:!1,code:"NO_SCHEMA",message:"当前没有草稿 Schema"};const a=(i.groups||[]).find(c=>c.key===e.groupKey);if(!a)return{ok:!1,code:"GROUP_NOT_FOUND",message:`分组不存在: ${e.groupKey}`};Object.assign(a,e.patch,{key:a.key,items:a.items});const o=z(i,{allowEmpty:!0});return o.valid?{ok:!0,draftRevision:ce(s),schema:i,meta:s}:{ok:!1,code:"SCHEMA_INVALID",message:(o.issues||[]).map(c=>c.message||c.code).join("; ")}}if(e.type==="removeField"){if(!e.confirmHighImpact)return{ok:!1,code:"HIGH_IMPACT_CONFIRM_REQUIRED",message:"删除字段需确认"};if(!i)return{ok:!1,code:"NO_SCHEMA",message:"当前没有草稿 Schema"};const a=[];for(const u of i.groups||[])for(const d of u.items||[])(d.relations||[]).forEach((f,g)=>{f&&f.target===e.fieldKey&&a.push({sourceKey:d.key,relationIndex:g,effect:f.effect})});if(a.length>0&&!e.clearInboundRelations)return{ok:!1,code:"RELATION_INBOUND_BLOCKED",message:`字段被联动引用,删除前须确认清理:${a.map(d=>`${d.sourceKey}→${e.fieldKey}${d.effect?`(${d.effect})`:""}`).join("; ")}`};if(a.length>0&&e.clearInboundRelations)for(const u of i.groups||[])for(const d of u.items||[])Array.isArray(d.relations)&&(d.relations=d.relations.filter(f=>(f==null?void 0:f.target)!==e.fieldKey));let o=!1;for(const u of i.groups||[]){const d=((n=u.items)==null?void 0:n.length)||0;u.items=(u.items||[]).filter(f=>f.key!==e.fieldKey),(((r=u.items)==null?void 0:r.length)||0)<d&&(o=!0)}if(!o)return{ok:!1,code:"FIELD_NOT_FOUND",message:`字段不存在: ${e.fieldKey}`};s.origins=s.origins.filter(u=>!(u.target.kind==="field"&&u.target.key===e.fieldKey));const l=z(i,{allowEmpty:!0});return l.valid?{ok:!0,draftRevision:ce(s),schema:i,meta:s}:{ok:!1,code:"SCHEMA_INVALID",message:(l.issues||[]).map(u=>u.message||u.code).join("; ")}}if(e.type==="reorder"){if(!i)return{ok:!1,code:"NO_SCHEMA",message:"当前没有草稿 Schema"};if(e.scope==="groups"){const l=[...i.groups||[]];if(e.from<0||e.to<0||e.from>=l.length||e.to>=l.length)return{ok:!1,code:"REORDER_OOB",message:"分组重排越界"};const[c]=l.splice(e.from,1);l.splice(e.to,0,c),i.groups=l}else{if(!e.parentKey)return{ok:!1,code:"PARENT_KEY_REQUIRED",message:"字段重排必须指定 parentKey,不得回退到首组"};const l=(i.groups||[]).find(d=>d.key===e.parentKey);if(!l)return{ok:!1,code:"GROUP_NOT_FOUND",message:`找不到分组: ${e.parentKey}`};const c=[...l.items||[]];if(e.from<0||e.to<0||e.from>=c.length||e.to>=c.length)return{ok:!1,code:"REORDER_OOB",message:"字段重排越界"};const[u]=c.splice(e.from,1);c.splice(e.to,0,u),l.items=c}const a=z(i,{allowEmpty:!0});return a.valid?{ok:!0,draftRevision:ce(s),schema:i,meta:s}:{ok:!1,code:"SCHEMA_INVALID",message:(a.issues||[]).map(l=>l.message||l.code).join("; ")}}return{ok:!1,code:"UNKNOWN_COMMAND",message:"未知草稿命令"}}function _i(t,e){const s=it(t);return s.pendingSuggestion={baseDraftRevision:e.baseDraftRevision,status:"active",createdAt:e.createdAt||new Date().toISOString()},s}function bi(t){const e=t.pendingSuggestion;return e?e.status==="stale"||e.baseDraftRevision!==t.draftRevision?{ok:!1,code:"STALE_SUGGESTION",message:"草稿已变更,请基于当前草稿重算建议",staleSuggestion:!0}:{ok:!0}:{ok:!1,code:"NO_PENDING",message:"没有待采纳建议"}}function C(t){return JSON.parse(JSON.stringify(t))}function vi(t){return t.some(e=>e.severity==="high")}class Ii{constructor(e=null,s="2.0"){this.brief=null,this.pending=null,this.history=[],this.seenRequestIds=new Set,this.lastDiscarded=[],this.aiRuns=[],this.clarification=null,this.authoringMeta=tt(),this.schema=e?C(e):null,this.version=s}snapshot(){return{schema:this.schema?C(this.schema):null,version:this.version,brief:this.brief?C(this.brief):null,pending:this.pending?C(this.pending):null,history:C(this.history),discardedPreviewValues:[...this.lastDiscarded],aiRuns:C(this.aiRuns),clarification:this.clarification?C(this.clarification):null,authoringMeta:C(this.authoringMeta)}}getAuthoringMeta(){return C(this.authoringMeta)}setAuthoringMeta(e){this.authoringMeta=C(e)}dispatchDraft(e){var i;const s=ki({schema:this.schema,meta:this.authoringMeta},e);return s.ok?(s.schema!==void 0&&(this.schema&&this.history.push({version:this.version,schema:C(this.schema),label:e.type,authoringMeta:C(this.authoringMeta),pending:this.pending?C(this.pending):null}),this.schema=s.schema?C(s.schema):null,this.schema&&(this.version=String(this.schema.version||this.version||"1"))),s.meta&&(this.authoringMeta=C(s.meta)),this.pending&&((i=this.authoringMeta.pendingSuggestion)==null?void 0:i.status)==="stale"&&(this.pending={...this.pending,suggestionStatus:"stale"}),(e.type==="discardSuggestion"||e.type==="recomputeSuggestion")&&(this.pending=null),{ok:!0,draftRevision:this.authoringMeta.draftRevision}):s}setBrief(e){this.brief=C(e)}applyClarification(e){this.brief=C(e.brief),this.clarification=C(e.questions)}answerQuestions(e){const s=this.brief||{id:`brief_${Date.now()}`,answers:{},unresolvedQuestions:[]},i=ai(s,e);return this.brief=C(i),this.clarification=(i.unresolvedQuestions||[]).length>0?C(i.unresolvedQuestions):null,C(i)}recordAiRun(e){this.aiRuns.push(C(e))}replaceSchema(e,s,i="replace"){this.schema&&this.history.push({version:this.version,schema:C(this.schema),label:i}),this.schema=C(e),this.version=s||String(e.version||this.version),this.pending=null}restoreSchemaSnapshot(e){this.schema=e.schema?C(e.schema):null,this.version=e.version,this.pending=e.pending?C(e.pending):null,this.history=C(e.history)}propose(e){const s=qt(e.changeSet,e.dryRun,this.version),i=e.systemRisks||[],n=e.dryRun.risks||[],r=i.length>0?[...i,...n.filter(l=>!i.some(c=>c.code===l.code&&c.path===l.path))]:n.length>0?[...n]:[],a=new Date().toISOString(),o=this.authoringMeta.draftRevision;this.pending={changeSet:C(s),dryRun:C(e.dryRun),systemRisks:C(r),modelRiskFlags:C(e.modelRiskFlags||e.changeSet.riskFlags||[]),createdAt:a,baseDraftRevision:o,suggestionStatus:"active",...e.explicitConstraintCheck?{explicitConstraintCheck:C(e.explicitConstraintCheck)}:{}},this.authoringMeta=_i(this.authoringMeta,{baseDraftRevision:o,createdAt:a}),this.clarification=null}rejectPending(){return this.pending=null,this.authoringMeta={...this.authoringMeta,pendingSuggestion:null},{ok:!0}}applyPending(e={}){var a;if(!this.pending)return{ok:!1,error:"NO_PENDING"};if(this.authoringMeta.pendingSuggestion){const o=bi(this.authoringMeta);if(!o.ok)return{ok:!1,error:o.code||"STALE_SUGGESTION"}}if(this.pending.suggestionStatus==="stale")return{ok:!1,error:"STALE_SUGGESTION"};if(((a=this.pending.explicitConstraintCheck)==null?void 0:a.status)==="failed")return{ok:!1,error:"CONSTRAINT_FAILED"};const s=this.pending.systemRisks||[];if(vi(s)&&!e.confirmHighRisk)return{ok:!1,requiresConfirm:!0,error:"HIGH_RISK_CONFIRM_REQUIRED"};if(!this.pending.dryRun.ok||!this.pending.dryRun.nextSchema)return{ok:!1,error:"DRY_RUN_INVALID"};const i=this.pending.changeSet.requestId,n=this.pending.changeSet.idempotencyKey;if(i&&this.seenRequestIds.has(i)||n&&this.seenRequestIds.has(n))return{ok:!1,error:"DUPLICATE_REQUEST"};if(!this.schema)return i&&this.seenRequestIds.add(i),n&&this.seenRequestIds.add(n),this.schema=C(this.pending.dryRun.nextSchema),this.version="1",this.schema={...this.schema,version:this.version},this.pending=null,this.authoringMeta={...this.authoringMeta,pendingSuggestion:null,draftRevision:Se(this.authoringMeta.draftRevision)},{ok:!0};const r=ne(this.schema,this.pending.changeSet,{expectedVersion:this.version,seenRequestIds:this.seenRequestIds});return!r.ok||!r.nextSchema?{ok:!1,error:r.errors.map(o=>o.message).join("; ")}:(this.history.push({version:this.version,schema:C(this.schema),label:this.pending.changeSet.intentSummary||"apply"}),i&&this.seenRequestIds.add(i),n&&this.seenRequestIds.add(n),this.schema=C(r.nextSchema),this.version=`${this.version}-r${this.history.length}`,this.schema={...this.schema,version:this.version},this.pending=null,this.authoringMeta={...this.authoringMeta,pendingSuggestion:null,draftRevision:Se(this.authoringMeta.draftRevision)},{ok:!0})}undo(){const e=this.history.pop();return e?(this.schema=C(e.schema),this.version=e.version,this.pending=null,e.authoringMeta?this.authoringMeta={...C(e.authoringMeta),draftRevision:Se(this.authoringMeta.draftRevision),pendingSuggestion:null}:this.authoringMeta={...this.authoringMeta,draftRevision:Se(this.authoringMeta.draftRevision),pendingSuggestion:null,origins:this.authoringMeta.origins.filter(s=>{var i,n;return s.target.kind==="group"?(((i=this.schema)==null?void 0:i.groups)||[]).some(r=>r.key===s.target.key):(((n=this.schema)==null?void 0:n.groups)||[]).some(r=>(r.items||[]).some(a=>a.key===s.target.key))})},{ok:!0}):{ok:!1,error:"NOTHING_TO_UNDO"}}getPendingDiff(){var e;return((e=this.pending)==null?void 0:e.dryRun.diff)||null}}function ts(t,e,s){const i=Si(t,e);return{core:new As(t,s,{trust:"untrusted",dialect:"safe-v1"}),retained:i}}function Si(t,e){const s=new Map;for(const r of t.groups||[])for(const a of r.items||[])s.set(a.key,a);const i={},n=[];for(const[r,a]of Object.entries(e||{})){const o=s.get(r);if(!o){n.push(r);continue}const l=a&&typeof a=="object"&&"value"in a?a.value:a;try{const c=o.valueType?Xe(l,o.valueType):l;if(o.valueType==="number"&&(c===null||Number.isNaN(c))){n.push(r);continue}i[r]=c}catch{n.push(r)}}return{values:i,discardedKeys:n}}async function ss(t,e){await t.init(e)}const se={maxFileBytes:2*1024*1024,maxExtractedChars:5e4,maxPdfPages:40,maxDocuments:3,maxClarifyingQuestions:3},Ai=[/trialValues/i,/trial_values/i,/cookie/i,/set-cookie/i,/\bjwt\b/i,/authorization:\s*bearer/i,/open_id/i,/\buin\b/i];function Qr(t){const e=String((t==null?void 0:t.text)||"").trim(),s=Array.isArray(t==null?void 0:t.documents)?t.documents.map(i=>String((i==null?void 0:i.text)||"")).join(`
|
|
61
|
+
`):"";return`${e}
|
|
62
|
+
${s}`.trim()}function Ei(t){let s=JSON.stringify(t);for(const i of Ai)s=s.replace(new RegExp(i.source,i.flags),"[REDACTED]");try{return JSON.parse(s)}catch{return t}}function Ri(t){const e=JSON.stringify(t);if(/trialValues|trial_values/i.test(e))throw new Error("TRIAL_VALUES_MUST_NOT_ENTER_AI")}function wi(){return`brief_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Ti(t={}){var e;return{id:t.id||wi(),goals:String(t.goals||""),audience:t.audience,scenario:t.scenario,platforms:t.platforms||[],constraints:t.constraints||[],requirements:t.requirements||(t.goals?[String(t.goals)]:[]),assumptions:t.assumptions||[],unresolvedQuestions:t.unresolvedQuestions||[],answers:t.answers||{},readiness:t.readiness||((e=t.unresolvedQuestions)!=null&&e.length?"needs_clarification":"ready"),evidenceDraft:t.evidenceDraft}}function Oi(t){const e=[],s=[],i=[],n=[{re:/姓名|真实姓名/,key:"customerName",label:"姓名",type:"input",required:!0},{re:/手机号|电话/,key:"mobile",label:"手机号",type:"phone",required:!0},{re:/身份证/,key:"idNumber",label:"身份证号",type:"input"},{re:/婚姻|已婚/,key:"maritalStatus",label:"婚姻状况",type:"select"},{re:/配偶/,key:"spouseName",label:"配偶姓名",type:"input"}];for(const o of n){const l=t.match(o.re);l&&e.push({key:o.key,label:o.label,type:o.type,required:o.required,evidence:l[0]})}/已婚/.test(t)&&/配偶/.test(t)&&/显示|可见|联动/.test(t)&&s.push({source:"maritalStatus",target:"spouseName",evidence:"已婚后显示配偶"});const r=t.match(/(婚姻状况|选项|枚举)[^。\n]{0,40}/),a=t.match(/未婚|已婚|离异/);if(r&&a){const o=Array.from(new Set(t.match(/未婚|已婚|离异/g)||[]));i.push({fieldKey:"maritalStatus",values:o,evidence:r[0]})}return{fields:e,relations:s,enums:i}}function xi(t){const e=[],s=String(t||"").trim();return!s||s.length<8||/^做个客户表[\s。.!!]*$/i.test(s)?(e.push({id:"gap_vague",kind:"vague_goal",prompt:"需要采集哪些关键字段?哪些必填?有没有显隐联动?",reason:"vague_goal",evidence:s.slice(0,40)}),e.slice(0,se.maxClarifyingQuestions)):(/姓名|手机|身份证|字段|采集/.test(s)||e.push({id:"gap_fields",kind:"field_type",prompt:"请列出至少两个要采集的字段及其类型。",reason:"missing_fields"}),/选项|枚举|下拉/.test(s)&&!/未婚|已婚|是\/否|A\/B/.test(s)&&e.push({id:"gap_enum",kind:"enum",prompt:"提到了选项/枚举,但没有列出取值。请给出完整选项,或明确允许我使用建议默认值。",reason:"enum_without_values"}),/接口|提交|api/i.test(s)&&!/\/api\/|提交接口/.test(s)&&e.push({id:"gap_api",kind:"api_dependency",prompt:"表单是否依赖已有查询/提交接口?如果有,请给出接口用途(不要粘贴凭据)。",reason:"api_unspecified"}),e.slice(0,se.maxClarifyingQuestions))}function Ci(t){const e=String(t.text||"").trim(),s=xi(e),i=!!t.allowSuggestedDefaults||/采用建议|默认值|你可以先按常见选项/.test(e)||Object.values(t.answers||{}).some(l=>/采用建议|默认/.test(String(l))),n=i?s.filter(l=>l.kind!=="enum"):s,r=Oi(e);i&&s.some(l=>l.kind==="enum")&&!r.enums.length&&r.enums.push({fieldKey:"maritalStatus",values:["未婚","已婚","离异"],evidence:"assumption:suggested_defaults"});const a=n.length>0?"needs_clarification":"ready",o=Ti({goals:e,requirements:e?[e]:[],assumptions:i?["用户允许采用建议默认枚举值"]:[],unresolvedQuestions:n,answers:t.answers||{},readiness:a,evidenceDraft:r});return{readiness:a,gaps:n,brief:o,evidenceDraft:r}}function Ni(t){return t==="ready"}function H(t){let e=0;for(let s=0;s<t.length;s++)e=e*31+t.charCodeAt(s)|0;return Math.abs(e).toString(36)}function Fe(t){return/手机|电话|电话号码/.test(t)?"phone":/身份证/.test(t)?"idcard":/邮箱|邮件/.test(t)?"input":/地址/.test(t)?"address":/日期|生日/.test(t)?"date":/金额|收入|额度/.test(t)?"number":/备注|说明/.test(t)?"textarea":/状况|类型|性别|是否|关系/.test(t)?"select":"input"}const Di=new Set(["姓名","真实姓名","手机号","手机","电话","身份证","身份证号","邮箱","邮件","备注","工作单位","收入"]);function $i(t){const e=[];for(const s of(t==null?void 0:t.groups)||[])for(const i of s.items||[])e.push({item:i,groupKey:s.key});return e}function rt(t,e){const s=String(e||"").trim();if(!s)return[];const i=$i(t),n=i.filter(({item:r})=>String(r.label||"")===s||String(r.key||"")===s||String(r.key||"").toLowerCase()===s.toLowerCase());return n.length>0?n:i.filter(({item:r})=>String(r.label||"").includes(s))}function Je(t,e){const s=rt(t,e);return s.length===0?null:s.length>1?{ambiguous:s}:{hit:s[0]}}function he(t){const e=String(t.label||t.key||""),s=String(t.key||"");return e&&s&&e!==s?`「${e}」(${s})`:`「${e||s}」`}function He(t,e,s){const i=s.map(n=>he(n.item)).join("、");return{kind:"clarification",confidence:.2,questions:[{id:`ambig_${H(t+e)}`,prompt:`「${e}」对应多个字段:${i}。请回复要操作的完整标签或 key(例如 ${he(s[0].item)})。`,reason:"field_reference_ambiguous"}]}}function Mi(t){const e=new Set;for(const s of(t==null?void 0:t.groups)||[]){s!=null&&s.key&&e.add(String(s.key));for(const i of(s==null?void 0:s.items)||[])i!=null&&i.key&&e.add(String(i.key))}return e}function is(t,e){let s=t.slice(0,40);if(!e.has(s))return e.add(s),s;let i=2;for(;e.has(`${t.slice(0,36)}_${i}`);)i+=1;return s=`${t.slice(0,36)}_${i}`,e.add(s),s}function Li(t,e){const i={紧急联系人:"g_emergency",基本信息:"g_basic",联系方式:"g_contact",配偶信息:"g_spouse",地址信息:"g_address"}[t]||`g_${H(t).slice(0,8)}`;return is(i,e)}function Vi(t){return/模块|分组|下面|包含|包括|字段\s*[::]|[、,,]/.test(t)}function Fi(t,e,s){const i=e.match(/^(?:增加|添加|新增|加一个|加个|加上)\s*(?:一个)?\s*[「『"']?(.+?)[」』"']?(?:模块|分组|组)\s*[,,、]?\s*(?:下面(?:有)?|包含|包括)?(?:[一二三四五六七八九十百两\d]+个)?(?:字段)?[::,,]?\s*(.+)$/);if(!i)return null;const n=i[1].replace(/(?:的)?(?:模块|分组|组)$/,"").trim();let r=i[2].replace(/[。!!??]\s*$/,"").trim();if(r=r.replace(/^(?:[一二三四五六七八九十百两\d]+个)?字段[::,,\s]*/,"").trim(),!n||n.length>24||!r)return null;const a=r.split(/[\u3001\uFF0C,]+/).map(g=>g.replace(/^(?:\u548C|\u53CA|\u4E0E)/,"").replace(/字段$/,"").trim()).filter(Boolean);if(a.length<2||a.length>12||a.some(g=>g.length<2||g.length>16))return null;const o=Mi(t),l=Li(n,o),c=/紧急联系人/.test(n)?"emergency":l.replace(/^g_/,"").replace(/[^a-zA-Z0-9_]/g,"")||"mod",u=a.map(g=>{let y=at(g);ot[g]&&/姓名|电话|手机|关系/.test(g)?y=`${c}${y.charAt(0).toUpperCase()}${y.slice(1)}`:(o.has(y)||y==="customerName"||y==="mobile")&&(y=`${c}_${y}`);const _=is(y,o),m=Fe(g);return{key:_,type:m,label:g,required:!1,placeholder:m==="select"?`请选择${g}`:`请输入${g}`,...m==="select"&&/关系/.test(g)?{props:{options:[{label:"配偶",value:"spouse"},{label:"父母",value:"parent"},{label:"子女",value:"child"},{label:"朋友",value:"friend"},{label:"其他",value:"other"}]}}:{}}}),d={requestId:`fast_mod_${H(e)}`,baseVersion:s,intentSummary:`新增「${n}」模块,含 ${u.map(g=>g.label).join("、")}`,assumptions:[`按模块意图新增分组 ${l}(未调用大模型)`],operations:[{op:"addGroup",group:{key:l,title:n,items:u}}],riskFlags:[],suggestedTests:[],briefId:"",idempotencyKey:`fast_mod_${H(e)}`},f=ne(t,d,{expectedVersion:s});return f.ok?{kind:"proposal",changeSet:d,dryRun:f,confidence:.88,intentSummary:d.intentSummary}:null}function Ki(t,e,s){var c;const i=String(e||"").trim();if(!i||!((c=t==null?void 0:t.groups)!=null&&c.length))return null;const n=Fi(t,i,s);if(n)return n;const r=i.match(/^(?:删除|去掉|移除|删掉)\s*(?:字段\s*)?[「『"']?(.+?)[」』"']?(?:字段)?$/);if(r){const{label:u,key:d}=Ne(r[1]),f=Je(t,d||u);if(!f)return null;if("ambiguous"in f)return He("delete",d||u,f.ambiguous);const g=f.hit,y={requestId:`fast_del_${H(i)}`,baseVersion:s,intentSummary:`删除字段${he(g.item)}`,assumptions:[],operations:[{op:"removeField",fieldKey:g.item.key}],riskFlags:[],suggestedTests:[],briefId:"",idempotencyKey:`fast_del_${H(i)}`},_=ne(t,y,{expectedVersion:s});return _.ok?{kind:"proposal",changeSet:y,dryRun:_,confidence:.9,intentSummary:y.intentSummary}:null}const a=i.match(/^(?:把|将)?\s*[「『"']?(.+?)[」』"']?\s*(?:改成|改为|改名为|改叫)\s*[「『"']?(.+?)[」』"']?\s*$/);if(a){const u=Ne(a[1].replace(/(?:的)?(?:标签|名称|字段)$/,"")),d=a[2].trim(),f=Je(t,u.key||u.label);if(!f||!d)return null;if("ambiguous"in f)return He("rename",u.key||u.label,f.ambiguous);const g=f.hit,y={requestId:`fast_ren_${H(i)}`,baseVersion:s,intentSummary:`把${he(g.item)}标签改成「${d}」(key 保持 ${g.item.key})`,assumptions:[],operations:[{op:"updateField",fieldKey:g.item.key,changes:{label:d}}],riskFlags:[],suggestedTests:[],briefId:"",idempotencyKey:`fast_ren_${H(i)}`},_=ne(t,y,{expectedVersion:s});return _.ok?{kind:"proposal",changeSet:y,dryRun:_,confidence:.92,intentSummary:y.intentSummary}:null}const o=i.match(/^[「『"']?(.+?)[」』"']?\s*(?:字段)?\s*(设为必填|改为必填|设成必填|取消必填|改为非必填|设为非必填)$/);if(o){const u=Ne(o[1]),d=!/取消|非必填/.test(o[2]),f=Je(t,u.key||u.label);if(!f)return null;if("ambiguous"in f)return He("required",u.key||u.label,f.ambiguous);const g=f.hit,y={requestId:`fast_req_${H(i)}`,baseVersion:s,intentSummary:d?`将${he(g.item)}设为必填`:`取消${he(g.item)}必填`,assumptions:[],operations:[{op:"updateField",fieldKey:g.item.key,changes:{required:d}}],riskFlags:[],suggestedTests:[],briefId:"",idempotencyKey:`fast_req_${H(i)}`},_=ne(t,y,{expectedVersion:s});return _.ok?{kind:"proposal",changeSet:y,dryRun:_,confidence:.9,intentSummary:y.intentSummary}:null}const l=i.match(/^(?:增加|添加|新增|加一个|加个|加上)\s*(?:一个|一项|一个)?\s*(?:字段\s*)?[「『"']?(.+?)[」』"']?(?:字段)?[。!!??]*$/);if(l){const{label:u,key:d}=Ne(l[1]);if(!u||u.length>40||Vi(u)||/不确定|随便|优化|改一下/.test(u))return null;const f=t.groups[0].key,g=at(u,d);if(rt(t,u).length>0||rt(t,g).length>0)return null;const y=Fe(u),_={requestId:`fast_add_${H(i)}`,baseVersion:s,intentSummary:`增加字段「${u}」(${g})`,assumptions:d?[`使用用户指定 key=${g}`]:[`按常用映射表解析 key=${g}`],operations:[{op:"addField",groupKey:f,field:{key:g,type:y,label:u,required:!1,placeholder:`请输入${u}`}}],riskFlags:[],suggestedTests:[],briefId:"",idempotencyKey:`fast_add_${H(i)}`},m=ne(t,_,{expectedVersion:s});return m.ok?{kind:"proposal",changeSet:_,dryRun:m,confidence:.9,intentSummary:_.intentSummary}:null}return null}function Pi(t){const e=String(t||"").trim();if(!e||e.length<6||/^(改一下|优化一下|帮我|随便)/.test(e)||/必填|非必填|选填|显示|隐藏|联动|选项|下拉|校验|验证|规则|条件|如果|提交|接口|默认|保留|删除|步骤|分组|平台|移动|调整/.test(e)||!/[、,,]/.test(e))return null;const s=e.match(/(?:采集|包含|包括|需要|字段[::]?)\s*(.+)$/);if(!s)return null;const i=s[1].replace(/[。.!!??]\s*$/,"");if(/[。.!!??;;()()::]|\b(?:and|or)\b/i.test(i))return null;const n=i.split(/[、,,]+/).map(a=>a.replace(/^(和|及|与)/,"").replace(/字段$/,"").trim());if(n.length<2||n.length>12||n.some(a=>a.length<2||a.length>12||/表单|进件|业务|平台|\s/.test(a))||n.some(a=>!Di.has(a))||n.some(a=>["select","address","search","list","task"].includes(Fe(a))))return null;const r=n.map(a=>({key:at(a),type:Fe(a),label:a,required:!1,placeholder:`请输入${a}`}));return new Set(r.map(a=>a.key)).size!==r.length?null:{confidence:.85,intentSummary:`新建表单:${r.map(a=>`${a.label}(${a.key})`).join("、")}`,schema:{version:"draft",storageKey:"studio_fast_form",apis:[],groups:[{key:"g_main",title:"基本信息",items:r}]}}}function qi(t,e){return{kind:"proposal",brief:e?{...e,readiness:"ready",unresolvedQuestions:[]}:void 0,changeSet:t.changeSet,dryRun:t.dryRun,systemRisks:[...t.dryRun.risks||[]],modelRiskFlags:[],confidence:t.confidence}}function Ui(t,e){return{kind:"clarification",brief:e||void 0,questions:t.questions,confidence:t.confidence}}const Qe=1;function F(t){return JSON.parse(JSON.stringify(t))}function ie(t){let e=0;const s=String(t||"");for(let i=0;i<s.length;i++)e=e*31+s.charCodeAt(i)|0;return`h${Math.abs(e).toString(36)}`}function ji(t){const e=String(t||"").trim();return!!(!e||e.length<8||/^做个客户表[\s。.!!]*$/i.test(e)||/^(做个表|帮我|随便|表单|生成表单|改一下|优化一下)[\s。.!!]*$/i.test(e)||/表单/.test(e)&&e.length<12&&!/姓名|手机|字段|采集|进件/.test(e))}function Gi(){return{version:"draft",storageKey:"studio_new_customer",apis:[],groups:[{key:"g_customer",title:"客户信息",items:[{key:"customerName",type:"input",label:"姓名",required:!0,valueType:"string"},{key:"mobile",type:"phone",label:"手机号",required:!0,valueType:"string"},{key:"idNumber",type:"input",label:"身份证号",required:!1,valueType:"string"},{key:"maritalStatus",type:"select",label:"婚姻状况",required:!1,valueType:"string",props:{options:[{label:"未婚",value:"single"},{label:"已婚",value:"married"}]},relations:[{target:"spouseName",effect:"visible",type:"local",logic:"value === 'married'"}]},{key:"spouseName",type:"input",label:"配偶姓名",required:!1,valueType:"string",visible:!1}]}]}}function Ae(t){return(t||[]).filter(e=>e.severity==="high").length}function Wr(t={}){let e=!!t.failNext,s=!!t.failInvalidJson,i=!!t.failTimeout;const n={lastSanitizedInput:null,setFailNext(r){e=r},async understand(r){var w,P,E,V,j,q,oe,X,R,ge,te,p,T;const a=Ei({text:r.text,mode:r.mode,appliedRevision:r.appliedRevision,briefId:(w=r.brief)==null?void 0:w.id});if(n.lastSanitizedInput=a,Ri(a),i)return i=!1,{kind:"error",error:{code:"TIMEOUT",message:"AI 响应超时,请重试",recoverable:!0,step:r.mode}};if(s)return s=!1,{kind:"error",error:{code:"INVALID_STRUCTURE",message:"模型返回了无法解析的 JSON,Applied Schema 未改动",recoverable:!0,step:r.mode}};if(e)return e=!1,{kind:"error",error:{code:"PROVIDER_FAILED",message:"AI 暂时不可用,请重试",recoverable:!0,step:r.mode}};const o=String(r.text||"").trim(),l=r.brief||me({goals:o,requirements:o?[o]:[]});if(r.mode==="generate"){const O=Ci({text:o,answers:l.answers,allowSuggestedDefaults:Object.values(l.answers||{}).some($=>/采用建议|默认/.test(String($)))});if(!Ni(O.readiness))return{kind:"clarification",brief:O.brief,questions:O.gaps.map($=>({id:$.id,prompt:$.prompt,reason:$.reason}))};Object.assign(l,O.brief),(P=O.brief.assumptions)!=null&&P.length&&(l.assumptions=[...new Set([...l.assumptions||[],...O.brief.assumptions])])}if(r.mode==="generate"&&ji(o)&&!(l.answers&&Object.keys(l.answers).length)){const O={id:`q_vague_${ie(o)}`,prompt:"需要采集哪些关键字段?哪些必填?有没有字段显隐联动?",reason:"vague_goal"};return{kind:"clarification",brief:{...F(l),goals:o||l.goals,unresolvedQuestions:[O],answers:l.answers||{},readiness:"needs_clarification"},questions:[O]}}if(r.mode==="generate"){const O=Gi(),$=`req_${ie(o)}`,ae=String(l.goals||o).slice(0,80)||"新建客户进件表",Te={requestId:$,baseVersion:"0",intentSummary:ae,assumptions:l.assumptions||[],operations:[],riskFlags:[],suggestedTests:[],briefId:l.id,idempotencyKey:$},Oe={ok:!0,nextSchema:O,diff:{entries:(((E=O.groups[0])==null?void 0:E.items)||[]).map(I=>({kind:"add",path:`groups[0].items.${I.key}`,fieldKey:I.key}))},risks:[],errors:[],appliedRequestId:$};return{kind:"proposal",brief:{...F(l),goals:o,unresolvedQuestions:[],requirements:[o],readiness:"ready"},changeSet:Te,dryRun:Oe,systemRisks:[],modelRiskFlags:[]}}const c=r.appliedSchema,u=String(r.appliedRevision||(c==null?void 0:c.version)||"2.0");if(!c)return{kind:"error",error:{code:"NO_APPLIED",message:"当前没有已应用表单,无法修改",recoverable:!0,step:"edit"}};const d=et(o,l);if(!d.clear)return{kind:"clarification",brief:{...F(l),goals:o||l.goals,unresolvedQuestions:d.questions.map($=>({id:$.id,prompt:$.prompt,reason:$.reason})),answers:l.answers||{},readiness:"needs_clarification"},questions:d.questions,confidence:.2};const f=/高风险|删除所有|清空|移除全部/.test(o),g=/真实姓名|改成真实|客户姓名/.test(o),y=/备注/.test(o);let _=[],m=o.slice(0,40)||"修改表单",S=[],h=.55;if(f){const O=(c.groups||[]).flatMap($=>$.items||[]).find($=>!$.required)||((q=(j=(V=c.groups)==null?void 0:V[0])==null?void 0:j.items)==null?void 0:q[0]);_=O?[{op:"updateField",fieldKey:O.key,changes:{label:`${O.label||O.key}(高风险调整)`}}]:[],m="删除非必填字段",h=.35,S=[{code:"BULK_DELETE",severity:"high",message:"将删除多个非必填字段,可能影响已有流程"}]}else if(g){const O=(c.groups||[]).flatMap($=>$.items||[]).find($=>/姓名|name/i.test(String($.label||$.key)))||((R=(X=(oe=c.groups)==null?void 0:oe[0])==null?void 0:X.items)==null?void 0:R[0]);O&&(_=[{op:"updateField",fieldKey:O.key,changes:{label:"真实姓名"}}],m="把客户姓名标签改成真实姓名",h=.88)}else y?(_=[{op:"addField",groupKey:((te=(ge=c.groups)==null?void 0:ge[0])==null?void 0:te.key)||"g1",field:{key:`note_${ie(o).slice(0,6)}`,type:"input",label:"备注",required:!1,valueType:"string"}}],m="增加备注字段",h=.86):(_=[{op:"addField",groupKey:((T=(p=c.groups)==null?void 0:p[0])==null?void 0:T.key)||"g1",field:{key:`field_${ie(o).slice(0,8)}`,type:"input",label:o.slice(0,12)||"新字段",required:!1,valueType:"string"}}],h=.55);const b=`req_${ie(o)}`,A={requestId:b,baseVersion:u,intentSummary:m,assumptions:[],operations:_,riskFlags:S,suggestedTests:[],briefId:l.id,idempotencyKey:b};let v=ne(c,A,{expectedVersion:u});if(!v.ok)return{kind:"error",error:{code:"DRY_RUN_FAILED",message:v.errors.map(O=>O.message).join("; ")||"dryRun 失败",recoverable:!0,step:"edit"}};const k=[...S,...v.risks||[]];return f&&Ae(k)===0&&k.push(...S),{kind:"proposal",brief:F(l),changeSet:A,dryRun:{...v,risks:k},systemRisks:k,modelRiskFlags:S,confidence:h}}};return n}function zr(){const t=new Map;return{async load(e){const s=t.get(e);return s?F(s):null},async save(e,s){t.set(e,F(s))},dump(e){const s=t.get(e);return s?F(s):null}}}function Xr(t){const e=new Ii(null);let s="entry",i="entry",n="author",r="",a="applied",o=[],l=t.locale||"zh-CN",c=null,u=null,d=null,f="",g=null,y="edit",_=null,m,S=[],h;const b=new Set;let A=null;const v=()=>{if(A)return A;const p=e.snapshot();return A={entryMode:s,workflowPhase:i,workspaceMode:n,formName:r,formBrief:p.brief,appliedSchema:p.schema,appliedRevision:p.schema?p.version:null,pendingProposal:p.pending,previewTarget:a,timeline:F(o),checks:P(p.pending),aiRun:u?F(u):null,locale:l,recoverableError:c?F(c):null,authoringMeta:p.authoringMeta||tt(),authorInteractionMode:y,authoringAuthority:_,isolationReason:m,importDiagnostics:S.length?F(S):void 0,cfmAuthoringExport:h?F(h):void 0},A},k=()=>{A=null;for(const p of b)p()},w=p=>{o=[...o,{id:p.id||`e_${Date.now()}_${o.length}`,at:p.at||Date.now(),...p}]},P=p=>{var $,ae;if(!p)return null;const T=p.systemRisks||[],O=(($=p.dryRun)==null?void 0:$.errors)||[];return{ok:!!((ae=p.dryRun)!=null&&ae.ok)&&Ae(T)===0,issueCount:O.length+T.length,highRiskCount:Ae(T)}},E=async()=>{const p=e.snapshot(),T=Array.from(e.seenRequestIds||[]),O={formatVersion:Qe,entryMode:s,workflowPhase:i,workspaceMode:n,formName:r,formBrief:p.brief,appliedSchema:p.schema,appliedRevision:p.schema?p.version:null,pendingProposal:p.pending,previewTarget:a,timeline:F(o),locale:l,seenRequestIds:T,authoringMeta:p.authoringMeta,authorInteractionMode:y,authoringAuthority:_,isolationReason:m,importDiagnostics:S.length?F(S):void 0,cfmAuthoringExport:h?F(h):void 0},$=JSON.stringify(O);if(/trialValues|trial_values/i.test($))throw new Error("REFUSING_TO_PERSIST_TRIAL_VALUES");await t.repository.save(t.workspaceId,O)},V=new Set,j=e.applyPending.bind(e),q=()=>{var T,O;const p=e.snapshot().pending;(T=p==null?void 0:p.changeSet)!=null&&T.requestId&&V.add(p.changeSet.requestId),(O=p==null?void 0:p.changeSet)!=null&&O.idempotencyKey&&V.add(p.changeSet.idempotencyKey)},oe=p=>{s=p.entryMode,i=p.workflowPhase,n=p.workspaceMode==="review"||p.workspaceMode==="test"?p.workspaceMode:"author",r=p.formName,a=p.previewTarget,o=F(p.timeline||[]),l=p.locale||"zh-CN",c=null,p.appliedSchema?e.replaceSchema(p.appliedSchema,p.appliedRevision||void 0,"hydrate"):(e.schema=null,e.version=p.appliedRevision||"0",e.pending=null,e.history=[]),p.formBrief&&e.setBrief(p.formBrief),p.pendingProposal&&e.propose({changeSet:p.pendingProposal.changeSet,dryRun:p.pendingProposal.dryRun,systemRisks:p.pendingProposal.systemRisks,modelRiskFlags:p.pendingProposal.modelRiskFlags,explicitConstraintCheck:p.pendingProposal.explicitConstraintCheck});for(const T of p.seenRequestIds||[])V.add(T);p.authoringMeta&&e.setAuthoringMeta(p.authoringMeta),y=p.authorInteractionMode==="trial"?"trial":"edit",_=p.authoringAuthority??null,m=p.isolationReason,S=p.importDiagnostics?F(p.importDiagnostics):[],h=p.cfmAuthoringExport?F(p.cfmAuthoringExport):void 0},X=async p=>{var O,$,ae,Te,Oe,qe;const T=(I,M={})=>(c=I,i="error",d=p,w({kind:"error",message:I.message,appliedIntact:!0}),k(),E().catch(()=>{}),{ok:!1,error:I.message,code:I.code,...M});try{switch(p.type){case"setLocale":return l=p.locale,k(),await E(),{ok:!0};case"startNewForm":{s="new",i="understanding",r="",g=null,a="proposal",c=null,e.replaceSchema({__empty:!0}),e.schema=null,e.version="0",e.pending=null,e.brief=null,e.history=[],e.clarification=null,o=[];const I=p.source.kind==="text"||p.source.kind==="document"||p.source.kind==="mixed"?p.source.text:"";return I.trim()&&e.setBrief(me({goals:I,requirements:[I]})),k(),await E(),{ok:!0}}case"openExistingForm":{c=null,i="understanding",k();try{const I=await t.existingForms.getByPageId(p.pageId);return e.replaceSchema(I.schema,I.revision,"open-existing"),e.pending=null,s="existing",r=I.formName,g=I.pageId,a="applied",i="idle",e.setBrief(me({goals:`打开已有表单 ${I.formName}`,requirements:[`page_id=${I.pageId}`]})),w({kind:"system-result",resultKind:"generated",body:`已载入 ${I.formName}`}),w({kind:"assistant",body:`已打开「${I.formName}」。告诉我你想改什么——例如增加字段、调整必填、或设置显隐联动——我会先生成提案供你确认。`}),k(),await E(),{ok:!0}}catch(I){return T({code:"OPEN_FAILED",message:(I==null?void 0:I.message)||"打开表单失败",recoverable:!0,step:"openExistingForm"})}}case"describeGoal":{c=null;const I=String(p.text||"").trim();if(!I)return T({code:"EMPTY_GOAL",message:"请先描述表单目标",recoverable:!0,step:"describeGoal"});f=I,w({kind:"goal",body:I}),i="understanding",u={requestId:`run_${ie(I)}`,status:"running",phase:"understanding_intent",message:"正在理解你的表单目标…"},k();const M=e.snapshot(),U=Pi(I);let x;if(U){const Z=`fast_gen_${ie(I)}`,ct=((O=U.schema.groups[0])==null?void 0:O.items)||[];x={kind:"proposal",brief:me({goals:I,requirements:[I],readiness:"ready"}),changeSet:{requestId:Z,baseVersion:"0",intentSummary:U.intentSummary,assumptions:["本地快速生成(字段列表明确,未调用 LLM)"],operations:[],riskFlags:[],suggestedTests:[],briefId:"",idempotencyKey:Z},dryRun:{ok:!0,nextSchema:U.schema,diff:{entries:ct.map(ye=>({kind:"add",path:`groups[0].items.${ye.key}`,fieldKey:ye.key}))},risks:[],errors:[],appliedRequestId:Z},systemRisks:[],modelRiskFlags:[],confidence:U.confidence},u={requestId:u.requestId,status:"running",phase:"building_proposal",message:"已识别字段清单,正在快速生成…",confidence:U.confidence},k()}else x=await t.architect.understand({text:I,mode:"generate",appliedSchema:M.schema,appliedRevision:M.schema?M.version:null,brief:M.brief});if(u={requestId:u.requestId,status:x.kind==="error"?"error":"ok",phase:x.kind==="error"?"error":x.kind==="clarification"?"awaiting_clarification":"done",message:x.kind==="error"?($=x.error)==null?void 0:$.message:x.kind==="clarification"?"需要补充细节":"目标已理解",confidence:x.confidence??null},x.kind==="error")return T(x.error||{code:"AI_ERROR",message:"理解需求失败",recoverable:!0,step:"describeGoal"});if(x.kind==="clarification")return x.brief&&e.setBrief(x.brief),x.questions&&e.applyClarification({kind:"clarification_required",questions:x.questions,brief:x.brief||e.snapshot().brief,meta:{requestId:u.requestId,promptVersion:"mem-v1",model:"memory",outputSchemaVersion:"v1",latencyMs:0,retryCount:0,status:"ok"}}),i="clarifying",w({kind:"assistant",body:`我理解了你的目标:「${I.slice(0,60)}${I.length>60?"…":""}」。生成表单前还需要确认几个问题。`}),w({kind:"clarification",questions:(x.questions||[]).map(Z=>Z.prompt)}),k(),await E(),{ok:!0};x.brief&&e.setBrief(x.brief),e.propose({changeSet:x.changeSet,dryRun:x.dryRun,systemRisks:x.systemRisks,modelRiskFlags:x.modelRiskFlags,explicitConstraintCheck:x.explicitConstraintCheck}),a="proposal",i="proposal_ready",r||(r=I.slice(0,30));const B=(((Te=(ae=x.dryRun)==null?void 0:ae.diff)==null?void 0:Te.entries)||[]).filter(Z=>Z.kind==="add").length,W=typeof x.confidence=="number"&&Number.isFinite(x.confidence)?x.confidence:null,N=Ae(x.systemRisks||[]);return w({kind:"assistant",body:`我理解了你的需求,已生成提案「${x.changeSet.intentSummary}」${B?`(约 ${B} 处字段变更)`:""}。请在预览后确认应用。`}),w({kind:"proposal",intentSummary:x.changeSet.intentSummary,highRisk:N>0}),u={requestId:u.requestId,status:"ok",phase:"done",message:N>0?"提案已就绪(含高风险项,确认后应用)":"提案已就绪,请确认后应用",confidence:W},k(),await E(),{ok:!0}}case"answerClarification":{c=null;const I=e.answerQuestions(p.answers);if(Object.values(p.answers||{}).some(N=>/采用建议|默认/.test(String(N)))){const N={...I,assumptions:[...new Set([...I.assumptions||[],"用户允许采用建议默认枚举值"])]};e.setBrief(N)}const U=Object.values(p.answers).join(";");w({kind:"assistant",body:`已记录你的回答:${U}`});const x=e.snapshot().brief,B=(x.unresolvedQuestions||[]).filter(N=>!(x.answers||{})[N.id]);if(B.length>0)return i="clarifying",u={requestId:(u==null?void 0:u.requestId)||`run_${Date.now().toString(36)}`,status:"ok",phase:"awaiting_clarification",message:`还需确认 ${B.length} 个问题`},w({kind:"assistant",body:`还有 ${B.length} 个细节需要确认。`}),k(),await E(),{ok:!0};const W=f||String(x.goals||Object.values(p.answers).join(" "));return e.snapshot().schema?X({type:"requestRevision",text:W}):X({type:"describeGoal",text:W})}case"requestRevision":{c=null;const I=String(p.text||"").trim();if(!I)return T({code:"EMPTY_REVISION",message:"请描述要修改的内容",recoverable:!0,step:"requestRevision"});const M=e.snapshot();if(!M.schema)return T({code:"NO_APPLIED",message:"当前没有已应用表单",recoverable:!0,step:"requestRevision"});f=I,w({kind:"goal",body:I});const U=(M.schema.groups||[]).length,x=(M.schema.groups||[]).reduce((ke,Ue)=>ke+(Ue.items||[]).length,0);w({kind:"assistant",body:`先对齐当前表单:${U} 个分组、${x} 个字段。接下来理解你的修改意图。`}),i="proposing";const B=`run_${ie(I)}`;u={requestId:B,status:"running",phase:"reading_schema",message:"正在阅读当前表单结构…"},k(),await new Promise(ke=>setTimeout(ke,16));const W=Ki(M.schema,I,M.version);let N;if(W?W.kind==="clarification"?N=Ui(W,M.brief):(u={requestId:B,status:"running",phase:"building_proposal",message:`识别为字段操作:${W.intentSummary}`,confidence:W.confidence},k(),N=qi(W,M.brief)):(u={requestId:B,status:"running",phase:"understanding_intent",message:"正在理解你的修改意图…"},k(),N=await t.architect.understand({text:I,mode:"edit",appliedSchema:M.schema,appliedRevision:M.version,brief:M.brief})),N.kind==="error")return u={requestId:B,status:"error",phase:"error",message:((Oe=N.error)==null?void 0:Oe.message)||"生成修改提案失败"},k(),T(N.error||{code:"AI_ERROR",message:"生成修改提案失败",recoverable:!0,step:"requestRevision"});if(N.kind==="clarification"){N.brief&&e.setBrief(N.brief),N.questions&&e.applyClarification({kind:"clarification_required",questions:N.questions,brief:N.brief||e.snapshot().brief,meta:{requestId:B,promptVersion:"mem-v1",model:"memory",outputSchemaVersion:"v1",latencyMs:0,retryCount:0,status:"ok"}}),i="clarifying",u={requestId:B,status:"ok",phase:"awaiting_clarification",message:"需要你补充细节后才能继续",confidence:N.confidence??.2};const ke=(N.questions||[]).map(Ue=>Ue.prompt);return w({kind:"assistant",body:`我理解了「${I.slice(0,48)}${I.length>48?"…":""}」,但还有不清楚的地方——我们一次确认一个问题。`}),w({kind:"clarification",questions:ke.slice(0,1)}),k(),await E(),{ok:!0}}u={requestId:B,status:"running",phase:"building_proposal",message:"正在整理修改提案…",confidence:N.confidence??null},k(),e.propose({changeSet:N.changeSet,dryRun:N.dryRun,systemRisks:N.systemRisks,modelRiskFlags:N.modelRiskFlags,explicitConstraintCheck:N.explicitConstraintCheck}),a="proposal",i="proposal_ready";const Z=Ae([...N.systemRisks||[],...((qe=N.dryRun)==null?void 0:qe.risks)||[]]),ye=typeof N.confidence=="number"&&Number.isFinite(N.confidence)?N.confidence:.55;return w({kind:"assistant",body:`已根据你的描述生成修改提案「${N.changeSet.intentSummary}」(置信度 ${Math.round(ye*100)}%)。`}),w({kind:"proposal",intentSummary:N.changeSet.intentSummary,highRisk:Z>0}),u={requestId:B,status:"ok",phase:"done",message:Z>0?"提案已就绪(含高风险项,确认后应用)":"提案已就绪,请确认后应用",confidence:ye},k(),await E(),{ok:!0}}case"switchPreviewVersion":return p.target==="proposal"&&!e.snapshot().pending?T({code:"NO_PENDING",message:"当前没有提案可预览",recoverable:!0,step:"switchPreviewVersion"}):(a=p.target,k(),await E(),{ok:!0});case"applyProposal":{c=null;const I=e.snapshot().pending;if(!I)return T({code:"NO_PENDING",message:"没有待应用提案",recoverable:!0,step:"applyProposal"});const M=e.snapshot().version;if(e.snapshot().schema&&I.changeSet.baseVersion&&I.changeSet.baseVersion!==M)return T({code:"STALE_REVISION",message:`提案基于版本 ${I.changeSet.baseVersion},当前为 ${M},请重新生成提案`,recoverable:!0,step:"applyProposal"});i="applying",k();const U=j({confirmHighRisk:p.confirmHighRisk});return U.ok?(q(),I.changeSet.requestId&&V.add(I.changeSet.requestId),I.changeSet.idempotencyKey&&V.add(I.changeSet.idempotencyKey),a="applied",i="idle",w({kind:"system-result",resultKind:"applied",body:"已应用提案"}),k(),await E(),{ok:!0}):U.requiresConfirm?(i="proposal_ready",k(),{ok:!1,requiresConfirm:!0,error:U.error||"HIGH_RISK_CONFIRM_REQUIRED",code:"HIGH_RISK_CONFIRM_REQUIRED"}):T({code:U.error||"APPLY_FAILED",message:U.error||"应用失败",recoverable:!0,step:"applyProposal"})}case"discardProposal":return e.rejectPending(),a=s==="new"&&!e.snapshot().schema?"proposal":"applied",i=e.snapshot().schema?"idle":"understanding",c=null,w({kind:"system-result",resultKind:"rejected",body:"已放弃提案"}),k(),await E(),{ok:!0};case"retryFailedStep":{if(!d)return T({code:"NOTHING_TO_RETRY",message:"没有可重试的步骤",recoverable:!1,step:"retryFailedStep"});const I=d;return d=null,c=null,X(I)}case"openReview":return e.snapshot().pending?(n="review",a!=="proposal"&&(a="proposal"),c=null,k(),await E(),{ok:!0}):T({code:"NO_PENDING",message:"当前没有提案可审阅",recoverable:!0,step:"openReview"});case"openTest":return e.snapshot().schema?(n="test",c=null,k(),await E(),{ok:!0}):T({code:"NO_APPLIED",message:"请先载入或应用一个表单后再进入测试",recoverable:!0,step:"openTest"});case"backToAuthor":return n="author",c=null,k(),await E(),{ok:!0};case"setAuthorInteractionMode":return y=p.mode,k(),await E(),{ok:!0};case"startBlankDraft":{const I={version:"1",groups:[{key:"g_main",title:"表单",items:[]}],apis:[]};return e.replaceSchema(I,"1","blank"),e.setAuthoringMeta(tt()),r=p.formName||"未命名表单",s="new",i="idle",n="author",a="applied",c=null,k(),await E(),{ok:!0}}case"renameForm":{const I=p.name.trim();return!I||I.length>100?T({code:"FORM_NAME_INVALID",message:"表单名称需为 1 至 100 个字符",recoverable:!0,step:"renameForm"}):(r=I,k(),await E(),{ok:!0})}case"insertCatalogEntry":case"patchField":case"patchGroup":case"removeField":case"reorder":case"addGroup":case"addField":{if(_==="cfm")return T({code:"CFM_AUTHORITY_NO_SCHEMA_WRITE",message:"CFM 为作者权威时禁止直接写入 FormSchema(防双写)",recoverable:!0,step:p.type});const I=p.type==="insertCatalogEntry"?{type:"insertCatalogEntry",catalog:{catalogId:p.catalogId,catalogVersion:p.catalogVersion},params:p.params,targetGroupKey:p.targetGroupKey,omitPreferredKeys:p.omitPreferredKeys}:p,M=e.dispatchDraft(I);return M.ok?(s==="entry"&&(s="new",i="idle"),a="applied",k(),await E(),{ok:!0}):T({code:M.code,message:M.message,recoverable:!0,step:p.type})}case"adoptAuthoringSurface":{const I=e.snapshot(),M={authoringAuthority:_,isolationReason:m,importDiagnostics:S,cfmAuthoringExport:h,formName:r,entryMode:s,workflowPhase:i,workspaceMode:n,previewTarget:a,recoverableError:c};try{return _=p.authority,m=p.isolationReason,S=p.diagnostics?F(p.diagnostics):[],h=p.authority==="cfm"&&p.cfmAuthoringExport?F(p.cfmAuthoringExport):void 0,e.replaceSchema(p.schema,p.revision,`adopt-${p.authority}`),p.formName&&(r=p.formName),s==="entry"&&(s=p.authority==="legacy-compat"?"existing":"new"),i="idle",n="author",a="applied",c=null,await E(),k(),{ok:!0}}catch(U){return e.restoreSchemaSnapshot(I),{authoringAuthority:_,isolationReason:m,importDiagnostics:S,cfmAuthoringExport:h,formName:r,entryMode:s,workflowPhase:i,workspaceMode:n,previewTarget:a,recoverableError:c}=M,T({code:"PERSIST_FAILED",message:U instanceof Error?U.message:"保存失败,原表单已保留",recoverable:!0,step:p.type})}}case"mirrorCfmProposal":{if(_!=="cfm")return T({code:"NOT_CFM_AUTHORITY",message:"仅 CFM 权威表单可镜像 CFM 提案",recoverable:!0,step:"mirrorCfmProposal"});if(p.cfmAuthoringExport&&(h=F(p.cfmAuthoringExport)),p.pending){e.propose({changeSet:p.pending.changeSet,dryRun:p.pending.dryRun,systemRisks:p.pending.systemRisks,modelRiskFlags:p.pending.modelRiskFlags,explicitConstraintCheck:p.pending.explicitConstraintCheck});const I=e.getAuthoringMeta();p.pending.suggestionStatus==="stale"&&(e.pending={...e.snapshot().pending,suggestionStatus:"stale"}),i=p.workflowPhase||"proposal_ready",a="proposal"}else e.rejectPending(),i=p.workflowPhase||"idle",a="applied";return k(),await E(),{ok:!0}}case"undoDraft":{const I=e.undo();return I.ok?(k(),await E(),{ok:!0}):T({code:I.error||"UNDO_FAILED",message:I.error||"无法撤销",recoverable:!0,step:"undoDraft"})}case"returnToEntry":return s="entry",n="author",i="entry",a="applied",u=null,c=null,_=null,m=void 0,S=[],h=void 0,e.pending=null,e.clarification=null,k(),await E(),{ok:!0};default:return T({code:"UNKNOWN_COMMAND",message:`未知命令 ${p.type}`,recoverable:!1})}}catch(I){return T({code:"UNEXPECTED",message:(I==null?void 0:I.message)||"未知错误",recoverable:!0,step:p.type})}},R={snapshot:v,dispatch:X,subscribe(p){return b.add(p),()=>{b.delete(p)}},async hydrate(){const p=await t.repository.load(t.workspaceId);if(!(!p||p.formatVersion!==Qe)){e.schema=null,e.version="0",e.pending=null,e.brief=null,e.history=[],e.clarification=null,e.seenRequestIds=new Set(p.seenRequestIds||[]),oe(p);for(const T of p.seenRequestIds||[])e.seenRequestIds.add(T);k()}},forceStaleRevision(p){e.version=p,e.schema&&(e.schema={...e.schema,version:p}),k()},_setPending(p){e.propose({changeSet:p.changeSet,dryRun:p.dryRun,systemRisks:p.systemRisks,modelRiskFlags:p.modelRiskFlags,explicitConstraintCheck:p.explicitConstraintCheck}),k()}},ge=async()=>{const p=e.snapshot(),T=Array.from(e.seenRequestIds||V),O={formatVersion:Qe,entryMode:s,workflowPhase:i,workspaceMode:n,formName:r,formBrief:p.brief,appliedSchema:p.schema,appliedRevision:p.schema?p.version:null,pendingProposal:p.pending,previewTarget:a,timeline:F(o),locale:l,seenRequestIds:T,authoringAuthority:_,isolationReason:m,importDiagnostics:S.length?F(S):void 0,cfmAuthoringExport:h?F(h):void 0};await t.repository.save(t.workspaceId,O)},te=R.dispatch;return R.dispatch=async p=>{const T=await te(p);try{await ge()}catch{}return T},R}async function Zr(t){const e=t.previousValues||{},{core:s,retained:i}=ts(t.schema,e);await ss(s,i.values);for(const c of t.changes||[])s.setControlData(c.key,c.value,{eventType:c.eventType||"blur"});let n,r;if(t.collect){s.validateAll()&&(r="validateAll reported errors");try{n=s.collectFormData()}catch(u){r=(u==null?void 0:u.message)||String(u)}}const a=[],o=[],l=[];for(const[c,u]of Object.entries(s.fields||{})){const d=u,f={key:c,value:d==null?void 0:d.value,visible:(d==null?void 0:d.visible)!==!1,disabled:(d==null?void 0:d.disabled)===!0,errMsg:(d==null?void 0:d.errMsg)||void 0};a.push(f),f.visible&&o.push(c),f.errMsg&&l.push({key:c,message:String(f.errMsg)})}return r&&!l.some(c=>c.key==="_collect")&&l.push({key:"_collect",message:r}),{ok:l.length===0,retainedValues:i.values,discardedKeys:i.discardedKeys,fields:a,visibleKeys:o,validationErrors:l,collected:n,collectError:r,layer:"instant-semantic",engine:"FormCore",expressionTrust:"untrusted",expressionDialect:"safe-v1"}}function Ot(t,e){var s;return(s=t==null?void 0:t.fields)==null?void 0:s[e]}function Bi(t,e,s,i){switch(e.type){case"visible":{const n=Ot(t,e.fieldKey),r=!!n&&n.visible!==!1;return{assertion:e,pass:r,detail:r?`${e.fieldKey} 可见`:`${e.fieldKey} 应为可见,实际 ${n?"隐藏":"不存在"}`}}case"hidden":{const n=Ot(t,e.fieldKey),r=!n||n.visible===!1;return{assertion:e,pass:r,detail:r?`${e.fieldKey} 隐藏`:`${e.fieldKey} 应隐藏,实际可见`}}case"fieldError":{const n=s.find(a=>a.key===e.fieldKey),r=!!(n&&(!e.messageIncludes||String(n.message).includes(e.messageIncludes)));return{assertion:e,pass:r,detail:r?`${e.fieldKey} 有预期错误`:`${e.fieldKey} 缺少预期校验错误`}}case"noFieldError":{const n=s.find(a=>a.key===e.fieldKey),r=!n;return{assertion:e,pass:r,detail:r?`${e.fieldKey} 无错误`:`${e.fieldKey} 仍有错误:${n==null?void 0:n.message}`}}case"submitBlocked":{const n=!!i||s.length>0;return{assertion:e,pass:n,detail:n?"提交被阻止(校验未通过)":"预期提交应被阻止,但校验已通过"}}case"submitReady":{const n=!i&&s.length===0;return{assertion:e,pass:n,detail:n?"提交就绪(可见字段校验通过)":`提交未就绪:${i||s.map(r=>r.message).join(";")}`}}default:return{assertion:e,pass:!1,detail:"未知断言"}}}async function Yi(t,e){const{core:s}=ts(t,{});let i=0;typeof s.on=="function"&&s.on("fetchAPI",async u=>{var f;i+=1;const d=((f=u==null?void 0:u.api)==null?void 0:f.id)||(u==null?void 0:u.apiId)||"";if(String(d).includes("employment"))return{companyName:{name:"演示科技有限公司",creditCode:"91110000MA0000000X"}};if(String(d).includes("search"))return{list:[{name:"演示科技有限公司",creditCode:"91110000MA0000000X"}]};if(String(d).includes("submit"))throw new Error("沙箱禁止真实提交");return{}}),await ss(s,{});for(const u of e.steps)s.setControlData(u.fieldKey,u.value,{eventType:u.eventType||"blur"}),typeof s.flushAsync=="function"&&await s.flushAsync();const n=typeof s.validateAll=="function"?s.validateAll():!1;let r;try{s.collectFormData()}catch(u){r=(u==null?void 0:u.message)||String(u)}n&&!r&&(r="validateAll reported errors");const a=[],o=[];for(const[u,d]of Object.entries(s.fields||{})){const f=d;(f==null?void 0:f.visible)!==!1&&a.push(u),f!=null&&f.errMsg&&o.push({key:u,message:String(f.errMsg)})}r&&!o.some(u=>u.key==="_collect")&&o.push({key:"_collect",message:r});const l=e.assertions.map(u=>Bi(s,u,o,r)),c=l.every(u=>u.pass);return{scenarioId:e.id,ok:c,assertionResults:l,visibleKeys:a,validationErrors:o,sandboxed:!0,stubbedFetches:i}}async function en(t,e){const s=[];for(const i of e)s.push(await Yi(t,i));return s}function Ji(t){return JSON.parse(JSON.stringify(t))}function De(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let n=t;for(let r=0;r<i.length-1;r++){const a=i[r];if(n==null)return;n=n[a]}n&&i.length&&(n[i[i.length-1]]=s)}function Hi(t,e={}){const s=e.autoConvert!==!1,i=e.isolateUntrusted!==!1,n=Ji(t),r=Lt(n),a=[];let o=0,l=0,c=0,u=0;for(const d of r){const f=d.classification.kind;if(f==="safe-v1"){o+=1,a.push({path:d.path,expression:d.expression,classification:d.classification,action:"kept-safe-v1"});continue}if(f==="legacy/convertible"&&s&&d.classification.safeExpression){De(n,d.path,d.classification.safeExpression),l+=1,a.push({path:d.path,expression:d.expression,classification:d.classification,action:"converted-to-safe-v1"});continue}if(f==="legacy/untrusted"&&i){d.path.includes(".relations[")?De(n,d.path,"false"):d.path.includes(".rules[")?De(n,d.path,"true"):De(n,d.path,"''"),c+=1,a.push({path:d.path,expression:d.expression,classification:ve(d.expression),action:"isolated-untrusted"});continue}u+=1,a.push({path:d.path,expression:d.expression,classification:d.classification,action:"reported-only"})}return{schema:n,report:{convertedAt:new Date().toISOString(),totals:{expressions:r.length,safeV1:o,converted:l,isolated:c,reportedOnly:u},issues:a}}}function tn(t){return Hi(t,{autoConvert:!1,isolateUntrusted:!1}).report}function Qi(t,e){const s=String(t||"").toLowerCase(),i=String(e||"").toLowerCase();return s.endsWith(".md")||i.includes("markdown")||i==="text/plain"?"md":s.endsWith(".docx")||i.includes("wordprocessingml")?"docx":s.endsWith(".pdf")||i==="application/pdf"?"pdf":null}function Wi(t){if(t instanceof Uint8Array)return t;if(typeof Buffer<"u"&&Buffer.isBuffer(t)){const e=t;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}return new Uint8Array(t)}function zi(t){return typeof TextDecoder<"u"?new TextDecoder("utf-8",{fatal:!1}).decode(t):Buffer.from(t).toString("utf8")}function Xi(t={}){return{async extract(e){const s=Qi(e.fileName,e.mimeType);if(!s)return{ok:!1,error:{code:"UNSUPPORTED_TYPE",message:"仅支持 .md / .docx / .pdf 需求文档",recoverable:!0}};const i=Wi(e.bytes);if(i.byteLength<=0)return{ok:!1,error:{code:"EMPTY_FILE",message:"文件为空,请重新选择",recoverable:!0}};if(i.byteLength>se.maxFileBytes)return{ok:!1,error:{code:"FILE_TOO_LARGE",message:`文件超过 ${Math.round(se.maxFileBytes/(1024*1024))}MB 上限`,recoverable:!0}};try{let n="",r;if(s==="md")n=zi(i);else if(s==="docx"){if(!t.docx)return{ok:!1,error:{code:"DOCX_PARSER_UNAVAILABLE",message:"当前环境未配置 .docx 解析器",recoverable:!0}};const o=await t.docx.extract(i,e.fileName);n=o.text,r=o.pageCount}else{if(!t.pdf)return{ok:!1,error:{code:"PDF_PARSER_UNAVAILABLE",message:"当前环境未配置 .pdf 解析器",recoverable:!0}};const o=await t.pdf.extract(i,e.fileName);if(n=o.text,r=o.pageCount,typeof r=="number"&&r>se.maxPdfPages)return{ok:!1,error:{code:"PDF_TOO_MANY_PAGES",message:`PDF 超过 ${se.maxPdfPages} 页上限`,recoverable:!0}}}if(n=String(n||"").trim(),n.length>se.maxExtractedChars)return{ok:!1,error:{code:"TEXT_TOO_LONG",message:`抽取文本超过 ${se.maxExtractedChars} 字符上限`,recoverable:!0}};if(!n)return{ok:!1,error:{code:"EMPTY_EXTRACT",message:"未能从文档中抽取到有效文本",recoverable:!0}};const a={fileName:e.fileName,mimeType:e.mimeType,kind:s,byteSize:i.byteLength,extractedChars:n.length,pageCount:r};return{ok:!0,text:n,meta:a}}catch(n){return{ok:!1,error:{code:"EXTRACT_FAILED",message:(n==null?void 0:n.message)||"文档解析失败,请重试或改用 .md",recoverable:!0}}}}}}function sn(){return Xi()}const Zi=()=>{throw new Error("fs is not available in FormStudio browser build")},rs=()=>{throw new Error("fs is not available in FormStudio browser build")},We=()=>!1,er=()=>{},tr=()=>{},xt=()=>{},Ct=(...t)=>t.filter(Boolean).join("/"),sr=/^(createdAt|updatedAt|timestamp|ts|now|expiresAt|issuedAt)$/i;function ir(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&Object.prototype.toString.call(t)==="[object Object]"}function lt(t,e={}){return JSON.stringify(nt(t,e))}function nt(t,e){if(t===null||typeof t!="object")return typeof t=="number"&&!Number.isFinite(t)?String(t):typeof t>"u"?null:t;if(Array.isArray(t))return t.map(n=>nt(n,e));if(!ir(t))return t instanceof Date?t.toISOString():String(t);const s=Object.keys(t).sort(),i={};for(const n of s){if(e.excludeVolatileTimestamps&&sr.test(n))continue;const r=t[n];typeof r>"u"||(i[n]=nt(r,e))}return i}const rr=/^(schema|brief|theme|password|secret|token|authorization|idcard|mobile|phone|bank|preview|value|values|raw)$/i;function ee(t){var s,i;const e={id:t.id||`aud_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,type:t.type,at:t.now||new Date().toISOString(),formKey:t.formKey,revisionId:t.revisionId,correlationId:t.correlationId,actorId:(s=t.actor)==null?void 0:s.id,actorType:(i=t.actor)==null?void 0:i.type,summary:t.summary?String(t.summary).slice(0,240):void 0,meta:nr(t.meta)};return t.attemptId&&String(t.attemptId).trim()&&(e.attemptId=String(t.attemptId).trim()),e}function nr(t){if(!t)return;const e={};for(const[s,i]of Object.entries(t)){if(rr.test(s)){e[s]="[redacted]";continue}i==null?e[s]=null:typeof i=="string"||typeof i=="number"||typeof i=="boolean"?e[s]=typeof i=="string"&&i.length>200?`${i.slice(0,200)}…`:i:e[s]="[redacted]"}return e}const D={VALIDATION:"VALIDATION",NOT_FOUND:"NOT_FOUND",STALE_VERSION:"STALE_VERSION",IMMUTABLE_HISTORY:"IMMUTABLE_HISTORY",IDEMPOTENCY_CONFLICT:"IDEMPOTENCY_CONFLICT",ILLEGAL_TRANSITION:"ILLEGAL_TRANSITION",CONFIRMATION_DENIED:"CONFIRMATION_DENIED",POLICY_DENIED:"POLICY_DENIED",RECOVERY_REQUIRED:"RECOVERY_REQUIRED"},G={NOT_FOUND_DRAFT:4002,NOT_FOUND_REVISION:4003,VALIDATION:4004,STALE_VERSION:4090,IMMUTABLE_HISTORY:4091,IDEMPOTENCY_CONFLICT:4092,ILLEGAL_TRANSITION:4093,CONFIRMATION_DENIED:4094,POLICY_DENIED:4095,CORRUPTION:4096,RECOVERY_REQUIRED:4097},or={VALIDATION:G.VALIDATION,NOT_FOUND:G.NOT_FOUND_DRAFT,STALE_VERSION:G.STALE_VERSION,IMMUTABLE_HISTORY:G.IMMUTABLE_HISTORY,IDEMPOTENCY_CONFLICT:G.IDEMPOTENCY_CONFLICT,ILLEGAL_TRANSITION:G.ILLEGAL_TRANSITION,CONFIRMATION_DENIED:G.CONFIRMATION_DENIED,POLICY_DENIED:G.POLICY_DENIED,CORRUPTION:G.CORRUPTION,RECOVERY_REQUIRED:G.RECOVERY_REQUIRED};class K extends Error{constructor(e){super(e.message),this.name="PersistenceError",this.code=e.code,this.legacyCode=e.legacyCode??or[e.code],this.correlationId=e.correlationId,this.details=e.details,e.cause!==void 0&&(this.cause=e.cause)}toLegacyShape(){return{message:this.message,code:this.legacyCode,stableCode:this.code}}}function J(t){const e=new K(t);throw Object.assign(new Error(e.message),{name:"PersistenceError",code:e.legacyCode,stableCode:e.code,legacyCode:e.legacyCode,correlationId:e.correlationId,details:e.details})}function ze(t){if(!t.operation||!String(t.operation).trim())throw new K({code:D.VALIDATION,message:"Fingerprint requires a non-empty operation"});if(!t.idempotencyKey||!String(t.idempotencyKey).trim())throw new K({code:D.VALIDATION,message:"Fingerprint requires a non-empty idempotencyKey"});const e={operation:String(t.operation).trim(),idempotencyKey:String(t.idempotencyKey).trim(),request:t.request},s=lt(e,{excludeVolatileTimestamps:!0});return Ke().update(s,"utf8").digest("hex")}function ar(t,e,s){if(!t||!e)throw new K({code:D.VALIDATION,message:"Idempotency fingerprint comparison requires both fingerprints",correlationId:s==null?void 0:s.correlationId});if(t!==e)throw new K({code:D.IDEMPOTENCY_CONFLICT,message:"Idempotency key reused with a different request fingerprint",correlationId:s==null?void 0:s.correlationId,details:{operation:(s==null?void 0:s.operation)||"",storedFingerprintPrefix:t.slice(0,12),nextFingerprintPrefix:e.slice(0,12)}})}const lr=Object.freeze({id:"local-compat",type:"local_compat"});let Nt=0;function cr(t){return Nt+=1,`local-corr-${t?String(t).slice(0,24):"anon"}-${Date.now()}-${Nt}`}function ur(t,e={}){const s=t==null?void 0:t.actor,i=t==null?void 0:t.correlationId;if(!e.allowLocalCompatDefaults){if(!s||!s.id||!s.type)throw new K({code:D.VALIDATION,message:"Mutation context requires actor.id and actor.type"});if(s.type==="local_compat")throw new K({code:D.POLICY_DENIED,message:"local_compat actor is not valid for production mutation contracts"});if(!i||typeof i!="string"||!i.trim())throw new K({code:D.VALIDATION,message:"Mutation context requires correlationId"});return{actor:{id:s.id,type:s.type},correlationId:i.trim(),expectedVersion:t==null?void 0:t.expectedVersion,idempotencyKey:t==null?void 0:t.idempotencyKey}}return{actor:s&&s.id&&s.type?{id:s.id,type:s.type}:{...lr},correlationId:i&&i.trim()?i.trim():cr(e.correlationSeed),expectedVersion:t==null?void 0:t.expectedVersion,idempotencyKey:t==null?void 0:t.idempotencyKey}}function dr(t,e=["web","vue-h5","miniapp"]){const s=[],i=z(t,{untrustedExpressions:!0});if(!i.valid)for(const a of i.issues)s.push(`[schema:${a.code}] ${a.path}: ${a.message}`);const n=Lt(t);for(const a of n)a.classification.kind==="legacy/untrusted"&&s.push(`[expression] ${a.path}: legacy/untrusted — ${a.classification.reason||a.expression.slice(0,60)}`);const r=[];for(const a of e){const o=gs(t,a);if(r.push({platform:a,summary:o.summary,verifiedEligible:o.verifiedEligible}),a==="web"||a==="vue-h5"){const l=o.issues.filter(c=>c.support==="unsupported"&&c.code==="CAPABILITY_UNSUPPORTED");for(const c of l)s.push(`[capability:${a}] ${c.path}: ${c.message}`)}}return{ok:s.length===0,errors:s,capabilitySummaries:r}}const fr=new Set(["synced","cancelled","expired","rolled_back"]),gr={preflight_pending:new Set(["preflight_passed","failed_retryable"]),preflight_passed:new Set(["awaiting_confirmation","cancelled","expired"]),awaiting_confirmation:new Set(["publishing","cancelled","expired"]),publishing:new Set(["published","failed_retryable"]),published:new Set(["sync_pending","rolled_back"]),sync_pending:new Set(["synced","failed_retryable"]),synced:new Set,failed_retryable:new Set(["publishing","sync_pending","cancelled"]),cancelled:new Set,expired:new Set,rolled_back:new Set};function pr(t){return fr.has(t)}function hr(t,e){const s=gr[t];return!!(s&&s.has(e))}function ns(t){const{from:e,to:s}=t;if(pr(e))throw new K({code:D.ILLEGAL_TRANSITION,message:`Terminal publish state ${e} cannot transition`,correlationId:t.correlationId,details:{from:e,to:s}});if(!hr(e,s))throw new K({code:D.ILLEGAL_TRANSITION,message:`Illegal publish transition ${e} -> ${s}`,correlationId:t.correlationId,details:{from:e,to:s,event:t.event||""}});if(s==="publishing"&&t.confirmationBound!==!0)throw new K({code:D.CONFIRMATION_DENIED,message:"Publishing requires an explicit confirmation binding",correlationId:t.correlationId,details:{from:e,to:s,confirmationBound:t.confirmationBound==null?"omitted":"false"}});return s}function $e(t,e,s){const i=ns({from:t.state,to:e,event:s==null?void 0:s.event,confirmationBound:s==null?void 0:s.confirmationBound,correlationId:t.correlationId});return{...t,state:i,updatedAt:(s==null?void 0:s.now)||t.updatedAt,attempts:i==="publishing"||i==="sync_pending"?t.attempts+(t.state==="failed_retryable"?1:0):t.attempts}}const mr={evaluate(t){return t.environment==="production"?{allowed:!1,code:D.POLICY_DENIED,reason:"Production publish is deny-by-default until identity and deployment gates are approved"}:t.actor.type==="ai"?{allowed:!1,code:D.POLICY_DENIED,reason:"AI actors cannot confirm or execute publish"}:t.actor.type==="local_compat"?{allowed:!1,code:D.POLICY_DENIED,reason:"local_compat actor is not an authorized publishing identity"}:t.action==="production_publish"?{allowed:!1,code:D.POLICY_DENIED,reason:"production_publish remains blocked"}:{allowed:!0,code:null,reason:"local/test policy allow"}}};function yr(){return mr}function Dt(t,e){const s=t.evaluate(e);if(!s.allowed)throw new K({code:s.code||D.POLICY_DENIED,message:s.reason,correlationId:e.correlationId,details:{action:e.action,environment:e.environment,actorType:e.actor.type}})}function kr(t){const e={schema:t.schema,brief:t.brief??null,authoringSnapshot:t.authoringSnapshot??null},s=lt(e,{excludeVolatileTimestamps:!0});return Ke().update(s,"utf8").digest("hex")}function _r(t){var i,n;if(!((i=t.actor)!=null&&i.id)||!((n=t.actor)!=null&&n.type))throw new K({code:D.VALIDATION,message:"Revision integrity requires actor"});if(!t.correlationId||!String(t.correlationId).trim())throw new K({code:D.VALIDATION,message:"Revision integrity requires correlationId"});if(!String(t.source).trim())throw new K({code:D.VALIDATION,message:"Revision integrity requires source"});const s={contentHash:kr({schema:t.schema,brief:t.brief,authoringSnapshot:t.authoringSnapshot}),parentRevisionId:t.parentRevisionId??null,actorId:t.actor.id,actorType:t.actor.type,source:String(t.source).trim(),correlationId:String(t.correlationId).trim(),acceptedChangeSummary:t.acceptedChangeSummary};return t.storeRevision!=null&&(s.storeRevision=t.storeRevision),t.etag!=null&&(s.etag=t.etag),s}const os=1;function br(){return{drafts:{},revisions:{},publishes:{},publishAttempts:{},auditEvents:[],idempotency:{},revisionCounter:0}}function vr(t){return Ke().update(lt(t),"utf8").digest("hex")}function Ir(t,e=os){return{envelopeVersion:e,integrityHash:vr(t),body:t}}function Sr(t){const e=os;return{sourceEnvelopeVersion:null,targetEnvelopeVersion:e,wouldMutate:!1,changes:[{path:"/",from:"absent",to:`envelope v${e} empty body`}],validForLoad:!0,notes:["Absent store initializes to empty envelope on first write"]}}function Ar(t){try{const e=JSON.parse(Zi(t,"utf8"));return e&&typeof e.pid=="number"&&typeof e.acquiredAtMs=="number"&&typeof e.acquiredAt=="string"?e:null}catch{return null}}function Er(t){const e=t.timeoutMs??3e3,s=t.staleMs??1e4,i=t.now??Date.now,n=i();for(;i()-n<=e;)try{const r=(void 0)(t.lockPath,"wx"),a={pid:process.pid,acquiredAt:new Date(i()).toISOString(),acquiredAtMs:i()};return rs(r,JSON.stringify(a),"utf8"),(void 0)(r),{release:()=>{try{xt(t.lockPath)}catch{}}}}catch(r){if(!r||r.code!=="EEXIST"&&r.code!=="EPERM")throw new K({code:D.RECOVERY_REQUIRED,message:"Unable to acquire store lock"});const a=Ar(t.lockPath);if((a?i()-a.acquiredAtMs:Number.POSITIVE_INFINITY)>s)try{xt(t.lockPath);continue}catch{}}throw new K({code:D.RECOVERY_REQUIRED,message:"Store lock acquisition timed out",details:{timeoutMs:e}})}async function Rr(t,e){const s=Er(t);try{return await e()}finally{s.release()}}function Y(t){return JSON.parse(JSON.stringify(t))}function wr(){return`form_studio_${Date.now()}_${Math.random().toString(36).slice(2,6)}`}function Tr(t){const e=/^v(\d+)\.(\d+)\.(\d+)$/.exec(t||"v0.0.0");if(!e)return"v0.1.0";const s=Number(e[1]),i=Number(e[2]),n=Number(e[3]);return n>=9?`v${s}.${i+1}.0`:`v${s}.${i}.${n+1}`}function Or(t,e){return`rev_${t}_${e.replace(/\./g,"_")}`}function $t(t){return t.type==="local_compat"?{id:"file-form-store",type:"system"}:t}class rn{constructor(e){this.policy=yr(),this.rootDir=e.rootDir,this.statePath=Ct(this.rootDir,"form-store.json"),this.lockPath=Ct(this.rootDir,"form-store.lock"),this.lockTimeoutMs=e.lockTimeoutMs??3e3,this.lockStaleMs=e.lockStaleMs??1e4,er(this.rootDir),this.state=this.loadBody()}dryRunMigration(){if(!We(this.statePath))return Sr()}listAuditEvents(e){const s=[...this.state.auditEvents].sort((i,n)=>{const r=i.at.localeCompare(n.at);return r!==0?r:i.id.localeCompare(n.id)});return Me(s,e).items}listPublishAttempts(e,s){this.reloadFromDisk();let i=Object.values(this.state.publishAttempts);return e&&(i=i.filter(n=>n.formKey===e)),i.sort((n,r)=>{const a=n.createdAt.localeCompare(r.createdAt);return a!==0?a:n.id.localeCompare(r.id)}),Me(i,s).items.map(Y)}getPublishAttempt(e){this.reloadFromDisk();const s=this.state.publishAttempts[e];return s?Y(s):null}async upsertPublishAttempt(e){return this.withMutationLock(()=>((!(e!=null&&e.id)||typeof e.id!="string")&&J({code:D.VALIDATION,message:"Publish attempt id is required"}),this.state.publishAttempts[e.id]=Y(e),this.persist(),Y(e)))}async peekFingerprintIdempotency(e,s){return this.withMutationLock(()=>{const i=this.readIdempotency(e,s);return i?(i.didBindLegacy&&this.persist(),i.result):null})}async putFingerprintIdempotency(e,s,i){await this.withMutationLock(()=>{this.writeIdempotency(e,s,i,new Date().toISOString()),this.persist()})}async importLegacyOrchestrationFile(e){return this.withMutationLock(()=>({importedAttempts:0,importedIdempotency:0,archived:!1}))}listDraftsPage(e){const s=Object.values(this.state.drafts).map(i=>({key:i.key,name:i.name,version:i.version,status:i.status,updatedAt:i.meta.updatedAt})).sort((i,n)=>{const r=i.key.localeCompare(n.key);return r!==0?r:i.updatedAt.localeCompare(n.updatedAt)});return Me(s,e)}listRevisionsPage(e,s){const i=Object.values(this.state.revisions).filter(n=>n.formKey===e).sort((n,r)=>{const a=n.createdAt.localeCompare(r.createdAt);if(a!==0)return a;const o=(n.storeRevision||0)-(r.storeRevision||0);return o!==0?o:n.id.localeCompare(r.id)}).map(Y);return Me(i,s)}loadBody(){if(!We(this.statePath))return br()}reloadFromDisk(){this.state=this.loadBody()}persist(){const e=Ir(this.state),s=`${this.statePath}.${process.pid}.${Date.now()}.tmp`;rs(s,JSON.stringify(e,null,2)),tr(s,this.statePath)}callerCorrelationId(e){var i;const s=(i=e==null?void 0:e.mutation)==null?void 0:i.correlationId;if(typeof s=="string"&&s.trim())return s.trim()}async withMutationLock(e,s){try{return await Rr({lockPath:this.lockPath,timeoutMs:this.lockTimeoutMs,staleMs:this.lockStaleMs},async()=>(this.reloadFromDisk(),await e()))}catch(i){if(i instanceof K&&i.code===D.RECOVERY_REQUIRED||(i==null?void 0:i.stableCode)===D.RECOVERY_REQUIRED||(i==null?void 0:i.code)===G.RECOVERY_REQUIRED){const r=s!=null&&s.correlationId&&String(s.correlationId).trim()?String(s.correlationId).trim():void 0;this.appendAuditUnlocked(ee({type:"lock_timeout",summary:"Store lock acquisition failed",...r?{correlationId:r}:{},meta:{code:D.RECOVERY_REQUIRED}}))}throw i instanceof K&&J({code:i.code,message:i.message,details:i.details,legacyCode:i.legacyCode,correlationId:i.correlationId}),i}}appendAuditUnlocked(e){try{if(!We(this.statePath))return;this.reloadFromDisk(),this.state.auditEvents.push(e),this.persist()}catch{}}appendAudit(e){this.state.auditEvents.push(e)}resolveCtx(e){var s,i;return ur({...(e==null?void 0:e.mutation)||{},expectedVersion:((s=e==null?void 0:e.mutation)==null?void 0:s.expectedVersion)??(e==null?void 0:e.expectedVersion),idempotencyKey:((i=e==null?void 0:e.mutation)==null?void 0:i.idempotencyKey)??(e==null?void 0:e.idempotencyKey)},{allowLocalCompatDefaults:!0})}readIdempotency(e,s,i){const n=this.state.idempotency[e];if(!n)return null;try{return n.fingerprint?(ar(n.fingerprint,s,{correlationId:i}),{result:Y(n.result),didBindLegacy:!1}):(n.fingerprint=s,{result:Y(n.result),didBindLegacy:!0})}catch(r){throw r instanceof K&&r.code===D.IDEMPOTENCY_CONFLICT&&(this.appendAudit(ee({type:"idempotency_conflict",correlationId:i,summary:"Idempotency key reused with different fingerprint",meta:{slot:e}})),this.persist(),J({code:D.IDEMPOTENCY_CONFLICT,message:r.message,correlationId:i,details:r.details})),r}}writeIdempotency(e,s,i,n){this.state.idempotency[e]={fingerprint:s,result:Y(i),storedAt:n}}async saveDraft(e){return this.withMutationLock(()=>this.saveDraftLocked(e,{sourceOverride:void 0}),{correlationId:this.callerCorrelationId(e)})}saveDraftLocked(e,s={}){const i=this.resolveCtx(e),n=e.idempotencyKey?ze({operation:"saveDraft",idempotencyKey:e.idempotencyKey,request:{key:e.key||null,name:e.name||null,schema:e.schema,brief:e.brief??null,theme:e.theme??null,expectedVersion:e.expectedVersion??null,author:e.author||null,source:s.sourceOverride||e.source||"save",changeSummary:e.changeSummary||null,appendRevision:e.appendRevision!==!1,actorId:i.actor.id,actorType:i.actor.type}}):"",r=e.idempotencyKey?`save:${e.idempotencyKey}`:"";if(r&&!s.skipIdempotency){const _=this.readIdempotency(r,n,i.correlationId);if(_)return _.didBindLegacy&&this.persist(),_.result}const a=new Date().toISOString(),o=!e.key,l=e.key||wr(),c=this.state.drafts[l];!o&&!c&&J({code:D.NOT_FOUND,message:`表单 ${l} 不存在`,legacyCode:G.NOT_FOUND_DRAFT,correlationId:i.correlationId}),e.expectedVersion!=null&&c&&c.version!==e.expectedVersion&&(this.appendAudit(ee({type:"draft_conflict",formKey:l,correlationId:i.correlationId,actor:i.actor,summary:"Stale expectedVersion on save",meta:{expectedVersion:e.expectedVersion,actualVersion:c.version},now:a})),this.persist(),J({code:D.STALE_VERSION,message:`版本冲突: expected ${e.expectedVersion}, actual ${c.version}`,correlationId:i.correlationId}));const u=o?"v0.1.0":Tr(c.version);let d;const f=s.sourceOverride||e.source||"save";if(e.appendRevision!==!1){d=Or(l,u),this.state.revisions[d]&&J({code:D.IMMUTABLE_HISTORY,message:`revision 已存在且不可变: ${d}`,correlationId:i.correlationId}),this.state.revisionCounter+=1;const _=this.state.revisionCounter,m=e.brief!=null?Y(e.brief):(c==null?void 0:c.brief)||null,S=Y(e.schema),h=_r({schema:S,brief:m,parentRevisionId:(c==null?void 0:c.meta.lastRevisionId)||null,actor:i.actor,source:f,correlationId:i.correlationId,acceptedChangeSummary:e.changeSummary,storeRevision:_,etag:`etag_${_}`}),b={id:d,formKey:l,version:u,schema:S,brief:m,author:e.author||i.actor.id,source:f,changeSummary:e.changeSummary,createdAt:a,immutable:!0,contentHash:h.contentHash,parentRevisionId:h.parentRevisionId,actorId:h.actorId,actorType:h.actorType,correlationId:h.correlationId,acceptedChangeSummary:h.acceptedChangeSummary,storeRevision:h.storeRevision,etag:h.etag};this.state.revisions[d]=b}const g={key:l,name:e.name||(c==null?void 0:c.name)||"未命名表单",schema:Y(e.schema),brief:e.brief!=null?Y(e.brief):(c==null?void 0:c.brief)||null,theme:e.theme!=null?Y(e.theme):c==null?void 0:c.theme,status:"draft",version:u,meta:{createdAt:(c==null?void 0:c.meta.createdAt)||a,updatedAt:a,lastRevisionId:d||(c==null?void 0:c.meta.lastRevisionId)}};this.state.drafts[l]=g;const y={key:l,version:u,status:g.status,revisionId:d};return this.appendAudit(ee({type:f==="rollback"?"restore":"draft_save",formKey:l,revisionId:d,correlationId:i.correlationId,actor:i.actor,summary:e.changeSummary||f,meta:{version:u,source:f},now:a})),r&&!s.skipIdempotency&&this.writeIdempotency(r,n,y,a),this.persist(),y}async getDraft(e){const s=this.state.drafts[e];return s||J({code:D.NOT_FOUND,message:`表单 ${e} 不存在`,legacyCode:G.NOT_FOUND_DRAFT}),Y(s)}async listDrafts(){return this.listDraftsPage().items}async listRevisions(e){return this.listRevisionsPage(e).items}async getRevision(e){const s=this.state.revisions[e];return s||J({code:D.NOT_FOUND,message:`revision ${e} 不存在`,legacyCode:G.NOT_FOUND_REVISION}),Y(s)}async testPublish(e){return this.withMutationLock(()=>this.testPublishLocked(e),{correlationId:this.callerCorrelationId(e)})}testPublishLocked(e){const s=this.resolveCtx(e),i=$t(s.actor),n=e.platforms||["web","vue-h5","miniapp"],r=ze({operation:"testPublish",idempotencyKey:e.idempotencyKey,request:{key:e.key,expectedVersion:e.expectedVersion??null,platforms:n,environment:"test",actorId:i.id,actorType:i.type}}),a=`testPublish:${e.idempotencyKey}`,o=this.readIdempotency(a,r,s.correlationId);if(o)return o.didBindLegacy&&this.persist(),o.result;const l=this.state.drafts[e.key];l||J({code:D.NOT_FOUND,message:`表单 ${e.key} 不存在`,legacyCode:G.NOT_FOUND_DRAFT,correlationId:s.correlationId}),e.expectedVersion&&l.version!==e.expectedVersion&&J({code:D.STALE_VERSION,message:`版本冲突: expected ${e.expectedVersion}, actual ${l.version}`,correlationId:s.correlationId});const c=l.meta.lastRevisionId||"",u=c?this.state.revisions[c]:void 0,d=(u==null?void 0:u.contentHash)||"";Dt(this.policy,{actor:i,action:"test_publish",environment:"test",formKey:e.key,revisionId:c,contentHash:d,correlationId:s.correlationId});const f=dr(l.schema,n),g=new Date().toISOString(),y=`pub_${e.key}_${Date.now()}`,_=!!e.skipAttemptRecord;let m;if(!f.ok){if(!_){const b=`pa_${e.key}_${Date.now()}`;m=b;let A={id:b,formKey:e.key,revisionId:c,contentHash:d,environment:"test",requestedPlatforms:n,state:"preflight_pending",actorId:i.id,actorType:i.type,confirmation:null,idempotencyKey:e.idempotencyKey,requestFingerprint:r,correlationId:s.correlationId,attempts:1,createdAt:g,updatedAt:g};this.appendAudit(ee({type:"preflight",formKey:e.key,revisionId:c,correlationId:s.correlationId,attemptId:b,actor:i,summary:"preflight failed",meta:{ok:!1,errorCount:f.errors.length},now:g})),A={...A,state:ns({from:"preflight_pending",to:"failed_retryable",correlationId:s.correlationId}),gateReportSummary:f.errors.join("; ").slice(0,500),errorCode:D.VALIDATION,errorMessage:f.errors.join("; ").slice(0,500),updatedAt:g},this.state.publishAttempts[b]=A}const h={id:y,formKey:e.key,revisionId:c,version:l.version,kind:"test",status:"failed",idempotencyKey:e.idempotencyKey,createdAt:g,error:f.errors.join("; ")};return this.state.publishes[y]=h,this.writeIdempotency(a,r,h,g),this.persist(),h}if(!_){const h=`pa_${e.key}_${Date.now()}`;m=h;let b={id:h,formKey:e.key,revisionId:c,contentHash:d,environment:"test",requestedPlatforms:n,state:"preflight_pending",actorId:i.id,actorType:i.type,confirmation:null,idempotencyKey:e.idempotencyKey,requestFingerprint:r,correlationId:s.correlationId,attempts:1,createdAt:g,updatedAt:g};this.appendAudit(ee({type:"preflight",formKey:e.key,revisionId:c,correlationId:s.correlationId,attemptId:h,actor:i,summary:"preflight passed",meta:{ok:!0,errorCount:0},now:g})),b=$e(b,"preflight_passed",{now:g}),b=$e(b,"awaiting_confirmation",{now:g});const A={confirmationToken:`local-test:${e.idempotencyKey}`,actorId:i.id,actorType:i.type,revisionId:c,contentHash:d,environment:"test",expiresAt:new Date(Date.now()+6e4).toISOString()};b={...b,confirmation:A},this.appendAudit(ee({type:"confirmation",formKey:e.key,revisionId:c,correlationId:s.correlationId,attemptId:h,actor:i,summary:"explicit testPublish confirmation",meta:{confirmationToken:"[redacted]"},now:g})),b=$e(b,"publishing",{confirmationBound:!0,now:g}),b=$e(b,"published",{now:g}),b={...b,gateReportSummary:"ok",downstreamState:"local_only",storePublishId:y},this.state.publishAttempts[h]=b}l.status="test_published",l.meta.updatedAt=g,this.state.drafts[e.key]=l;const S={id:y,formKey:e.key,revisionId:c,version:l.version,kind:"test",status:"published",idempotencyKey:e.idempotencyKey,createdAt:g};return this.state.publishes[y]=S,this.appendAudit(ee({type:"test_publish",formKey:e.key,revisionId:c,correlationId:s.correlationId,attemptId:m,actor:i,summary:"test publish succeeded",meta:_?{publishId:y,skipAttemptRecord:!0}:{publishId:y},now:g})),this.writeIdempotency(a,r,S,g),this.persist(),S}async rollbackToRevision(e){return this.withMutationLock(()=>{var o,l,c;const s=this.resolveCtx(e),i=(o=e.mutation)!=null&&o.idempotencyKey?ze({operation:"rollbackToRevision",idempotencyKey:e.mutation.idempotencyKey,request:{key:e.key,revisionId:e.revisionId,author:e.author||null,actorId:s.actor.id}}):"",n=(l=e.mutation)!=null&&l.idempotencyKey?`rollback:${e.mutation.idempotencyKey}`:"";if(n){const u=this.readIdempotency(n,i,s.correlationId);if(u)return u.didBindLegacy&&this.persist(),u.result}const r=this.state.revisions[e.revisionId];r||J({code:D.NOT_FOUND,message:`revision ${e.revisionId} 不存在`,legacyCode:G.NOT_FOUND_REVISION,correlationId:s.correlationId}),r.formKey!==e.key&&J({code:D.VALIDATION,message:"revision 不属于该表单",correlationId:s.correlationId});const a=this.saveDraftLocked({key:e.key,schema:r.schema,brief:r.brief,expectedVersion:(c=this.state.drafts[e.key])==null?void 0:c.version,author:e.author||"rollback",source:"rollback",changeSummary:`rollback to ${r.id}`,appendRevision:!0,mutation:{actor:s.actor,correlationId:s.correlationId}},{sourceOverride:"rollback",skipIdempotency:!0});return this.appendAudit(ee({type:"rollback",formKey:e.key,revisionId:a.revisionId,correlationId:s.correlationId,actor:s.actor,summary:`rollback to ${e.revisionId}`,meta:{fromRevisionId:e.revisionId}})),n&&this.writeIdempotency(n,i,a,new Date().toISOString()),this.persist(),a},{correlationId:this.callerCorrelationId(e)})}async productionPublish(e){return this.withMutationLock(()=>{const s=this.resolveCtx(e),i=$t(s.actor),n=new Date().toISOString();try{Dt(this.policy,{actor:i,action:"production_publish",environment:"production",formKey:e.key,revisionId:"",correlationId:s.correlationId})}catch{}const r={id:`pub_blocked_${Date.now()}`,formKey:e.key,revisionId:"",version:"",kind:"production",status:"blocked",idempotencyKey:e.idempotencyKey,createdAt:n,error:"Production publish is deny-by-default until identity and deployment gates are approved"};return this.state.publishes[r.id]=r,this.appendAudit(ee({type:"production_blocked",formKey:e.key,correlationId:s.correlationId,actor:i,summary:"production publish denied",meta:{idempotencyKey:e.idempotencyKey},now:n})),this.persist(),r},{correlationId:this.callerCorrelationId(e)})}tryMutateRevision(e,s){const i=this.state.revisions[e];return i?i.immutable?{ok:!1,error:"IMMUTABLE"}:(i.schema=s,this.persist(),{ok:!0}):{ok:!1,error:"NOT_FOUND"}}}function Me(t,e){const s=e==null?void 0:e.limit;let i=0;if(e!=null&&e.cursor){const o=t.findIndex(l=>(l.id||l.key)===e.cursor);i=o>=0?o+1:0}if(s==null||s<=0)return{items:t.slice(i)};const n=t.slice(i,i+s),r=n[n.length-1],a=n.length===s&&i+s<t.length?(r==null?void 0:r.id)||(r==null?void 0:r.key):void 0;return{items:n,nextCursor:a}}export{Q as ArchitectError,cs as CAPABILITY_MANIFESTS,ei as EDIT_TASK_CONTRACT_VERSION,je as ExpressionError,Ut as FORM_KNOWLEDGE_VERSION,rn as FileFormStore,Fr as FixtureLlmAdapter,Vr as FormArchitect,As as FormCore,bt as GENERATE_OUTPUT_SCHEMA_VERSION,_t as OUTPUT_SCHEMA_VERSION,an as PREVIEW_HOST_PROTOCOL_VERSION,ln as PREVIEW_IO_POLICY_ID,cn as PREVIEW_LAYER_LABELS,Ie as PROMPT_VERSION,un as PreviewOrchestrator,dn as PreviewTrialBag,se as REQUIREMENT_LIMITS,fn as TARGET_PREVIEW_PAYLOAD_VERSION,fs as VALID_CONTROL_TYPES,us as VALID_EFFECTS,ds as VALID_RULE_TYPES,gn as VALID_VALUE_TYPES,Ii as WorkspaceSession,Xe as adjustValueType,et as analyzeIntent,ai as answerClarification,ne as applyChangeSet,Ri as assertArchitectInputSafe,qr as assertNoSensitivePayload,Ci as assessRequirement,pn as attachPreviewIoGuards,tn as buildDxImportReport,Yt as buildEditTaskContract,hn as buildEnvelope,Ys as buildFormDomainKnowledge,Gt as buildFormUnderstanding,Lr as buildImpactReport,Pr as buildRedactedAiRunRecord,mn as buildTargetPreviewPayload,Ee as calculateValueFromLogicStr,Zs as checkExplicitEditConstraints,ve as classifyExpression,Lt as classifySchemaExpressions,le as cloneObj,Yr as commitCatalogStatus,Es as convertComponent,Ti as createContractBrief,yn as createDefaultAdapter,me as createEmptyBrief,Kr as createFunctionLlmAdapter,kn as createHostProtocolClient,_n as createHostProtocolResponder,Wr as createMemoryArchitectPort,sn as createMemoryRequirementDocumentPort,bn as createMemoryTransport,zr as createMemoryWorkspaceRepository,vn as createMiniappPreviewAdapter,In as createPreviewIoCounters,Sn as createPreviewRuntime,An as createPreviewStorageAdapter,En as createRequestId,Xi as createRequirementDocumentPort,Rn as createRnPreviewAdapter,wn as createTaroH5PreviewAdapter,Tn as createVueH5PreviewAdapter,On as createWebPreviewAdapter,Xr as createWorkspaceController,Bt as deriveExplicitEditConstraints,xn as deriveSchemaRevision,Qi as detectDocumentKind,Pt as detectRisks,Fs as diffSchemas,hs as evaluateExpression,qt as explainChangeSet,Oi as extractEvidenceDraft,xi as findClarificationGaps,Nr as findNodePath,Qr as flattenRequirementText,Cr as generateFunctionFromStr,Ur as getBuiltinCatalog,ks as getByteLen,Cn as getCapabilityManifest,Re as getCatalogEntry,di as hashPrompt,Jr as hydrateCatalogStatusFromStorage,Os as inferType,ss as initCoreWithTrialValues,es as instantiateCatalogEntry,Mt as isSafeV1Expression,Nn as isTargetPlatform,Dn as isTrialSafe,ut as isValidValue,jr as listLocalDraftEntries,Ni as mayCreateApplyableProposal,Js as mentionedPlatforms,$r as oldConfigToSchema,hi as persistCatalogStatusOverlay,Si as pickCompatibleTrialValues,Hr as previewCatalogInsert,It as questionsFromStrings,ts as rebuildFormCoreWithValues,Ei as redactSensitiveArchitectInput,Dr as resolveRelationChain,Vt as resolveRelations,Yi as runFormScenario,en as runFormScenarios,Zr as runInstantSemanticProbe,dr as runPublishGates,Hi as sanitizeImportedSchema,Mr as schemaToQuestionnaire,Br as searchCatalog,pi as transitionCatalogStatus,ms as tryConvertToSafeV1,Pi as tryFastGenerateSchema,Ki as tryParseFastFieldEdit,Gr as upsertLocalDraftEntry,gs as validateCapabilities,Ce as validateControlValue,z as validateFormSchema,$n as validatePreviewHostMessage,Mn as validateTargetPreviewReceipt};
|