openxiangda-contracts 2.16.1 → 2.16.2

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.
@@ -1,8 +1,8 @@
1
- import{createHash as jn}from"node:crypto";function Wn(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function et(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`JSON number must be finite: ${t}`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map((n,s)=>et(n,`${t}[${s}]`)).join(",")}]`;if(Wn(e))return`{${Object.keys(e).filter(s=>e[s]!==void 0).sort((s,r)=>s===r?0:s<r?-1:1).map(s=>`${JSON.stringify(s)}:${et(e[s],`${t}.${s}`)}`).join(",")}}`;let o=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${o})`)}function H(e){return et(e,"$")}function X(e){return jn("sha256").update(H(e)).digest("hex")}var vt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,nt=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Bn=["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","date-range","datetime-range","option.single","option.multiple","cascade.single","cascade.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple","image","signature","address","location","uuid","json","file","serial-number","subtable"],Jn=new Set(Bn),Lt=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),Vt=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),wt=new Set(["resource-ref.single","resource-ref.multiple"]),ot=[{code:"id",type:"uuid",nullable:!1},{code:"revision",type:"number.integer",nullable:!1},{code:"created_by",type:"text.short",nullable:!1},{code:"updated_by",type:"text.short",nullable:!1},{code:"created_at",type:"datetime",nullable:!1},{code:"updated_at",type:"datetime",nullable:!1}],ni=new Map(ot.map(e=>[e.code,e])),ue=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function je(e){return Lt.has(e)}function We(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!je(e.type)||t.requiredHint===!0)}function st(e,t,o=500){Array.isArray(e)||h("NATIVE_ARRAY_REQUIRED",t),e.length===0&&h("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&h("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((s,r)=>{let a=`${t}/${r}`,i=oe(s,a);re(i,["code","type","nullable","indexed","options","source","maxLength","precision","scale","min","max","rangeBoundary","timePrecision","file","serial","subtable"],a);let l=ae(i.code,`${a}/code`,63);vt.test(l)||h("NATIVE_FIELD_CODE_INVALID",`${a}/code`),n.has(l)&&h("NATIVE_DATA_FIELD_DUPLICATE",`${a}/code`),n.add(l);let p=ae(i.type,`${a}/type`,32);Jn.has(p)||h("NATIVE_DATA_FIELD_TYPE_INVALID",`${a}/type`);let _=p,d=Pt(i.nullable,`${a}/nullable`),c=Pt(i.indexed,`${a}/indexed`);d===!0&&Lt.has(_)&&h("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${a}/nullable`);let A=Yn(i.options,_,a),f=Hn(i.source,_,a),E=qn(i,_,a),N=Gn(i.rangeBoundary,_,a),m=Xn(i.file,_,a),g=Qn(i.serial,_,a),T=Zn(i.subtable,_,a);return{code:l,type:_,...d===void 0?{}:{nullable:d},...c===void 0?{}:{indexed:c},...A?{options:A}:{},...f?{source:f}:{},...E,...N?{rangeBoundary:N}:{},...m?{file:m}:{},...g?{serial:g}:{},...T?{subtable:T}:{}}})}function Gn(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&h("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&h("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function kt(e,t){Array.isArray(e)||h("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,s)=>{let r=`${t}/${s}`,a=oe(n,r),i=ae(a.code,`${r}/code`,64);(!nt.test(i)||o.has(i))&&h("NATIVE_RESOURCE_CODE_INVALID",`${r}/code`);let l=oe(a.schema,`${r}/schema`);o.set(i,{pointer:r,fields:st(l.fields,`${r}/schema/fields`)})});for(let[n,s]of o){let r=new Map(s.fields.map(i=>[i.code,i]));s.fields.filter(i=>i.type==="subtable").reduce((i,l)=>i+(l.subtable?.maxRows??20),0)>49&&h("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${s.pointer}/schema/fields`),s.fields.forEach((i,l)=>{let p=`${s.pointer}/schema/fields/${l}`;if(i.source&&zn(i.source,r,o,`${p}/source`),i.subtable){let _=o.get(i.subtable.resourceCode);(!_||i.subtable.resourceCode===n)&&h("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${p}/subtable/resourceCode`);let d=_.fields.find(A=>A.code===i.subtable?.foreignKey);(!d||d.type!=="uuid"||d.nullable!==!1)&&h("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${p}/subtable/foreignKey`);let c=_.fields.find(A=>A.code===i.subtable?.orderField);(!c||c.type!=="number.integer"||c.nullable!==!1)&&h("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${p}/subtable/orderField`)}})}}function xt(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&h("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(r=>[r.code,r])),s=new Set;return e.map((r,a)=>{let i=`${o}/${a}`,l=oe(r,i);re(l,["code","message","expression"],i);let p=ae(l.code,`${i}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(p)||s.has(p))&&h("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${i}/code`),s.add(p);let _=Me(l.message,`${i}/message`,500);_!==void 0&&_.length===0&&h("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${i}/message`);let d=oe(l.expression,`${i}/expression`);re(d,["leftField","operator","rightField"],`${i}/expression`);let c=fe(d.leftField,`${i}/expression/leftField`),A=fe(d.rightField,`${i}/expression/rightField`),f=n.get(c),E=n.get(A);(!f||!E)&&h("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${i}/expression`),f.type===E.type||["number.integer","number.decimal"].includes(f.type)&&["number.integer","number.decimal"].includes(E.type)||h("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${i}/expression`);let m=String(d.operator);return["eq","neq","gt","gte","lt","lte"].includes(m)||h("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${i}/expression/operator`),!["eq","neq"].includes(m)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(f.type)&&h("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${i}/expression`),{code:p,..._===void 0?{}:{message:_},expression:{leftField:c,operator:m,rightField:A}}})}function zn(e,t,o,n){let s=o.get(e.resourceCode);s||h("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let r=new Map(s.fields.map(i=>[i.code,i])),a=r.get(e.labelField);(!a||!["text.short","text.long"].includes(a.type))&&h("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let i of["searchFields","descriptionFields","snapshotFields"])for(let l of e[i]||[])r.has(l)||h("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${i}`);for(let[i,l]of(e.filters||[]).entries())r.has(l.field)||h("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${i}/field`),"binding"in l&&!t.has(l.binding.field)&&h("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${i}/binding/field`)}function Yn(e,t,o){let n=`${o}/options`;if(e===void 0){Vt.has(t)&&h("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!Vt.has(t)||!Array.isArray(e))&&h("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&h("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let s=0,r=(a,i,l)=>{l>5&&h("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",i);let p=new Set;return a.map((_,d)=>{s+=1,s>1e3&&h("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let c=`${i}/${d}`,A=oe(_,c);re(A,["label","value","description","color","children"],c);let f=ae(A.label,`${c}/label`,500),E=ae(A.value,`${c}/value`,500);p.has(E)&&h("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${c}/value`),p.add(E);let N=Me(A.description,`${c}/description`,2e3),m=Me(A.color,`${c}/color`,64),g;return A.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(A.children))&&h("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${c}/children`),(A.children.length<1||A.children.length>100)&&h("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${c}/children`),g=r(A.children,`${c}/children`,l+1)),{label:f,value:E,...N===void 0?{}:{description:N},...m===void 0?{}:{color:m},...g?{children:g}:{}}})};return r(e,n,1)}function Hn(e,t,o){let n=`${o}/source`;if(e===void 0){wt.has(t)&&h("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}wt.has(t)||h("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let s=oe(e,n);re(s,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode"],n),s.kind!=="resource"&&h("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let r=ae(s.resourceCode,`${n}/resourceCode`,64);nt.test(r)||h("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=fe(s.labelField,`${n}/labelField`),i=tt(s.searchFields,`${n}/searchFields`,10),l=tt(s.descriptionFields,`${n}/descriptionFields`,10),p=tt(s.snapshotFields,`${n}/snapshotFields`,50),_=be(s.pageSize,`${n}/pageSize`,1,100),d;s.loadMode!==void 0&&(["search","all"].includes(String(s.loadMode))||h("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),d=s.loadMode);let c=Kn(s.filters,`${n}/filters`);return{kind:"resource",resourceCode:r,labelField:a,...i?{searchFields:i}:{},...l?{descriptionFields:l}:{},...p?{snapshotFields:p}:{},...c?{filters:c}:{},..._===void 0?{}:{pageSize:_},...d?{loadMode:d}:{}}}function Kn(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&h("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,n)=>{let s=`${t}/${n}`,r=oe(o,s),a=Object.prototype.hasOwnProperty.call(r,"value"),i=Object.prototype.hasOwnProperty.call(r,"binding");re(r,a?["field","operator","value"]:["field","operator","binding"],s),a===i&&h("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",s);let l=fe(r.field,`${s}/field`);["eq","in"].includes(String(r.operator))||h("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${s}/operator`);let p=r.operator;if(a)return{field:l,operator:p,value:r.value};let _=oe(r.binding,`${s}/binding`);return re(_,["kind","field"],`${s}/binding`),_.kind!=="field"&&h("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${s}/binding/kind`),{field:l,operator:p,binding:{kind:"field",field:fe(_.field,`${s}/binding/field`)}}})}function qn(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||h("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=Ue(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&h("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=Ue(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:Ue(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||h("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let s=Ft(e.min,`${o}/min`),r=Ft(e.max,`${o}/max`);t==="number.integer"&&[s,r].some(a=>a!==void 0&&!Number.isSafeInteger(a))&&h("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),s!==void 0&&r!==void 0&&s>r&&h("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),s!==void 0&&(n.min=s),r!==void 0&&(n.max=r)}return e.timePrecision!==void 0&&((t!=="time"||!["minute","second"].includes(e.timePrecision))&&h("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function Xn(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||h("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let s=oe(e,n);re(s,["maxCount","maxSizeMb","accept"],n);let r=be(s.maxCount,`${n}/maxCount`,1,100);t==="signature"&&r!==void 0&&r!==1&&h("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let a=be(s.maxSizeMb,`${n}/maxSizeMb`,1,1024),i;return s.accept!==void 0&&((!Array.isArray(s.accept)||s.accept.length>50)&&h("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),i=s.accept.map((l,p)=>ae(l,`${n}/accept/${p}`,255)),new Set(i).size!==i.length&&h("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...r===void 0?{}:{maxCount:r},...a===void 0?{}:{maxSizeMb:a},...i===void 0?{}:{accept:i}}}function Qn(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&h("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&h("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let s=oe(e,n);re(s,["prefix","digits","start"],n);let r=Me(s.prefix,`${n}/prefix`,64),a=be(s.digits,`${n}/digits`,1,32),i=be(s.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...r===void 0?{}:{prefix:r},...a===void 0?{}:{digits:a},...i===void 0?{}:{start:i}}}function Zn(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&h("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&h("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let s=oe(e,n);re(s,["resourceCode","foreignKey","orderField","maxRows"],n);let r=ae(s.resourceCode,`${n}/resourceCode`,64);nt.test(r)||h("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=fe(s.foreignKey,`${n}/foreignKey`),i=fe(s.orderField,`${n}/orderField`);i===a&&h("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let l=be(s.maxRows,`${n}/maxRows`,1,49);return{resourceCode:r,foreignKey:a,orderField:i,...l===void 0?{}:{maxRows:l}}}function tt(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&h("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((s,r)=>fe(s,`${t}/${r}`));return new Set(n).size!==n.length&&h("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function fe(e,t){let o=ae(e,t,63);return vt.test(o)||h("NATIVE_FIELD_CODE_INVALID",t),o}function oe(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&h("NATIVE_OBJECT_REQUIRED",t),e}function re(e,t,o){let n=new Set(t);for(let s of Object.keys(e))n.has(s)||h("NATIVE_PROPERTY_UNKNOWN",`${o}/${s}`)}function ae(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&h("NATIVE_STRING_INVALID",t),e}function Me(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&h("NATIVE_STRING_INVALID",t),e}function Pt(e,t){if(e!==void 0)return typeof e!="boolean"&&h("NATIVE_BOOLEAN_REQUIRED",t),e}function be(e,t,o,n){if(e!==void 0)return Ue(e,t,o,n)}function Ft(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&h("NATIVE_NUMBER_REQUIRED",t),e}function Ue(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&h("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function h(e,t){throw new ue(e,t)}var Ut=["created_by","updated_by","created_at","updated_at"];function Se(e){return Ut.includes(e)}function Mt(e){return Ut.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var eo=ot.map(e=>e.code);function jt(e){return eo.includes(e)}var to=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],no=new Set(to);function ri(e){return no.has(String(e))}var it=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],ye=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],oo=["eq","neq","in","isEmpty"],Be=["eq","neq","in","isEmpty","isNotEmpty"],Oe=["has","hasAny","hasAll","isEmpty","isNotEmpty"],Wt=["overlaps","contains","containedBy","isEmpty"],rt=["jsonContains","isEmpty","isNotEmpty"],at=["isEmpty","isNotEmpty"],so={"text.short":it,"text.long":it,"text.rich":it,"number.integer":ye,"number.decimal":ye,boolean:oo,date:ye,time:ye,datetime:ye,"date-range":Wt,"datetime-range":Wt,"option.single":Be,"option.multiple":Oe,"cascade.single":Oe,"cascade.multiple":Oe,"user.single":Be,"user.multiple":Oe,"department.single":Be,"department.multiple":Oe,"resource-ref.single":Be,"resource-ref.multiple":Oe,file:at,image:at,signature:at,address:rt,location:rt,uuid:["eq","neq","in","isEmpty"],json:rt,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},io=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),ro=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function Jt(e){return so[e]}function ai(e,t){return Jt(e).includes(t)}function ct(e){return io.has(e)}function dt(e){return!ro.has(e)}function Gt(e){return Jt(e).length>0}var Bt=new Set(["number.integer","number.decimal"]),zt=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),ao=new Set([...zt,"boolean","uuid"]),co=new Set(["option.single","user.single","department.single","resource-ref.single"]);function ci(e,t){return t==="sum"||t==="avg"?Bt.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?zt.has(e)?{valueExpression:"column",numericResult:Bt.has(e)}:null:co.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:ao.has(e)?{valueExpression:"column",numericResult:!0}:null}var lo=500,pe={surface:["mutationOwner","generated","fields","list","form","detail","mobile","views"],generated:["list","detail","create","update","delete"],field:["label","type","widget","section","requiredHint","system","hidden","readCapabilities","createCapabilities","updateCapabilities","maxLength","precision","scale","min","max","rangeBoundary","maxCount","maxSizeMb","accept","options","list","searchable","sortable","source","timePrecision","serial","subtable"],list:["actions","fieldOrder","defaultPageSize","searchableFields","filterFields","defaultSort"],defaultSort:["field","order"],layout:["layout","fieldOrder"],mobile:["enabled"]},uo={"text.short":["text","email","phone"],"text.long":["textarea"],"text.rich":["rich-text"],"number.integer":["number","rating"],"number.decimal":["number","money","percent"],boolean:["switch"],date:["date"],time:["time"],datetime:["datetime"],"date-range":["date-range"],"datetime-range":["datetime-range"],"option.single":["select","radio"],"option.multiple":["multi-select","checkbox"],"cascade.single":["cascade"],"cascade.multiple":["cascade"],"user.single":["directory-user"],"user.multiple":["directory-user"],"department.single":["directory-department","scope"],"department.multiple":["directory-department","scope"],"resource-ref.single":["select","radio","resource"],"resource-ref.multiple":["multi-select","checkbox","resource"],file:["attachment"],image:["image"],signature:["signature"],address:["address"],location:["location"],uuid:["readonly"],json:["json"],"serial-number":["readonly"],subtable:["subtable"]};function ft(e,t,o){if(e===void 0)return;let n=Q(e,o);ce(n,pe.surface,o);let s=n.mutationOwner===void 0?"native":le(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow"].includes(s)||P("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let r=n.generated===void 0?{}:Q(n.generated,`${o}/generated`);ce(r,pe.generated,`${o}/generated`);for(let l of pe.generated)ut(r[l],`${o}/generated/${l}`);if(s!=="native")for(let l of["create","update","delete"])r[l]===!0&&P("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${l}`);let a=new Map(t.map(l=>[l.code,l])),i=Q(n.fields,`${o}/fields`);for(let l of Object.keys(i))a.has(l)||P("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${l}`);for(let l of t)Object.prototype.hasOwnProperty.call(i,l.code)||P("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${l.code}`),po(i[l.code],l,`${o}/fields/${l.code}`);for(let l of["create","update"]){let p=r[l]??s==="native",_=t.some(d=>{let c=Q(i[d.code],`${o}/fields/${d.code}`);return Ht(d,c,l)});p&&!_&&P("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${l}`)}if(_o(n.list,a,`${o}/list`),Yt(n.form,a,`${o}/form`),Yt(n.detail,a,`${o}/detail`),n.mobile!==void 0){let l=Q(n.mobile,`${o}/mobile`);ce(l,pe.mobile,`${o}/mobile`),ut(l.enabled,`${o}/mobile/enabled`)}fo(n,t,o)}function pt(e,t){let o=e.views?.find(s=>s.code===t);o||P("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(s=>s.fields.map(r=>[r,s.title])));return{mutationOwner:e.mutationOwner||"native",generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([s,r])=>{let a={...r};delete a.section;let i=n.get(s);return[s,{...a,...i?{section:i}:{},list:o.list.fieldOrder.includes(s)}]}))}}function fo(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&P("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((s,r)=>{let a=`${o}/views/${r}`,i=Q(s,a);ce(i,["code","name","generated","list","form","detail","mobile","sections"],a);let l=le(i.code,`${a}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(l)||n.has(l))&&P("NATIVE_DATA_VIEW_CODE_INVALID",`${a}/code`),n.add(l),le(i.name,`${a}/name`,255),Q(i.generated,`${a}/generated`),Q(i.mobile,`${a}/mobile`);for(let _ of["list","detail","create","update","delete"])typeof i.generated[_]!="boolean"&&P("NATIVE_DATA_VIEW_OPERATION_INVALID",`${a}/generated/${_}`);typeof i.mobile.enabled!="boolean"&&P("NATIVE_DATA_VIEW_MOBILE_INVALID",`${a}/mobile/enabled`);for(let _ of["list","form","detail"]){let d=Q(i[_],`${a}/${_}`),c=$e(d.fieldOrder,`${a}/${_}/fieldOrder`,500,!0);for(let A of c){let f=e.fields[A];(!f||(f.hidden??f.system)===!0)&&P("NATIVE_DATA_VIEW_FIELD_INVALID",`${a}/${_}/fieldOrder`)}}if(i.sections!==void 0){(!Array.isArray(i.sections)||i.sections.length>100)&&P("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${a}/sections`);let _=new Set;i.sections.forEach((d,c)=>{let A=`${a}/sections/${c}`,f=Q(d,A);ce(f,["title","fields"],A),le(f.title,`${A}/title`,255);for(let E of $e(f.fields,`${A}/fields`,100,!0)){let N=e.fields[E];(!N||(N.hidden??N.system)===!0||_.has(E))&&P("NATIVE_DATA_VIEW_FIELD_INVALID",`${A}/fields`),_.add(E)}})}let p=pt(e,l);if(ft(p,t,a),i.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let _ of t)We(_,e.fields[_.code])&&Ht(_,e.fields[_.code],"create")&&!i.form.fieldOrder.includes(_.code)&&P("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${a}/form/fieldOrder`)})}function Ht(e,t,o){if(e.type==="serial-number"||t.system===!0)return!1;let n=t[`${o}Capabilities`];return Array.isArray(n)&&n.length>0}function po(e,t,o){let n=Q(e,o);ce(n,pe.field,o),le(n.label,`${o}/label`,500),n.type!==t.type&&P("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let s=le(n.widget,`${o}/widget`,64);uo[t.type].includes(s)||P("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),Io(n.section,`${o}/section`,255);for(let r of["requiredHint","system","hidden","list","searchable","sortable"])ut(n[r],`${o}/${r}`);n.searchable===!0&&!ct(t.type)&&P("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!dt(t.type)&&P("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let r of["readCapabilities","createCapabilities","updateCapabilities"])$e(n[r],`${o}/${r}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&P("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&P("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let r=Array.isArray(n.accept)?n.accept:[n.accept];$e(r,`${o}/accept`,50,!1)}for(let r of["maxLength","precision","scale","min","max","rangeBoundary","options","source","timePrecision","serial","subtable"])Eo(n,t,r,o);Ao(n,t,o)}function _o(e,t,o){if(e===void 0)return;let n=Q(e,o);if(ce(n,pe.list,o),n.actions!==void 0){let s=Q(n.actions,`${o}/actions`);ce(s,["import","export"],`${o}/actions`);for(let r of["import","export"])s[r]!==void 0&&typeof s[r]!="boolean"&&P("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${r}`)}if(n.fieldOrder!==void 0)for(let s of $e(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(s)||P("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&P("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[s,r]of[["searchableFields",ct],["filterFields",Gt]]){if(n[s]===void 0)continue;let a=$e(n[s],`${o}/${s}`,100,!0);for(let i of a){let l=t.get(i);(!l||!r(l.type))&&P("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${s}`)}}if(n.defaultSort!==void 0){let s=Q(n.defaultSort,`${o}/defaultSort`);ce(s,pe.defaultSort,`${o}/defaultSort`);let r=le(s.field,`${o}/defaultSort/field`,63),a=t.get(r);!jt(r)&&(!a||!dt(a.type))&&P("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),s.order!==void 0&&!["asc","desc"].includes(s.order)&&P("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function Yt(e,t,o){if(e===void 0)return;let n=Q(e,o);if(ce(n,pe.layout,o),n.layout!==void 0&&!["flat","sections"].includes(n.layout)&&P("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),n.fieldOrder!==void 0){let s=`${o}/fieldOrder`;(!Array.isArray(n.fieldOrder)||n.fieldOrder.length>t.size||n.fieldOrder.length>lo)&&P("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",s);let r=n.fieldOrder.map((a,i)=>le(a,`${s}/${i}`,63));new Set(r).size!==r.length&&P("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",s),r.forEach((a,i)=>{t.has(a)||P("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${s}/${i}`)})}}function Eo(e,t,o,n){e[o]===void 0&&t[o]===void 0||((e[o]===void 0||t[o]===void 0)&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`),H(e[o])!==H(t[o])&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function Ao(e,t,o){let n=t.file||{},s={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:lt(e.accept)}};for(let r of["maxCount","maxSizeMb","accept"]){if(s[r]===void 0&&n[r]===void 0)continue;(s[r]===void 0||n[r]===void 0)&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`);let a=r==="accept"?lt(s[r]):s[r],i=r==="accept"?lt(n[r]):n[r];H(a)!==H(i)&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`)}}function lt(e){return(Array.isArray(e)?[...e]:[e]).sort((t,o)=>{let n=String(t),s=String(o);return n===s?0:n<s?-1:1})}function $e(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&P("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let s=e.map((r,a)=>le(r,`${t}/${a}`,255));return new Set(s).size!==s.length&&P("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),s}function Q(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&P("NATIVE_OBJECT_REQUIRED",t),e}function ce(e,t,o){let n=new Set(t);for(let s of Object.keys(e))n.has(s)||P("NATIVE_PROPERTY_UNKNOWN",`${o}/${s}`)}function le(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&P("NATIVE_STRING_INVALID",t),e}function Io(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&P("NATIVE_STRING_INVALID",t)}function ut(e,t){e!==void 0&&typeof e!="boolean"&&P("NATIVE_BOOLEAN_REQUIRED",t)}function P(e,t){throw new ue(e,t)}import{createHash as mo}from"crypto";var _t=new Set(["option.single","user.single","department.single","resource-ref.single"]),No=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),qt=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),go=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),To=new Set([..._t,...qt,"signature","address","location","json"]);function Ti(e,t){let o=new Set([...Array.isArray(t?.list?.searchableFields)?t.list.searchableFields:[],...Object.entries(t?.fields||{}).filter(([,n])=>n?.searchable===!0).map(([n])=>n)]);return e.map(n=>Co(n,o.has(n.code))).sort((n,s)=>n.code.localeCompare(s.code))}function Co(e,t=!1){let o=e.type==="date-range"||e.type==="datetime-range";if(o&&e.rangeBoundary!=="closed"&&e.rangeBoundary!=="half-open")throw new Error("OPENXIANGDA_NATIVE_DATA_RANGE_BOUNDARY_INVALID");return{code:e.code,type:e.type,nullable:!0,indexed:e.indexed===!0,storage:$o(e),index:Oo(e,t),...o?{rangeBoundary:e.rangeBoundary}:{},...e.type==="serial-number"?{serial:{prefix:e.serial?.prefix||"",digits:e.serial?.digits??6,start:e.serial?.start??1}}:{},...e.type==="subtable"&&e.subtable?{subtable:{resourceCode:e.subtable.resourceCode,foreignKey:e.subtable.foreignKey,orderField:e.subtable.orderField,maxRows:e.subtable.maxRows??20}}:{}}}function Ci(e,t){if(t.type==="subtable")return null;let o=te(t.code),n=Xt(e,t),s=[n?` DEFAULT ${n}`:"",ho(o,t),bo(o,t)].join("");return`${o} ${t.storage}${s}`}function bi(e,t){return Xt(e,t)}function bo(e,t){if(t.type!=="date-range"&&t.type!=="datetime-range")return"";if(t.rangeBoundary!=="closed"&&t.rangeBoundary!=="half-open")throw new Error("OPENXIANGDA_NATIVE_DATA_RANGE_BOUNDARY_INVALID");let o=t.type==="datetime-range"&&t.rangeBoundary==="closed";return` CHECK (${e} IS NULL OR (NOT isempty(${e}) AND lower(${e}) IS NOT NULL AND upper(${e}) IS NOT NULL AND lower_inc(${e}) AND ${o?"":"NOT "}upper_inc(${e})))`}function Oi(e){return e.type==="serial-number"||je(e.type)&&e.type!=="subtable"}function $i(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=Ge(e,o.code),s=o.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${n} AS bigint MINVALUE ${s} START WITH ${s} CACHE 1`})}function hi(e,t){let o=Je(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${Ge(e,n.code)} OWNED BY ${o}.${te(n.code)}`)}function Ri(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${Ge(e,o.code)} TO "openxiangda_data_api"`)}function Di(e,t){let o=Je(e),n=[];for(let s of t){if(s.type==="subtable")continue;let r=te(s.code),a=te(_e("idx",e,s.code,s.index));switch(s.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} (${r})`);break;case"btree-snapshot-expressions":{let i=te(_e("idx",e,s.code,"snapshot-value")),l=te(_e("idx",e,s.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${i} ON ${o} ((${r} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${l} ON ${o} ((${r} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIN (${r} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIST (${r})`);break;case"gin-trigram":{let i=_t.has(s.type)?`((${r} ->> 'label')) gin_trgm_ops`:`${r} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIN (${i})`);break}case"none":break}if(s.type==="serial-number"){let i=te(_e("uidx",e,s.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${i} ON ${o} (${r})`)}}return n}function Si(e,t,o,n){let s=Je(e),r=Je(t),a=te(_e("uidx",e,"environment_id","subtable-parent")),i=te(_e("idx",t,o,n,"subtable-child")),l=te(_e("fk",t,o,e)),p=te(o),_=te(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${a} ON ${s} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${i} ON ${r} ("tenant_id", "app_code", "environment_key", ${p}, ${_}, "id")`,`DO $native_subtable$ BEGIN
1
+ import{createHash as jn}from"node:crypto";function Wn(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function et(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`JSON number must be finite: ${t}`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map((n,i)=>et(n,`${t}[${i}]`)).join(",")}]`;if(Wn(e))return`{${Object.keys(e).filter(i=>e[i]!==void 0).sort((i,r)=>i===r?0:i<r?-1:1).map(i=>`${JSON.stringify(i)}:${et(e[i],`${t}.${i}`)}`).join(",")}}`;let o=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${o})`)}function H(e){return et(e,"$")}function X(e){return jn("sha256").update(H(e)).digest("hex")}var vt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,nt=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Bn=["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","date-range","datetime-range","option.single","option.multiple","cascade.single","cascade.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple","image","signature","address","location","uuid","json","file","serial-number","subtable"],Jn=new Set(Bn),Lt=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),Vt=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),wt=new Set(["resource-ref.single","resource-ref.multiple"]),ot=[{code:"id",type:"uuid",nullable:!1},{code:"revision",type:"number.integer",nullable:!1},{code:"created_by",type:"text.short",nullable:!1},{code:"updated_by",type:"text.short",nullable:!1},{code:"created_at",type:"datetime",nullable:!1},{code:"updated_at",type:"datetime",nullable:!1}],ns=new Map(ot.map(e=>[e.code,e])),ue=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function je(e){return Lt.has(e)}function We(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!je(e.type)||t.requiredHint===!0)}function it(e,t,o=500){Array.isArray(e)||R("NATIVE_ARRAY_REQUIRED",t),e.length===0&&R("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&R("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((i,r)=>{let a=`${t}/${r}`,s=oe(i,a);re(s,["code","type","nullable","indexed","options","source","maxLength","precision","scale","min","max","rangeBoundary","timePrecision","file","serial","subtable"],a);let l=ae(s.code,`${a}/code`,63);vt.test(l)||R("NATIVE_FIELD_CODE_INVALID",`${a}/code`),n.has(l)&&R("NATIVE_DATA_FIELD_DUPLICATE",`${a}/code`),n.add(l);let p=ae(s.type,`${a}/type`,32);Jn.has(p)||R("NATIVE_DATA_FIELD_TYPE_INVALID",`${a}/type`);let _=p,d=Pt(s.nullable,`${a}/nullable`),c=Pt(s.indexed,`${a}/indexed`);d===!0&&Lt.has(_)&&R("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${a}/nullable`);let A=Yn(s.options,_,a),f=Hn(s.source,_,a),E=qn(s,_,a),N=Gn(s.rangeBoundary,_,a),m=Xn(s.file,_,a),g=Qn(s.serial,_,a),T=Zn(s.subtable,_,a);return{code:l,type:_,...d===void 0?{}:{nullable:d},...c===void 0?{}:{indexed:c},...A?{options:A}:{},...f?{source:f}:{},...E,...N?{rangeBoundary:N}:{},...m?{file:m}:{},...g?{serial:g}:{},...T?{subtable:T}:{}}})}function Gn(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&R("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&R("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function kt(e,t){Array.isArray(e)||R("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,i)=>{let r=`${t}/${i}`,a=oe(n,r),s=ae(a.code,`${r}/code`,64);(!nt.test(s)||o.has(s))&&R("NATIVE_RESOURCE_CODE_INVALID",`${r}/code`);let l=oe(a.schema,`${r}/schema`);o.set(s,{pointer:r,fields:it(l.fields,`${r}/schema/fields`)})});for(let[n,i]of o){let r=new Map(i.fields.map(s=>[s.code,s]));i.fields.filter(s=>s.type==="subtable").reduce((s,l)=>s+(l.subtable?.maxRows??20),0)>49&&R("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${i.pointer}/schema/fields`),i.fields.forEach((s,l)=>{let p=`${i.pointer}/schema/fields/${l}`;if(s.source&&zn(s.source,r,o,`${p}/source`),s.subtable){let _=o.get(s.subtable.resourceCode);(!_||s.subtable.resourceCode===n)&&R("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${p}/subtable/resourceCode`);let d=_.fields.find(A=>A.code===s.subtable?.foreignKey);(!d||d.type!=="uuid"||d.nullable!==!1)&&R("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${p}/subtable/foreignKey`);let c=_.fields.find(A=>A.code===s.subtable?.orderField);(!c||c.type!=="number.integer"||c.nullable!==!1)&&R("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${p}/subtable/orderField`)}})}}function xt(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&R("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(r=>[r.code,r])),i=new Set;return e.map((r,a)=>{let s=`${o}/${a}`,l=oe(r,s);re(l,["code","message","expression"],s);let p=ae(l.code,`${s}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(p)||i.has(p))&&R("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${s}/code`),i.add(p);let _=Me(l.message,`${s}/message`,500);_!==void 0&&_.length===0&&R("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${s}/message`);let d=oe(l.expression,`${s}/expression`);re(d,["leftField","operator","rightField"],`${s}/expression`);let c=fe(d.leftField,`${s}/expression/leftField`),A=fe(d.rightField,`${s}/expression/rightField`),f=n.get(c),E=n.get(A);(!f||!E)&&R("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),f.type===E.type||["number.integer","number.decimal"].includes(f.type)&&["number.integer","number.decimal"].includes(E.type)||R("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`);let m=String(d.operator);return["eq","neq","gt","gte","lt","lte"].includes(m)||R("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${s}/expression/operator`),!["eq","neq"].includes(m)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(f.type)&&R("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:p,..._===void 0?{}:{message:_},expression:{leftField:c,operator:m,rightField:A}}})}function zn(e,t,o,n){let i=o.get(e.resourceCode);i||R("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let r=new Map(i.fields.map(s=>[s.code,s])),a=r.get(e.labelField);(!a||!["text.short","text.long"].includes(a.type))&&R("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let s of["searchFields","descriptionFields","snapshotFields"])for(let l of e[s]||[])r.has(l)||R("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${s}`);for(let[s,l]of(e.filters||[]).entries())r.has(l.field)||R("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${s}/field`),"binding"in l&&!t.has(l.binding.field)&&R("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${s}/binding/field`)}function Yn(e,t,o){let n=`${o}/options`;if(e===void 0){Vt.has(t)&&R("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!Vt.has(t)||!Array.isArray(e))&&R("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&R("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let i=0,r=(a,s,l)=>{l>5&&R("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",s);let p=new Set;return a.map((_,d)=>{i+=1,i>1e3&&R("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let c=`${s}/${d}`,A=oe(_,c);re(A,["label","value","description","color","children"],c);let f=ae(A.label,`${c}/label`,500),E=ae(A.value,`${c}/value`,500);p.has(E)&&R("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${c}/value`),p.add(E);let N=Me(A.description,`${c}/description`,2e3),m=Me(A.color,`${c}/color`,64),g;return A.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(A.children))&&R("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${c}/children`),(A.children.length<1||A.children.length>100)&&R("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${c}/children`),g=r(A.children,`${c}/children`,l+1)),{label:f,value:E,...N===void 0?{}:{description:N},...m===void 0?{}:{color:m},...g?{children:g}:{}}})};return r(e,n,1)}function Hn(e,t,o){let n=`${o}/source`;if(e===void 0){wt.has(t)&&R("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}wt.has(t)||R("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let i=oe(e,n);re(i,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode"],n),i.kind!=="resource"&&R("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let r=ae(i.resourceCode,`${n}/resourceCode`,64);nt.test(r)||R("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=fe(i.labelField,`${n}/labelField`),s=tt(i.searchFields,`${n}/searchFields`,10),l=tt(i.descriptionFields,`${n}/descriptionFields`,10),p=tt(i.snapshotFields,`${n}/snapshotFields`,50),_=be(i.pageSize,`${n}/pageSize`,1,100),d;i.loadMode!==void 0&&(["search","all"].includes(String(i.loadMode))||R("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),d=i.loadMode);let c=Kn(i.filters,`${n}/filters`);return{kind:"resource",resourceCode:r,labelField:a,...s?{searchFields:s}:{},...l?{descriptionFields:l}:{},...p?{snapshotFields:p}:{},...c?{filters:c}:{},..._===void 0?{}:{pageSize:_},...d?{loadMode:d}:{}}}function Kn(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&R("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,n)=>{let i=`${t}/${n}`,r=oe(o,i),a=Object.prototype.hasOwnProperty.call(r,"value"),s=Object.prototype.hasOwnProperty.call(r,"binding");re(r,a?["field","operator","value"]:["field","operator","binding"],i),a===s&&R("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",i);let l=fe(r.field,`${i}/field`);["eq","in"].includes(String(r.operator))||R("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${i}/operator`);let p=r.operator;if(a)return{field:l,operator:p,value:r.value};let _=oe(r.binding,`${i}/binding`);return re(_,["kind","field"],`${i}/binding`),_.kind!=="field"&&R("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${i}/binding/kind`),{field:l,operator:p,binding:{kind:"field",field:fe(_.field,`${i}/binding/field`)}}})}function qn(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||R("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=Ue(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&R("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=Ue(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:Ue(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||R("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let i=Ft(e.min,`${o}/min`),r=Ft(e.max,`${o}/max`);t==="number.integer"&&[i,r].some(a=>a!==void 0&&!Number.isSafeInteger(a))&&R("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&r!==void 0&&i>r&&R("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&(n.min=i),r!==void 0&&(n.max=r)}return e.timePrecision!==void 0&&((t!=="time"||!["minute","second"].includes(e.timePrecision))&&R("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function Xn(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||R("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let i=oe(e,n);re(i,["maxCount","maxSizeMb","accept"],n);let r=be(i.maxCount,`${n}/maxCount`,1,100);t==="signature"&&r!==void 0&&r!==1&&R("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let a=be(i.maxSizeMb,`${n}/maxSizeMb`,1,1024),s;return i.accept!==void 0&&((!Array.isArray(i.accept)||i.accept.length>50)&&R("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),s=i.accept.map((l,p)=>ae(l,`${n}/accept/${p}`,255)),new Set(s).size!==s.length&&R("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...r===void 0?{}:{maxCount:r},...a===void 0?{}:{maxSizeMb:a},...s===void 0?{}:{accept:s}}}function Qn(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&R("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&R("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let i=oe(e,n);re(i,["prefix","digits","start"],n);let r=Me(i.prefix,`${n}/prefix`,64),a=be(i.digits,`${n}/digits`,1,32),s=be(i.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...r===void 0?{}:{prefix:r},...a===void 0?{}:{digits:a},...s===void 0?{}:{start:s}}}function Zn(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&R("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&R("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let i=oe(e,n);re(i,["resourceCode","foreignKey","orderField","maxRows"],n);let r=ae(i.resourceCode,`${n}/resourceCode`,64);nt.test(r)||R("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=fe(i.foreignKey,`${n}/foreignKey`),s=fe(i.orderField,`${n}/orderField`);s===a&&R("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let l=be(i.maxRows,`${n}/maxRows`,1,49);return{resourceCode:r,foreignKey:a,orderField:s,...l===void 0?{}:{maxRows:l}}}function tt(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&R("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((i,r)=>fe(i,`${t}/${r}`));return new Set(n).size!==n.length&&R("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function fe(e,t){let o=ae(e,t,63);return vt.test(o)||R("NATIVE_FIELD_CODE_INVALID",t),o}function oe(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&R("NATIVE_OBJECT_REQUIRED",t),e}function re(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||R("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function ae(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&R("NATIVE_STRING_INVALID",t),e}function Me(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&R("NATIVE_STRING_INVALID",t),e}function Pt(e,t){if(e!==void 0)return typeof e!="boolean"&&R("NATIVE_BOOLEAN_REQUIRED",t),e}function be(e,t,o,n){if(e!==void 0)return Ue(e,t,o,n)}function Ft(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&R("NATIVE_NUMBER_REQUIRED",t),e}function Ue(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&R("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function R(e,t){throw new ue(e,t)}var Ut=["created_by","updated_by","created_at","updated_at"];function Se(e){return Ut.includes(e)}function Mt(e){return Ut.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var eo=ot.map(e=>e.code);function jt(e){return eo.includes(e)}var to=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],no=new Set(to);function rs(e){return no.has(String(e))}var st=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],ye=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],oo=["eq","neq","in","isEmpty"],Be=["eq","neq","in","isEmpty","isNotEmpty"],Oe=["has","hasAny","hasAll","isEmpty","isNotEmpty"],Wt=["overlaps","contains","containedBy","isEmpty"],rt=["jsonContains","isEmpty","isNotEmpty"],at=["isEmpty","isNotEmpty"],io={"text.short":st,"text.long":st,"text.rich":st,"number.integer":ye,"number.decimal":ye,boolean:oo,date:ye,time:ye,datetime:ye,"date-range":Wt,"datetime-range":Wt,"option.single":Be,"option.multiple":Oe,"cascade.single":Oe,"cascade.multiple":Oe,"user.single":Be,"user.multiple":Oe,"department.single":Be,"department.multiple":Oe,"resource-ref.single":Be,"resource-ref.multiple":Oe,file:at,image:at,signature:at,address:rt,location:rt,uuid:["eq","neq","in","isEmpty"],json:rt,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},so=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),ro=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function Jt(e){return io[e]}function as(e,t){return Jt(e).includes(t)}function ct(e){return so.has(e)}function dt(e){return!ro.has(e)}function Gt(e){return Jt(e).length>0}var Bt=new Set(["number.integer","number.decimal"]),zt=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),ao=new Set([...zt,"boolean","uuid"]),co=new Set(["option.single","user.single","department.single","resource-ref.single"]);function cs(e,t){return t==="sum"||t==="avg"?Bt.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?zt.has(e)?{valueExpression:"column",numericResult:Bt.has(e)}:null:co.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:ao.has(e)?{valueExpression:"column",numericResult:!0}:null}var lo=500,pe={surface:["mutationOwner","generated","fields","list","form","detail","mobile","views"],generated:["list","detail","create","update","delete"],field:["label","type","widget","section","requiredHint","system","hidden","readCapabilities","createCapabilities","updateCapabilities","maxLength","precision","scale","min","max","rangeBoundary","maxCount","maxSizeMb","accept","options","list","searchable","sortable","source","timePrecision","serial","subtable"],list:["actions","fieldOrder","defaultPageSize","searchableFields","filterFields","defaultSort"],defaultSort:["field","order"],layout:["layout","fieldOrder"],mobile:["enabled"]},uo={"text.short":["text","email","phone"],"text.long":["textarea"],"text.rich":["rich-text"],"number.integer":["number","rating"],"number.decimal":["number","money","percent"],boolean:["switch"],date:["date"],time:["time"],datetime:["datetime"],"date-range":["date-range"],"datetime-range":["datetime-range"],"option.single":["select","radio"],"option.multiple":["multi-select","checkbox"],"cascade.single":["cascade"],"cascade.multiple":["cascade"],"user.single":["directory-user"],"user.multiple":["directory-user"],"department.single":["directory-department","scope"],"department.multiple":["directory-department","scope"],"resource-ref.single":["select","radio","resource"],"resource-ref.multiple":["multi-select","checkbox","resource"],file:["attachment"],image:["image"],signature:["signature"],address:["address"],location:["location"],uuid:["readonly"],json:["json"],"serial-number":["readonly"],subtable:["subtable"]};function ft(e,t,o){if(e===void 0)return;let n=Q(e,o);ce(n,pe.surface,o);let i=n.mutationOwner===void 0?"native":le(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow"].includes(i)||P("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let r=n.generated===void 0?{}:Q(n.generated,`${o}/generated`);ce(r,pe.generated,`${o}/generated`);for(let l of pe.generated)ut(r[l],`${o}/generated/${l}`);if(i!=="native")for(let l of["create","update","delete"])r[l]===!0&&P("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${l}`);let a=new Map(t.map(l=>[l.code,l])),s=Q(n.fields,`${o}/fields`);for(let l of Object.keys(s))a.has(l)||P("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${l}`);for(let l of t)Object.prototype.hasOwnProperty.call(s,l.code)||P("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${l.code}`),po(s[l.code],l,`${o}/fields/${l.code}`);for(let l of["create","update"]){let p=r[l]??i==="native",_=t.some(d=>{let c=Q(s[d.code],`${o}/fields/${d.code}`);return Ht(d,c,l)});p&&!_&&P("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${l}`)}if(_o(n.list,a,`${o}/list`),Yt(n.form,a,`${o}/form`),Yt(n.detail,a,`${o}/detail`),n.mobile!==void 0){let l=Q(n.mobile,`${o}/mobile`);ce(l,pe.mobile,`${o}/mobile`),ut(l.enabled,`${o}/mobile/enabled`)}fo(n,t,o)}function pt(e,t){let o=e.views?.find(i=>i.code===t);o||P("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(i=>i.fields.map(r=>[r,i.title])));return{mutationOwner:e.mutationOwner||"native",generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([i,r])=>{let a={...r};delete a.section;let s=n.get(i);return[i,{...a,...s?{section:s}:{},list:o.list.fieldOrder.includes(i)}]}))}}function fo(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&P("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((i,r)=>{let a=`${o}/views/${r}`,s=Q(i,a);ce(s,["code","name","generated","list","form","detail","mobile","sections"],a);let l=le(s.code,`${a}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(l)||n.has(l))&&P("NATIVE_DATA_VIEW_CODE_INVALID",`${a}/code`),n.add(l),le(s.name,`${a}/name`,255),Q(s.generated,`${a}/generated`),Q(s.mobile,`${a}/mobile`);for(let _ of["list","detail","create","update","delete"])typeof s.generated[_]!="boolean"&&P("NATIVE_DATA_VIEW_OPERATION_INVALID",`${a}/generated/${_}`);typeof s.mobile.enabled!="boolean"&&P("NATIVE_DATA_VIEW_MOBILE_INVALID",`${a}/mobile/enabled`);for(let _ of["list","form","detail"]){let d=Q(s[_],`${a}/${_}`),c=$e(d.fieldOrder,`${a}/${_}/fieldOrder`,500,!0);for(let A of c){let f=e.fields[A];(!f||(f.hidden??f.system)===!0)&&P("NATIVE_DATA_VIEW_FIELD_INVALID",`${a}/${_}/fieldOrder`)}}if(s.sections!==void 0){(!Array.isArray(s.sections)||s.sections.length>100)&&P("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${a}/sections`);let _=new Set;s.sections.forEach((d,c)=>{let A=`${a}/sections/${c}`,f=Q(d,A);ce(f,["title","fields"],A),le(f.title,`${A}/title`,255);for(let E of $e(f.fields,`${A}/fields`,100,!0)){let N=e.fields[E];(!N||(N.hidden??N.system)===!0||_.has(E))&&P("NATIVE_DATA_VIEW_FIELD_INVALID",`${A}/fields`),_.add(E)}})}let p=pt(e,l);if(ft(p,t,a),s.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let _ of t)We(_,e.fields[_.code])&&Ht(_,e.fields[_.code],"create")&&!s.form.fieldOrder.includes(_.code)&&P("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${a}/form/fieldOrder`)})}function Ht(e,t,o){if(e.type==="serial-number"||t.system===!0)return!1;let n=t[`${o}Capabilities`];return Array.isArray(n)&&n.length>0}function po(e,t,o){let n=Q(e,o);ce(n,pe.field,o),le(n.label,`${o}/label`,500),n.type!==t.type&&P("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let i=le(n.widget,`${o}/widget`,64);uo[t.type].includes(i)||P("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),Io(n.section,`${o}/section`,255);for(let r of["requiredHint","system","hidden","list","searchable","sortable"])ut(n[r],`${o}/${r}`);n.searchable===!0&&!ct(t.type)&&P("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!dt(t.type)&&P("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let r of["readCapabilities","createCapabilities","updateCapabilities"])$e(n[r],`${o}/${r}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&P("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&P("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let r=Array.isArray(n.accept)?n.accept:[n.accept];$e(r,`${o}/accept`,50,!1)}for(let r of["maxLength","precision","scale","min","max","rangeBoundary","options","source","timePrecision","serial","subtable"])Eo(n,t,r,o);Ao(n,t,o)}function _o(e,t,o){if(e===void 0)return;let n=Q(e,o);if(ce(n,pe.list,o),n.actions!==void 0){let i=Q(n.actions,`${o}/actions`);ce(i,["import","export"],`${o}/actions`);for(let r of["import","export"])i[r]!==void 0&&typeof i[r]!="boolean"&&P("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${r}`)}if(n.fieldOrder!==void 0)for(let i of $e(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(i)||P("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&P("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[i,r]of[["searchableFields",ct],["filterFields",Gt]]){if(n[i]===void 0)continue;let a=$e(n[i],`${o}/${i}`,100,!0);for(let s of a){let l=t.get(s);(!l||!r(l.type))&&P("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${i}`)}}if(n.defaultSort!==void 0){let i=Q(n.defaultSort,`${o}/defaultSort`);ce(i,pe.defaultSort,`${o}/defaultSort`);let r=le(i.field,`${o}/defaultSort/field`,63),a=t.get(r);!jt(r)&&(!a||!dt(a.type))&&P("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),i.order!==void 0&&!["asc","desc"].includes(i.order)&&P("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function Yt(e,t,o){if(e===void 0)return;let n=Q(e,o);if(ce(n,pe.layout,o),n.layout!==void 0&&!["flat","sections"].includes(n.layout)&&P("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),n.fieldOrder!==void 0){let i=`${o}/fieldOrder`;(!Array.isArray(n.fieldOrder)||n.fieldOrder.length>t.size||n.fieldOrder.length>lo)&&P("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i);let r=n.fieldOrder.map((a,s)=>le(a,`${i}/${s}`,63));new Set(r).size!==r.length&&P("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i),r.forEach((a,s)=>{t.has(a)||P("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${i}/${s}`)})}}function Eo(e,t,o,n){e[o]===void 0&&t[o]===void 0||((e[o]===void 0||t[o]===void 0)&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`),H(e[o])!==H(t[o])&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function Ao(e,t,o){let n=t.file||{},i={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:lt(e.accept)}};for(let r of["maxCount","maxSizeMb","accept"]){if(i[r]===void 0&&n[r]===void 0)continue;(i[r]===void 0||n[r]===void 0)&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`);let a=r==="accept"?lt(i[r]):i[r],s=r==="accept"?lt(n[r]):n[r];H(a)!==H(s)&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`)}}function lt(e){return(Array.isArray(e)?[...e]:[e]).sort((t,o)=>{let n=String(t),i=String(o);return n===i?0:n<i?-1:1})}function $e(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&P("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((r,a)=>le(r,`${t}/${a}`,255));return new Set(i).size!==i.length&&P("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function Q(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&P("NATIVE_OBJECT_REQUIRED",t),e}function ce(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||P("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function le(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&P("NATIVE_STRING_INVALID",t),e}function Io(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&P("NATIVE_STRING_INVALID",t)}function ut(e,t){e!==void 0&&typeof e!="boolean"&&P("NATIVE_BOOLEAN_REQUIRED",t)}function P(e,t){throw new ue(e,t)}import{createHash as mo}from"crypto";var _t=new Set(["option.single","user.single","department.single","resource-ref.single"]),No=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),qt=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),go=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),To=new Set([..._t,...qt,"signature","address","location","json"]);function Ts(e,t){let o=new Set([...Array.isArray(t?.list?.searchableFields)?t.list.searchableFields:[],...Object.entries(t?.fields||{}).filter(([,n])=>n?.searchable===!0).map(([n])=>n)]);return e.map(n=>Co(n,o.has(n.code))).sort((n,i)=>n.code.localeCompare(i.code))}function Co(e,t=!1){let o=e.type==="date-range"||e.type==="datetime-range";if(o&&e.rangeBoundary!=="closed"&&e.rangeBoundary!=="half-open")throw new Error("OPENXIANGDA_NATIVE_DATA_RANGE_BOUNDARY_INVALID");return{code:e.code,type:e.type,nullable:!0,indexed:e.indexed===!0,storage:$o(e),index:Oo(e,t),...o?{rangeBoundary:e.rangeBoundary}:{},...e.type==="serial-number"?{serial:{prefix:e.serial?.prefix||"",digits:e.serial?.digits??6,start:e.serial?.start??1}}:{},...e.type==="subtable"&&e.subtable?{subtable:{resourceCode:e.subtable.resourceCode,foreignKey:e.subtable.foreignKey,orderField:e.subtable.orderField,maxRows:e.subtable.maxRows??20}}:{}}}function Cs(e,t){if(t.type==="subtable")return null;let o=te(t.code),n=Xt(e,t),i=[n?` DEFAULT ${n}`:"",ho(o,t),bo(o,t)].join("");return`${o} ${t.storage}${i}`}function bs(e,t){return Xt(e,t)}function bo(e,t){if(t.type!=="date-range"&&t.type!=="datetime-range")return"";if(t.rangeBoundary!=="closed"&&t.rangeBoundary!=="half-open")throw new Error("OPENXIANGDA_NATIVE_DATA_RANGE_BOUNDARY_INVALID");let o=t.type==="datetime-range"&&t.rangeBoundary==="closed";return` CHECK (${e} IS NULL OR (NOT isempty(${e}) AND lower(${e}) IS NOT NULL AND upper(${e}) IS NOT NULL AND lower_inc(${e}) AND ${o?"":"NOT "}upper_inc(${e})))`}function Os(e){return e.type==="serial-number"||je(e.type)&&e.type!=="subtable"}function $s(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=Ge(e,o.code),i=o.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${n} AS bigint MINVALUE ${i} START WITH ${i} CACHE 1`})}function hs(e,t){let o=Je(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${Ge(e,n.code)} OWNED BY ${o}.${te(n.code)}`)}function Rs(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${Ge(e,o.code)} TO "openxiangda_data_api"`)}function Ds(e,t){let o=Je(e),n=[];for(let i of t){if(i.type==="subtable")continue;let r=te(i.code),a=te(_e("idx",e,i.code,i.index));switch(i.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} (${r})`);break;case"btree-snapshot-expressions":{let s=te(_e("idx",e,i.code,"snapshot-value")),l=te(_e("idx",e,i.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${o} ((${r} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${l} ON ${o} ((${r} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIN (${r} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIST (${r})`);break;case"gin-trigram":{let s=_t.has(i.type)?`((${r} ->> 'label')) gin_trgm_ops`:`${r} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIN (${s})`);break}case"none":break}if(i.type==="serial-number"){let s=te(_e("uidx",e,i.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${s} ON ${o} (${r})`)}}return n}function Ss(e,t,o,n){let i=Je(e),r=Je(t),a=te(_e("uidx",e,"environment_id","subtable-parent")),s=te(_e("idx",t,o,n,"subtable-child")),l=te(_e("fk",t,o,e)),p=te(o),_=te(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${a} ON ${i} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${s} ON ${r} ("tenant_id", "app_code", "environment_key", ${p}, ${_}, "id")`,`DO $native_subtable$ BEGIN
2
2
  ALTER TABLE ${r}
3
3
  ADD CONSTRAINT ${l}
4
4
  FOREIGN KEY ("tenant_id", "app_code", "environment_key", ${p})
5
- REFERENCES ${s} ("tenant_id", "app_code", "environment_key", "id")
5
+ REFERENCES ${i} ("tenant_id", "app_code", "environment_key", "id")
6
6
  ON DELETE CASCADE;
7
7
  EXCEPTION WHEN duplicate_object THEN NULL;
8
- END $native_subtable$`]}function _e(e,...t){return`${e}_${mo("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function te(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function Oo(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":_t.has(e.type)?"btree-snapshot-expressions":No.has(e.type)?"gin-jsonb-path":"btree":"none"}function $o(e){switch(e.type){case"text.short":return`varchar(${e.maxLength??255})`;case"text.long":case"text.rich":return"text";case"number.integer":return"bigint";case"number.decimal":return`numeric(${e.precision??38},${e.scale??10})`;case"boolean":return"boolean";case"date":return"date";case"time":return"time(0)";case"datetime":return"timestamptz";case"date-range":return"daterange";case"datetime-range":return"tstzrange";case"uuid":return"uuid";case"serial-number":return"varchar(255)";case"subtable":return"child-resource";default:return To.has(e.type),"jsonb"}}function Xt(e,t){if(je(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=Kt(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${Kt(Ge(e,t.code))})::text, ${n}, '0'))`}function ho(e,t){return qt.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:go.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function Je(e){return`"app_data".${te(e)}`}function Ge(e,t){let o=_e("seq",e,t);return`"app_data".${te(o)}`}function Kt(e){return`'${e.replace(/'/g,"''")}'`}var Qt=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),Ro=new Set([...Qt,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),Zt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Do=new Set(["__proto__","prototype","constructor"]),Et=class extends Error{constructor(o){super("OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID");this.path=o;this.name="NativeScopeSourceFieldPathV2Error"}path;code="OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID"};function Ve(e,t){let o=tn(e);if(!o)return null;let n=t.get(o[0]);if(!n)return null;let s=o.slice(1).join(".")||void 0;return{field:n,...s?{valuePath:s}:{}}}function At(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function en(e,t,o){if(!e||!t||!So(e))return!1;let{field:n,valuePath:s}=e;if(!s)return t.valueType==="uuid"?n.type==="uuid":["text.short","text.long","serial-number"].includes(n.type);if(s==="value")return!(t.valueSourceResourceCode&&n.type.startsWith("resource-ref.")&&n.source?.resourceCode!==t.valueSourceResourceCode);let r=s.slice(9),i=o.get(n.source?.resourceCode||"")?.get(r)?.type;return t.valueType==="uuid"?i==="uuid":["text.short","text.long","serial-number"].includes(i||"")}function Vi(e,t){let o=tn(t);if(!o)throw new Et(String(t||""));let n=e;for(let s of o){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,s))return;n=n[s]}return n}function So(e){let{field:t,valuePath:o}=e;if(!o)return!Ro.has(t.type);if(o==="value")return Qt.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return Zt.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function tn(e){if(typeof e!="string"||e.length===0||e.length>192)return null;let t=e.split(".");return![1,2,3].includes(t.length)||t.some(o=>!Zt.test(o)||Do.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var yo=new Set(["option.single","user.single","department.single","resource-ref.single"]),Vo=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),wo=new Set(["value","label","description","color"]),Po=new Set(["avatarUrl","employeeNo","title","mobile","email"]),Fo=new Set(["fullPath","parent.value","parent.label"]),vo=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),Lo=new Set(["longitude","latitude","accuracy"]),ko=new Set(["address","name","province","city","district","source"]);function Pi(e){let t=new Map(e.map(o=>[o.code,new Map(o.schema.fields.map(n=>[n.code,n]))]));return e.map(o=>({...o,schema:{...o.schema,fields:o.schema.fields.map(n=>{let s=xo(n,t);if(!Object.keys(s).length)return n;let r={...n};return Object.defineProperty(r,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(s)}),r})}}))}function Fi(e,t){if(yo.has(e.type)&&wo.has(t)||e.type==="user.single"&&Po.has(t)||e.type==="department.single"&&Fo.has(t))return we(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&vo.has(t))return we(t);if(e.type==="location"){if(Lo.has(t))return{parts:[t],type:"number.decimal"};if(ko.has(t))return we(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function xo(e,t){if(e.type!=="resource-ref.single"||!e.source)return{};let o=t.get(e.source.resourceCode);return o?Object.fromEntries((e.source.snapshotFields||[]).flatMap(n=>{let s=o.get(n);return s?[[`snapshot.${n}`,Vo.has(s.type)?s.type:"json"]]:[]})):{}}function we(e){return{parts:e.split("."),type:"text.short"}}var It=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function nn(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(E,N)=>{throw new It(`${o}${E}`,N)},s=(E,N,m)=>((!E||typeof E!="object"||Array.isArray(E)||Object.keys(E).some(g=>!m.includes(g)))&&n(N,"Invalid action object or unsupported property"),E),r=s(e.execution,"/execution",["kind","version","operations"]);(r.kind!=="native-data"||r.version!==1)&&n("/execution","Expected native-data version 1"),e.platformAccess&&n("/platformAccess","Native actions do not use application runtime capabilities"),(!Array.isArray(e.eventTypes)||!e.eventTypes.length||e.eventTypes.some(E=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(E)))&&n("/eventTypes","Native data actions require declared data events");let a=e.filter?.resourceCodes;(!Array.isArray(a)||!a.length||a.length>20)&&n("/filter/resourceCodes","Native actions require explicit source resources");let i=new Map(t.map(E=>[E.code,E])),l=a.map(E=>{let N=i.get(E);return N||n("/filter/resourceCodes","Unknown source resource"),new Set((N.schema?.fields||[]).map(m=>m.code))}),p=new Set(e.payload?.fields||[]),_=e.payload?.includeChanges===!0,d=(E,N)=>{let m=s(E,N,["source","path","value"]);if(m.source==="literal"){(!Object.hasOwn(m,"value")||Object.hasOwn(m,"path"))&&n(N,"Literal binding requires only value");let b;try{b=JSON.stringify(m.value)}catch{n(N,"Literal must be JSON")}return(b===void 0||Buffer.byteLength(b)>65536)&&n(N,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(b)}}(m.source!=="event"||typeof m.path!="string"||Object.hasOwn(m,"value"))&&n(N,"Expected a literal or event binding");let g=m.path.split(".");(g.length>8||g.some(b=>!/^[A-Za-z0-9_-]+$/.test(b)||["__proto__","prototype","constructor"].includes(b)))&&n(N,"Invalid event path");let T=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(m.path),D=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(m.path);if(T||D){let b=(T||D)[1];l.some(O=>!O.has(b))&&n(N,"Source field must exist on every filtered resource"),p.add(b),D&&(_=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(m.path)||n(N,"Event path is not part of the data event contract");return{source:"event",path:m.path}};(!Array.isArray(r.operations)||r.operations.length<1||r.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let c={},A=r.operations.map((E,N)=>{let m=`/execution/operations/${N}`,g=s(E,m,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(g.operation)||n(m,"Unsupported Native operation");let T=i.get(g.resourceCode);T||n(m,"Unknown action target resource");let D=new Map((T.schema?.fields||[]).map(O=>[O.code,O])),b=g.data===void 0?{}:s(g.data,`${m}/data`,[...D.keys()]);return Object.keys(b).length>32&&n(m,"Maximum 32 mapped fields per operation"),g.operation==="create"&&(g.id!==void 0||g.expectedRevision!==void 0)&&n(m,"Create does not accept id or expectedRevision"),g.operation==="delete"&&g.data!==void 0&&n(m,"Delete does not accept data"),Object.keys(b).some(O=>D.get(O)?.type==="serial-number")&&n(m,"Generated fields cannot be assigned"),c[g.resourceCode]=X(T),{operation:g.operation,resourceCode:g.resourceCode,...g.operation==="create"?{}:{id:d(g.id,`${m}/id`),expectedRevision:d(g.expectedRevision,`${m}/expectedRevision`)},...g.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(b).map(([O,V])=>[O,d(V,`${m}/data/${O}`)]))}}});(p.size>32||[...p].some(E=>l.some(N=>!N.has(E))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let f={kind:"native-data",version:1,operations:A,resourceDigests:c};return Buffer.byteLength(JSON.stringify(f))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...f,digest:X(f)},payload:{includeChanges:_,fields:[...p].sort()}}}function Ee(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function sn(e,t){if(e?.instanceCommands===void 0)return[];let o=Ee(e.instanceCommands);if(!o||!Object.keys(o).length||Object.keys(o).some(s=>!["withdraw","terminate"].includes(s)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let n=[];for(let[s,r]of Object.entries(o)){let a=Ee(r),i=s==="withdraw"?["beforeFact"]:["beforeFact","capability"];if(!a||Object.keys(a).some(l=>!i.includes(l))){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${s}`);continue}if(s==="terminate"){let l=a.capability;(typeof l!="string"||l.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(l)||t&&(!l.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(l)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(s==="withdraw"||a.beforeFact!==void 0){let l=a.beforeFact,p=Ee(e.inputSchema),_=Ee(Ee(p?.properties)?.[l]),d=Ee(Ee(e.subject)?.factProjection)?.[l],c=t?.fields.get(d);(typeof l!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(l)||!Array.isArray(p?.required)||!p.required.includes(l)||_?.type!=="string"||_?.format!=="date-time"||typeof d!="string"||t&&(c?.type!=="datetime"||c.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${s}`)}}return n}function xi(e,t){let o=e?.terminate?.capability;return typeof o=="string"&&/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(o)&&t.includes(o)}function on(e){if(typeof e!="string")return null;let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/.exec(e);if(!t)return null;let[,o,n,s,r,a,i]=t,l=t[8],p=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(s)<1||Number(s)>p||Number(r)>23||Number(a)>59||Number(i)>59||l!=="Z"&&(Number(l.slice(1,3))>23||Number(l.slice(4))>59))return null;let _=Date.parse(e);return Number.isFinite(_)?_:null}function Ui(e,t,o,n){let s=e?.[t];if(!s||t==="terminate"&&s.beforeFact===void 0)return null;let r=s.beforeFact,a=Ee(o),i=r&&a&&Object.hasOwn(a,r)?on(a[r]):null,l=n instanceof Date?n.getTime():on(n);return i===null||l===null||!Number.isFinite(l)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":l<i?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}import*as Ke from"crypto";var rn="native-4",an={"application-native-2":"1.0.0","authz.native-batch-explain":"1.0.0","authz.native-management":"1.0.0","deployment.durable-runs":"1.0.0","deployment.platform-executor":"1.0.0","environment.on-demand-production":"1.0.0","environment.runtime-lifecycle":"1.0.0","data-api-v2":"1.1.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","workflow.named-input-sources":"1.0.0","directory-v2":"1.0.0","events-v2":"1.0.0","events.durable-receipts":"1.0.0","events.capture-policy":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","business-process.durable-command":"1.1.0","workflow.fresh-command-token":"1.0.0","notification-hub-v2":"1.0.0","authentication.application-login-surface":"1.0.0","public-access.anonymous-owner-records":"1.0.0"};var Wi=5,Bi=20,Ji=50,Gi=50,zi=100,Fe=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function ze(e,t){let o=[],n=(s,r,a)=>{a>5&&Pe("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",r);let i=dn(s,r),l=["allOf","anyOf"].filter(d=>d in i);if(l.length===0){o.push({rule:i,pointer:r}),o.length>50&&Pe("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",r);return}let p=l[0],_=i[p];(l.length!==1||Object.keys(i).length!==1||!Array.isArray(_)||_.length<1||_.length>20)&&Pe("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",r),_.forEach((d,c)=>n(d,`${r}/${p}/${c}`,a+1))};return n(e,t,1),o}function cn(e,t){ze(e,t);let o=(n,s)=>{let r=dn(n,s);if(Array.isArray(r.allOf))return mt(r.allOf.flatMap((a,i)=>o(a,`${s}/allOf/${i}`)),s);if(Array.isArray(r.anyOf)){let a=[[]];return r.anyOf.forEach((i,l)=>{let p=o(i,`${s}/anyOf/${l}`);a=mt(a.flatMap(_=>p.map(d=>[..._,...d])),s)}),a}return[[r]]};return mt(o(e,t),t)}function mt(e,t){let o=e.reduce((n,s)=>n+s.length,0);return(e.length>50||o>100)&&Pe("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function dn(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&Pe("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function Pe(e,t){throw new Fe(e,t)}var Uo="openxiangda.config-bundle/v3",Rn="openxiangda.contract-bundle/v3",ln="openxiangda.native-configuration-projection/v1",Le=rn,Mo=/^[a-f0-9]{64}$/,jo=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Wo=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,Bo=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,Jo=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,Go=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,zo=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,un=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,Yo=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,Ho=/^[A-Z][A-Z0-9_]*$/,Ko=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,qo=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Xo=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,Qo=16,Zo=2*1024,es=new Set(["text.short","text.long","number.integer","number.decimal","boolean","date","time","datetime","option.single","option.multiple","cascade.single","cascade.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple","uuid","serial-number"]),ts=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),ns=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),os=4*1024*1024,ss=8*1024*1024,is=40,rs=1e5,gt=1024*1024,as="openxiangda.event-handler-manifest/v2",Dn="openxiangda.application-route-manifest/v3",fn=64,cs=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),K=Object.freeze({perspectives:100,resources:100,capabilities:2e3,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:100,routes:500,adminPages:500,adminNavigationGroups:100,adminNavigationItems:500}),Tt=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],Ct=["openxiangda.workflow.instance.started.v2","openxiangda.workflow.instance.cc_added.v2","openxiangda.workflow.instance.completed.v2","openxiangda.workflow.instance.rejected.v2","openxiangda.workflow.instance.returned.v2","openxiangda.workflow.instance.resumed.v2","openxiangda.workflow.instance.withdrawn.v2","openxiangda.workflow.instance.terminated.v2","openxiangda.workflow.task.created.v2","openxiangda.workflow.task.assigned.v2","openxiangda.workflow.task.assignment_pending.v2","openxiangda.workflow.task.assignment_resolution_failed.v2","openxiangda.workflow.task.approved.v2","openxiangda.workflow.task.completed.v2","openxiangda.workflow.task.rejected.v2","openxiangda.workflow.task.returned.v2","openxiangda.workflow.task.resubmitted.v2","openxiangda.workflow.task.transferred.v2","openxiangda.workflow.task.reassigned.v2","openxiangda.workflow.task.delegated.v2","openxiangda.workflow.task.assignee_added.v2","openxiangda.workflow.task.cancelled.v2","openxiangda.workflow.participant.activated.v2","openxiangda.workflow.participant.completed.v2","openxiangda.workflow.participant.rejected.v2","openxiangda.workflow.participant.returned.v2","openxiangda.workflow.participant.transferred.v2","openxiangda.workflow.participant.reassigned.v2","openxiangda.workflow.participant.delegated.v2","openxiangda.workflow.participant.added.v2","openxiangda.workflow.participant.suspended.v2","openxiangda.workflow.participant.resumed.v2","openxiangda.workflow.participant.cancelled.v2"],ds=new Set(Ct),bt=class extends Error{code;pointer;identifiers;constructor(t,o,n={}){super(t),this.name="NativeConfigurationCompilerError",this.code=t,this.pointer=o,this.identifiers=Object.fromEntries(Object.entries(n).slice(0,8).map(([s,r])=>[s,String(r).slice(0,128)]))}};function rr(e){let t=R(e.appCode,"/appCode",128);jo.test(t)||u("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=$t(e.expectedConfigDigest,"/expectedConfigDigest"),n=$t(e.expectedContractDigest,"/expectedContractDigest"),s=On(e.configBytes,os,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),r=On(e.contractBytes,ss,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");$n(s,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),$n(r,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let a=Cn(s,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),i=Cn(r,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");bn(a,"/config"),bn(i,"/contracts");let l=a,p=i;ps(l,t),_s(p,t,o);let _=Es(l,o,p.generatorVersion);Qs(_,p,l),H(_)!==H(p)&&u("NATIVE_CONTRACT_CLOSURE_MISMATCH",ht(_,p,"/contracts"));let d={authz:{appCode:t,...l.authz,perspectives:l.perspectives,capabilityCatalog:_.capabilities},data:{appCode:t,resources:l.data.resources,resourceContracts:_.resources},events:{appCode:t,...l.events,consumers:_.eventConsumers,producers:_.eventProducers,handlerManifest:_.eventHandlerManifest,eventTypes:_.eventTypes,capturePlans:us({resources:l.data.resources,dataPolicies:l.authz.dataPolicies,subscriptions:_.eventConsumers,capturePolicies:l.events.capturePolicies})},workflows:{appCode:t,...l.workflows,contracts:_.workflows},runtime:{appCode:t,requirements:l.runtime,backend:l.backend,frontend:l.frontend},contracts:_},c={authz:he(d.authz),data:he(d.data),events:he(d.events),workflows:he(d.workflows),runtime:he(d.runtime),contracts:he(d.contracts)},A={configDigest:o,contractDigest:n,generatorVersion:p.generatorVersion},f=ls(l),E={schemaVersion:ln,compilerContractVersion:Le,appCode:t,source:A,projections:c,requiredPlatformCapabilities:f,aggregateDigest:X({schemaVersion:ln,compilerContractVersion:Le,appCode:t,source:A,requiredPlatformCapabilities:f,projectionDigests:Object.fromEntries(Object.entries(c).map(([N,m])=>[N,m.digest]))})};return Mn(E)}function ls(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,s=t.some(f=>f.capabilities.some(E=>E.endsWith(":directory:read")))||o.some(f=>f.schema.fields.some(E=>["user.single","user.multiple","department.single","department.multiple"].includes(E.type)))||n.some(f=>f.platformAccess?.directory),r=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),a=n.some(f=>f.platformAccess?.managedFiles||f.platformAccess?.managedFileCopies)||e.events.subscriptions.some(f=>f.platformAccess?.managedFileCopies),i=n.some(f=>f.platformAccess?.notification)||e.events.subscriptions.some(f=>f.platformAccess?.notification),l=e.workflows.definitions.filter(f=>f.launch.mode==="standalone"||f.launch.mode==="hidden-handoff"),p=n.some(f=>f.platformAccess?.workflow)||l.length>0,_={resources:o},d={perspectives:e.perspectives,authz:e.authz},c={schemaVersion:e.schemaVersion,appCode:e.appCode,frontend:{routes:e.frontend.routes,user:e.frontend.user,admin:e.frontend.admin,devicePolicy:e.frontend.devicePolicy},backend:{operations:n.map(f=>({code:f.code,method:f.method,path:f.path,capability:f.capability,platformAccess:f.platformAccess||null,ai:f.ai||null}))}};return[{code:"application-native-2",declaration:c},{code:"authz.native-batch-explain",declaration:d},{code:"authz.native-management",declaration:d},{code:"deployment.durable-runs",declaration:c.backend},{code:"deployment.platform-executor",declaration:c.backend},{code:"environment.on-demand-production",declaration:{environments:["preproduction","production"]}},{code:"environment.runtime-lifecycle",declaration:{environments:["preproduction","production"]}},...o.length?[{code:"data-api-v2",declaration:_},{code:"data.native-golden-crud",declaration:_}]:[],...o.some(Mt)?[{code:"data.audit-read-access",declaration:_}]:[],...s?[{code:"directory-v2",declaration:{roles:t.map(f=>({code:f.code,capabilities:f.capabilities.filter(E=>E.endsWith(":directory:read"))})),resources:o.map(f=>({code:f.code,fields:f.schema.fields.filter(E=>["user.single","user.multiple","department.single","department.multiple"].includes(E.type))})),operations:n.filter(f=>f.platformAccess?.directory).map(f=>({code:f.code,directory:f.platformAccess.directory}))}}]:[],...a?[{code:"data.managed-files",declaration:{operations:n.filter(f=>f.platformAccess?.managedFiles||f.platformAccess?.managedFileCopies).map(f=>({code:f.code,...f.platformAccess?.managedFiles?{managedFiles:f.platformAccess.managedFiles}:{},...f.platformAccess?.managedFileCopies?{managedFileCopies:f.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(f=>f.platformAccess?.managedFileCopies).map(f=>({code:f.code,managedFileCopies:f.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(f=>f.execution)?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(f=>f.execution)}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...r?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(f=>f.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(f=>f.definition.instanceCommands!==void 0)}]:[],...p?[{code:"business-process.durable-command",declaration:{operations:n.filter(f=>f.platformAccess?.workflow).map(f=>({code:f.code,workflow:f.platformAccess.workflow})),definitions:l,activations:e.workflows.activations.filter(f=>l.some(E=>E.definition.code===f.workflowCode))}}]:[],...i?[{code:"notification-hub-v2",declaration:{operations:n.filter(f=>f.platformAccess?.notification).map(f=>({code:f.code,notification:f.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(f=>f.platformAccess?.notification).map(f=>({code:f.code,notification:f.platformAccess.notification}))}}]:[],...e.frontend.authentication?[{code:"authentication.application-login-surface",declaration:e.frontend.authentication}]:[],...e.frontend.publicAccess?[{code:"public-access.anonymous-owner-records",declaration:e.frontend.publicAccess}]:[]].map(({code:f,declaration:E})=>({code:f,contractVersion:an[f],usageDigest:`sha256:${X(E)}`})).sort((f,E)=>f.code===E.code?0:f.code<E.code?-1:1)}function us(e){let t=new Map,o=new Set(e.resources.map(r=>String(r.code)));for(let[r,a]of $(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let i=`/capturePlan/capturePolicies/${r}`,l=I(a,i);C(l,["resourceCode","mode"],i);let p=G(l.resourceCode,`${i}/resourceCode`);o.has(p)||u("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",i,{resourceCode:p}),t.has(p)&&u("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",i,{resourceCode:p}),l.mode!=="all"&&l.mode!=="subscribed"&&u("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${i}/mode`),t.set(p,l.mode)}let n=new Map(e.dataPolicies.map((r,a)=>{let i=I(r,`/capturePlan/dataPolicies/${a}`);return[String(i.code),i]})),s=e.subscriptions.map((r,a)=>I(r,`/capturePlan/subscriptions/${a}`));return e.resources.map((r,a)=>{let i=`/capturePlan/resources/${a}`,l=I(r,i),p=G(l.code,`${i}/code`),_=l.schema?I(l.schema,`${i}/schema`):l,d=new Set($(_.fields||[],`${i}/schema/fields`,500).map((O,V)=>z(I(O,`${i}/schema/fields/${V}`).code,`${i}/schema/fields/${V}/code`))),c=l.dataPolicyCode?y(l.dataPolicyCode,`${i}/dataPolicyCode`):null,A=c?n.get(c):void 0;c&&!A&&u("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",i,{resourceCode:p,dataPolicyCode:c});let f=new Set;for(let O of A?.rules||[])f.add(String(O.field));if(A?.readExpression)for(let O of ze(A.readExpression,`${i}/readExpression`))f.add(String(O.rule.field));let E=new Set,N=new Set,m=new Set;for(let[O,V]of s.entries()){let w=$(V.eventTypes,`/capturePlan/subscriptions/${O}/eventTypes`,20).map(String);if(!w.some(B=>B.startsWith("openxiangda.data.")))continue;let x=I(V.filter||{},`/capturePlan/subscriptions/${O}/filter`),M=Array.isArray(x.resourceCodes)?x.resourceCodes.map(String):[];if(M.length&&!M.includes(p))continue;for(let B of w)Tt.includes(B)&&m.add(B);for(let B of fs(x,`/capturePlan/subscriptions/${O}/filter`))E.add(B);let ee=I(V.payload||{},`/capturePlan/subscriptions/${O}/payload`);for(let B of $(ee.fields||[],`/capturePlan/subscriptions/${O}/payload/fields`,32))N.add(z(B,`/capturePlan/subscriptions/${O}/payload/fields`))}let g=new Set([...E,...N]),T=new Set([...g,...f]);T.size>fn&&u("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",i,{resourceCode:p,maximum:fn});for(let O of T)!d.has(O)&&!(f.has(O)&&cs.has(O))&&u("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",i,{resourceCode:p,field:O});let D=I(l.fieldPolicies||{},`${i}/fieldPolicies`);for(let O of g)D[O]?.mask==="omit"&&u("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",i,{resourceCode:p,field:O});let b={resourceCode:p,...t.get(p)==="subscribed"?{capturedEventTypes:[...m].sort()}:{},filterFields:[...E].sort(),projectionFields:[...N].sort(),authorizationFields:[...f].sort(),captureFields:[...T].sort()};return{...b,digest:X(b)}}).sort((r,a)=>r.resourceCode.localeCompare(a.resourceCode))}function fs(e,t){let o=new Set;for(let[a,i]of $(e.changes||[],`${t}/changes`,16).entries()){let l=I(i,`${t}/changes/${a}`);o.add(z(l.field,`${t}/changes/${a}/field`))}let n=I(e.changedFields||{},`${t}/changedFields`);for(let a of["anyOf","allOf","noneOf"])for(let[i,l]of $(n[a]||[],`${t}/changedFields/${a}`,32).entries())o.add(z(l,`${t}/changedFields/${a}/${i}`));let s=0,r=(a,i,l)=>{l>3&&u("NATIVE_EVENT_FILTER_DEPTH_LIMIT",i);let p=I(a,i);if(p.change){let d=I(p.change,`${i}/change`);o.add(z(d.field,`${i}/change/field`)),s+=1;return}if(p.not){r(p.not,`${i}/not`,l+1);return}let _=p.all?"all":p.any?"any":null;_||u("NATIVE_EVENT_FILTER_CONDITION_INVALID",i);for(let[d,c]of $(p[_],`${i}/${_}`,16).entries())r(c,`${i}/${_}/${d}`,l+1)};return e.where&&r(e.where,`${t}/where`,1),s+=Array.isArray(e.changes)?e.changes.length:0,s>16&&u("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function ps(e,t){C(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),v(e.schemaVersion,Uo,"/config/schemaVersion"),v(e.compilerContractVersion,Le,"/config/compilerContractVersion"),v(e.appCode,t,"/config/appCode"),$(e.perspectives,"/config/perspectives",100);let o=I(e.authz,"/config/authz");C(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),$(o.capabilities,"/config/authz/capabilities",2e3),$(o.roles,"/config/authz/roles",100),$(o.scopeDimensions,"/config/authz/scopeDimensions",100),$(o.scopeSources,"/config/authz/scopeSources",100),$(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),$(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),$(o.dataPolicies,"/config/authz/dataPolicies",100),$(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=I(e.backend,"/config/backend");C(n,["secrets","operations"],"/config/backend"),$(n.secrets,"/config/backend/secrets",100),$(n.operations,"/config/backend/operations",500),zs(n.secrets);let s=I(e.data,"/config/data");C(s,["resources"],"/config/data",["resourceDetailRoutes"]),$(s.resources,"/config/data/resources",100),s.resourceDetailRoutes!==void 0&&$(s.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let r=I(e.events,"/config/events");C(r,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),$(r.schemas,"/config/events/schemas",100),$(r.subscriptions,"/config/events/subscriptions",100),$(r.timers,"/config/events/timers",100),$(r.dateTriggers,"/config/events/dateTriggers",100);let a=I(e.workflows,"/config/workflows");C(a,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),$(a.definitions,"/config/workflows/definitions",100),$(a.bindings,"/config/workflows/bindings",100),$(a.activations,"/config/workflows/activations",100),$(a.providers,"/config/workflows/providers",100),$(a.editableParameters,"/config/workflows/editableParameters",100);let i=I(e.frontend,"/config/frontend");C(i,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),$(i.routes,"/config/frontend/routes",500);let l=I(i.user,"/config/frontend/user");C(l,["applicationTodoCenter"],"/config/frontend/user"),De(l.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),Rt(i.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(i,"authentication")&&yn(i.authentication,i.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(i,"publicAccess")&&Rs(i.publicAccess,e,"/config/frontend/publicAccess");let p=I(i.admin,"/config/frontend/admin");C(p,["navigation"],"/config/frontend/admin",["access"]),p.access!==void 0&&Xe(p.access,"/config/frontend/admin/access",e.appCode),Vs(p.navigation,"/config/frontend/admin/navigation");let _=I(e.runtime,"/config/runtime");C(_,["protocolCapabilities","health"],"/config/runtime"),F(_.protocolCapabilities,"/config/runtime/protocolCapabilities",100),C(I(_.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),v(_.health.livePath,"/__platform/health","/config/runtime/health/livePath"),v(_.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),v(_.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function _s(e,t,o){C(e,["schemaVersion","compilerContractVersion","generatorVersion","appCode","configDigest","perspectives","resources","capabilities","operations","eventConsumers","eventProducers","eventSchemas","eventHandlerManifest","eventTypes","workflows","routes","routeManifest","adminPages","adminNavigation"],"/contracts",["authentication","publicAccess","adminAccess"]),v(e.schemaVersion,Rn,"/contracts/schemaVersion"),v(e.compilerContractVersion,Le,"/contracts/compilerContractVersion"),R(e.generatorVersion,"/contracts/generatorVersion",128),v(e.appCode,t,"/contracts/appCode"),v(e.configDigest,o,"/contracts/configDigest"),$(e.perspectives,"/contracts/perspectives",K.perspectives),$(e.resources,"/contracts/resources",K.resources),$(e.capabilities,"/contracts/capabilities",K.capabilities),$(e.operations,"/contracts/operations",K.operations),$(e.eventConsumers,"/contracts/eventConsumers",K.eventConsumers),$(e.eventProducers,"/contracts/eventProducers",K.eventProducers),$(e.eventSchemas,"/contracts/eventSchemas",K.eventSchemas),I(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),F(e.eventTypes,"/contracts/eventTypes",K.eventTypes),$(e.workflows,"/contracts/workflows",K.workflows),$(e.routes,"/contracts/routes",K.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&Os(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&Ds(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&Xe(e.adminAccess,"/contracts/adminAccess",t),ks(e.routeManifest,"/contracts/routeManifest",t),Fs(e.adminPages,"/contracts/adminPages"),vs(e.adminNavigation,"/contracts/adminNavigation")}function Es(e,t,o){let n=ms(e);Ws(e,n),Js(e),Bs(e),Ys(e);let s=e.events.schemas.map((c,A)=>{let f=`/config/events/schemas/${A}`,E=I(c,f),N=R(E.eventType,`${f}/eventType`,255);return N.startsWith("openxiangda.")&&u("NATIVE_EVENT_SCHEMA_RESERVED",`${f}/eventType`,{eventType:N}),v(E.schemaDigest,X(I(E.jsonSchema,`${f}/jsonSchema`)),`${f}/schemaDigest`),E}),r=new Set([...Tt,...Ct,...s.map(c=>String(c.eventType))]),a=new Map(e.data.resources.map(c=>[String(c.code),new Map(c.schema.fields.map(A=>[String(A.code),String(A.type)]))])),i=ne(e.events.subscriptions.map((c,A)=>{let f=`/config/events/subscriptions/${A}`,E=I(c,f),N=F(E.eventTypes,`${f}/eventTypes`,20);N.forEach((D,b)=>{r.has(D)||u("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${f}/eventTypes/${b}`,{eventType:D})});let m=nn(E,e.data.resources,f),g=Is(E.delivery,N,`${f}/delivery`),T=As(E.platformAccess,`${f}/platformAccess`,a);return{code:y(E.code,`${f}/code`),endpointPath:ie(E.endpointPath,`${f}/endpointPath`),eventTypes:N,filter:I(E.filter,`${f}/filter`),payload:m?.payload||I(E.payload,`${f}/payload`),...m?{execution:m.execution}:{},...T?{platformAccess:T}:{},delivery:g}}),c=>c.code),l=new Map(s.map(c=>[String(c.eventType),String(c.dataSchemaVersion)])),p=ne([...e.data.resources.flatMap(c=>Tt.map(A=>({code:`data:${c.code}:${A}`,source:"data",eventType:A,dataSchemaVersion:"2.0.0",resourceCode:c.code}))),...s.map(c=>({code:`app:${c.eventType}`,source:"app",eventType:c.eventType,dataSchemaVersion:c.dataSchemaVersion})),...e.events.timers.map(c=>({code:c.code,source:"timer",eventType:c.eventType,dataSchemaVersion:l.get(String(c.eventType))||"2.0.0"})),...e.events.dateTriggers.map(c=>({code:c.code,source:"date",eventType:c.eventType,dataSchemaVersion:l.get(String(c.eventType))||"2.0.0",resourceCode:c.resourceCode,field:c.field})),...e.workflows.activations.length?Ct.map(c=>({code:`workflow:${c}`,source:"workflow",eventType:c,dataSchemaVersion:"2.0.0"})):[]],c=>`${c.source}:${c.code}:${c.eventType}`),_=U([...i.flatMap(c=>c.eventTypes),...p.map(c=>String(c.eventType))]);Ps(e);let d=Pn(e);return{schemaVersion:Rn,compilerContractVersion:Le,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:Ns(e),capabilities:ne(n,c=>c.code),operations:Sn(e),eventConsumers:i,eventProducers:p,eventSchemas:s,eventHandlerManifest:{schemaVersion:as,appCode:e.appCode,handlers:i.filter(c=>!c.execution).map(c=>({code:c.code,endpointPath:c.endpointPath,eventTypes:c.eventTypes,dataSchemaVersions:U(c.eventTypes.map(A=>A.startsWith("openxiangda.")?"2.0.0":l.get(A)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2}))},eventTypes:_,workflows:Ln(e),routes:qe(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:$s(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:Ss(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:Ms(e),adminPages:d,adminNavigation:ys(e)}}function As(e,t,o){if(e===void 0)return;let n=I(e,t);C(n,["notification","managedFileCopies"],t,!0);let s={};if(n.notification!==void 0){let r=I(n.notification,`${t}/notification`);C(r,["mode"],`${t}/notification`),v(r.mode,"business-standard",`${t}/notification/mode`),s.notification={mode:"business-standard"}}if(n.managedFileCopies!==void 0){let r=$(n.managedFileCopies,`${t}/managedFileCopies`,16);r.length||u("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let a=new Set;s.managedFileCopies=ne(r.map((i,l)=>{let p=`${t}/managedFileCopies/${l}`,_=I(i,p);C(_,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],p),v(_.mode,"copy",`${p}/mode`);let d=G(_.sourceResourceCode,`${p}/sourceResourceCode`),c=G(_.targetResourceCode,`${p}/targetResourceCode`),A=o.get(d),f=o.get(c);(!A||!f)&&u("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",p);let E=F(_.sourceFieldCodes,`${p}/sourceFieldCodes`,16),N=F(_.targetFieldCodes,`${p}/targetFieldCodes`,16);(!E.length||E.length!==N.length)&&u("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",p),E.forEach((g,T)=>{let D=A.get(g),b=f.get(N[T]);(!["file","image"].includes(String(D))||D!==b)&&u("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${p}/sourceFieldCodes/${T}`)});let m=`${d}:${E.join(",")}=>${c}:${N.join(",")}`;return a.has(m)&&u("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",p),a.add(m),{mode:"copy",sourceResourceCode:d,sourceFieldCodes:U(E),targetResourceCode:c,targetFieldCodes:U(N)}}),i=>`${i.sourceResourceCode}:${i.sourceFieldCodes.join(",")}=>${i.targetResourceCode}:${i.targetFieldCodes.join(",")}`)}return Object.keys(s).length||u("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),s}function Is(e,t,o){let n=I(e,o);C(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),Z(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),Z(n.maxAttempts,`${o}/maxAttempts`,1,12);let s=Z(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);Z(n.maxBackoffMs,`${o}/maxBackoffMs`,s,18e5),Z(n.concurrency,`${o}/concurrency`,1,50);let r=R(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(r)||u("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),r==="workflow-instance"&&t.some(a=>!ds.has(a))&&u("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function ms(e){let t=new Map;for(let o of Un(e.appCode))t.set(o.code,o);for(let[o,n]of e.authz.capabilities.entries()){let s=`/config/authz/capabilities/${o}`,r=I(n,s);C(r,["code","kind","name","description"],s,!0);let a=Ae(r.code,`${s}/code`,e.appCode);t.has(a)&&u("NATIVE_CAPABILITY_DUPLICATE",`${s}/code`),["backend","ui"].includes(r.kind)||u("NATIVE_CAPABILITY_KIND_INVALID",`${s}/kind`);let i={code:a,kind:r.kind,name:R(r.name,`${s}/name`,255),source:"explicit",...r.description===void 0?{}:{description:St(r.description,`${s}/description`,2e3)}};t.set(a,i)}for(let[o,n]of e.data.resources.entries()){let s=`/config/data/resources/${o}`,r=ke(n,s,e.appCode),a={read:`\u8BFB\u53D6${r.name}`,create:`\u65B0\u5EFA${r.name}`,update:`\u66F4\u65B0${r.name}`,delete:`\u5220\u9664${r.name}`};for(let i of["read","create","update","delete"]){let l=Ae(r.capabilities[i],`${s}/capabilities/${i}`,e.appCode);t.has(l)&&u("NATIVE_CAPABILITY_DUPLICATE",`${s}/capabilities/${i}`),t.set(l,{code:l,kind:"data",name:a[i],source:"data"})}for(let[i,l]of Object.entries(r.fieldPolicies)){if(Se(i))continue;let p=I(l,`${s}/fieldPolicies/${i}`);for(let _ of["read","create","update"])if(Array.isArray(p[_]))for(let d of F(p[_],`${s}/fieldPolicies/${i}/${_}`,2e3))Ae(d,`${s}/fieldPolicies/${i}/${_}`,e.appCode),!t.has(d)&&t.set(d,{code:d,kind:"data",name:`${r.name}.${i}.${_}`,source:"data"})}}return[...t.values()]}function Ns(e){let t=gs(e);return ne(e.data.resources.map((o,n)=>{let s=ke(o,`/config/data/resources/${n}`,e.appCode),r=t.get(s.code);return{code:s.code,schemaDigest:X(s.schema),fields:ne(s.schema.fields.map(a=>({code:a.code,type:a.type})),a=>a.code),...r?{detailRouteCode:r}:{}}}),o=>o.code)}function gs(e){let t=e.data.resourceDetailRoutes===void 0?[]:$(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((r,a)=>{let i=`/config/data/resources/${a}`,l=ke(r,i,e.appCode);return[l.code,l]})),n=new Map(qe(e).map(r=>[String(r.code),r])),s=new Map;for(let[r,a]of t.entries()){let i=`/config/data/resourceDetailRoutes/${r}`,l=I(a,i);C(l,["resourceCode","desktop","mobile"],i);let p=G(l.resourceCode,`${i}/resourceCode`);s.has(p)&&u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${i}/resourceCode`);let _=o.get(p);_||u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${i}/resourceCode`);let d=y(l.desktop,`${i}/desktop`),c=y(l.mobile,`${i}/mobile`);d===c&&u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",i);let A=String(_.capabilities.read);for(let[f,E]of[["desktop",d],["mobile",c]]){let N=`${i}/${f}`,m=n.get(E);m||u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",N),m.surface!=="user"&&u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",N);let g=ie(m.path,`${N}/path`),T=[...g.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],D=f==="mobile"?!g.startsWith("/m/"):g==="/m"||g.startsWith("/m/");(g.includes("*")||g.includes("?")||g.includes("#")||g.split("/").includes("..")||T.length!==1||D)&&u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",N);let b=Array.isArray(m.access?.allOf)?m.access.allOf:[];m.capability!==A&&!b.includes(A)&&u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",N)}s.set(p,{desktop:d,mobile:c})}return s}function Sn(e){let t=new Map(e.data.resources.map((s,r)=>{let a=`/config/data/resources/${r}`,i=ke(s,a,e.appCode);return[i.code,new Map(i.schema.fields.map(l=>[String(l.code),String(l.type)]))]})),o=new Set(t.keys()),n=new Set(e.workflows.activations.map((s,r)=>Qe(I(s,`/config/workflows/activations/${r}`).workflowCode,`/config/workflows/activations/${r}/workflowCode`)));return ne(e.backend.operations.map((s,r)=>{let a=`/config/backend/operations/${r}`,i=I(s,a);C(i,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","ai"],a,!0);let l=R(i.method,`${a}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(l)||u("NATIVE_OPERATION_METHOD_INVALID",`${a}/method`);let p=y(i.code,`${a}/code`);Cs(i.ai,a,p,l,o);let _=Ts(i.platformAccess,`${a}/platformAccess`,t,n,new Set(e.authz.roles.map(d=>String(d.code))));return{code:p,method:l,path:ie(i.path,`${a}/path`),requiredCapability:Ae(i.capability,`${a}/capability`,e.appCode),requestSchemaDigest:X(I(i.requestSchema,`${a}/requestSchema`)),responseSchemaDigest:X(I(i.responseSchema,`${a}/responseSchema`)),...i.description===void 0?{}:{description:St(i.description,`${a}/description`,2e3)},..._?{platformAccess:_}:{}}}),s=>s.code)}function Ts(e,t,o,n,s){if(e===void 0)return null;let r=I(e,t);C(r,["directory","managedFiles","managedFileCopies","notification","workflow","roleAssertions"],t,!0),Object.keys(r).length===0&&u("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let a={};if(r.roleAssertions!==void 0){let i=I(r.roleAssertions,`${t}/roleAssertions`);C(i,["roleCodes"],`${t}/roleAssertions`);let l=F(i.roleCodes,`${t}/roleAssertions/roleCodes`,20);l.length||u("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),l.forEach((p,_)=>{s.has(p)||u("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${_}`)}),a.roleAssertions={roleCodes:U(l)}}if(r.directory!==void 0){let i=I(r.directory,`${t}/directory`);C(i,["mode","fields"],`${t}/directory`),i.mode!=="current-initiator"&&u("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let l=new Set(["displayName","employeeNumber","primaryDepartment","departments"]),p=F(i.fields,`${t}/directory/fields`,4);(!p.length||p.some(_=>!l.has(_)))&&u("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),a.directory={mode:"current-initiator",fields:U(p)}}if(r.managedFiles!==void 0){let i=$(r.managedFiles,`${t}/managedFiles`,16);i.length||u("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let l=new Set;a.managedFiles=ne(i.map((p,_)=>{let d=`${t}/managedFiles/${_}`,c=I(p,d);C(c,["resourceCode","fieldCodes","intents"],d);let A=G(c.resourceCode,`${d}/resourceCode`);(l.has(A)||!o.has(A))&&u("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${d}/resourceCode`),l.add(A);let f=F(c.fieldCodes,`${d}/fieldCodes`,16);(!f.length||f.some(N=>!["file","image","signature"].includes(String(o.get(A)?.get(N)||""))))&&u("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${d}/fieldCodes`);let E=F(c.intents,`${d}/intents`,2);return(!E.length||E.some(N=>!["create","update"].includes(N)))&&u("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${d}/intents`),{resourceCode:A,fieldCodes:U(f),intents:U(E)}}),p=>p.resourceCode)}if(r.managedFileCopies!==void 0){let i=$(r.managedFileCopies,`${t}/managedFileCopies`,16);i.length||u("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let l=new Set;a.managedFileCopies=ne(i.map((p,_)=>{let d=`${t}/managedFileCopies/${_}`,c=I(p,d);C(c,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],d),v(c.mode,"copy",`${d}/mode`);let A=G(c.sourceResourceCode,`${d}/sourceResourceCode`),f=G(c.targetResourceCode,`${d}/targetResourceCode`),E=o.get(A),N=o.get(f);(!E||!N)&&u("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",d);let m=F(c.sourceFieldCodes,`${d}/sourceFieldCodes`,16),g=F(c.targetFieldCodes,`${d}/targetFieldCodes`,16);(!m.length||m.length!==g.length)&&u("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",d),m.forEach((D,b)=>{let O=E.get(D),V=N.get(g[b]);(!["file","image"].includes(String(O))||O!==V)&&u("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${d}/sourceFieldCodes/${b}`)});let T=`${A}:${m.join(",")}=>${f}:${g.join(",")}`;return l.has(T)&&u("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",d),l.add(T),{mode:"copy",sourceResourceCode:A,sourceFieldCodes:U(m),targetResourceCode:f,targetFieldCodes:U(g)}}),p=>`${p.sourceResourceCode}:${p.sourceFieldCodes.join(",")}=>${p.targetResourceCode}:${p.targetFieldCodes.join(",")}`)}if(r.notification!==void 0){let i=I(r.notification,`${t}/notification`);C(i,["mode"],`${t}/notification`),i.mode!=="business-standard"&&u("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),a.notification={mode:"business-standard"}}if(r.workflow!==void 0){let i=I(r.workflow,`${t}/workflow`);C(i,["codes"],`${t}/workflow`);let l=F(i.codes,`${t}/workflow/codes`,16);(!l.length||l.some(p=>!n.has(p)))&&u("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`),a.workflow={codes:U(l)}}return a}function Cs(e,t,o,n,s){if(e===void 0)return;let r=`${t}/ai`,a=I(e,r);Jo.test(o)||u("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),C(a,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],r,!0),R(a.name,`${r}/name`,gt),R(a.description,`${r}/description`,gt);let i=R(a.risk,`${r}/risk`,16);["read","write","destructive","external"].includes(i)||u("NATIVE_OPERATION_AI_RISK_INVALID",`${r}/risk`),i==="read"!=(n==="GET")&&u("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`),n==="DELETE"&&!["destructive","external"].includes(i)&&u("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`);let l=F(a.resources,`${r}/resources`,16);l.length===0&&u("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${r}/resources`),l.forEach((_,d)=>{let c=G(_,`${r}/resources/${d}`);s.has(c)||u("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${r}/resources/${d}`)});let p=F(a.sideEffects,`${r}/sideEffects`,20);(i==="read"&&p.length!==0||i!=="read"&&p.length===0)&&u("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${r}/sideEffects`),a.concurrency!==void 0&&!["none","revision"].includes(R(a.concurrency,`${r}/concurrency`,16))&&u("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${r}/concurrency`),a.timeoutMs!==void 0&&Z(a.timeoutMs,`${r}/timeoutMs`,100,3e4)}function Ye(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function bs(e,t){let o=I(e,t),n=R(o.type,`${t}/type`,32),s=["code","type","label","presentation","required"],r=n==="sso"?[...s,"provider"]:n==="dingtalk"?[...s,"flow"]:s;C(o,r,t);let a=y(o.code,`${t}/code`),i=R(o.label,`${t}/label`,255),l=R(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(l)||u("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let p=De(o.required,`${t}/required`);return["sso","password","dingtalk"].includes(n)||u("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),n==="sso"&&o.provider!=="tenant-default"&&u("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),n==="dingtalk"&&!["auto","jsapi","oauth"].includes(R(o.flow,`${t}/flow`,16))&&u("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:a,type:n,label:i,presentation:l,required:p,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function pn(e,t,o){let n=I(e,o);C(n,["routeCode","path","defaultRouteCode"],o);let s=y(n.routeCode,`${o}/routeCode`),r=ie(n.path,`${o}/path`),a=t==="desktop"?"/login":"/m/login";return(r!==a||/[:*?#\\]/.test(r))&&u("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:a}),{routeCode:s,path:r,defaultRouteCode:y(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function yn(e,t,o,n){if(e===null)return;let s=I(e,n);C(s,["accountMode","registration","methods","surfaces"],n),v(s.accountMode,"existing-platform-users-only",`${n}/accountMode`);let r=I(s.registration,`${n}/registration`);C(r,["mode"],`${n}/registration`),v(r.mode,"reject",`${n}/registration/mode`);let a=$(s.methods,`${n}/methods`,8);a.length===0&&u("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let i=a.map((m,g)=>bs(m,`${n}/methods/${g}`)),l=new Set,p=new Set;for(let[m,g]of i.entries())l.has(g.code)&&u("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${m}/code`),p.has(g.type)&&u("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${m}/type`),l.add(g.code),p.add(g.type);i.filter(m=>m.presentation==="primary").length!==1&&u("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let _=I(s.surfaces,`${n}/surfaces`);C(_,["desktop","mobile"],`${n}/surfaces`);let d=pn(_.desktop,"desktop",`${n}/surfaces/desktop`),c=pn(_.mobile,"mobile",`${n}/surfaces/mobile`);d.routeCode===c.routeCode&&u("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let A=$(t,"/config/frontend/routes",500),f=new Map;for(let[m,g]of A.entries()){let T=I(g,`/config/frontend/routes/${m}`);f.set(String(T.code||""),T)}let E=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(m=>String(m.code||"")).filter(m=>/^[a-z][a-z0-9-]{0,62}$/.test(m)));for(let[m,g]of[["desktop",d],["mobile",c]]){f.has(g.routeCode)&&u("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${m}/routeCode`);let T=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(g.defaultRouteCode||"")),D=f.get(g.defaultRouteCode),b=String(D?.path||"");if(T&&E.has(T[1])){let V=T[2]==="records"?`/my/${T[1]}`:`/my/${T[1]}/submit`;D={surface:"user",path:m==="mobile"?`/m${V}`:V},b=String(D.path)}let O=m==="desktop"?b==="/m"||b.startsWith("/m/"):!(b==="/m"||b.startsWith("/m/"));(!D||D.surface!=="user"||/[:*]/.test(b)||O)&&u("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${m}/defaultRouteCode`)}let N=Vn(o).filter(m=>!m.owner.startsWith("authentication:"));for(let[m,g]of[["desktop",d],["mobile",c]]){let T=N.find(D=>Ye(D.path)===Ye(g.path));T&&u("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${m}/path`,{owner:T.owner})}}function Os(e,t){if(e===null)return;let o={data:{resources:[]},workflows:{definitions:[]},frontend:{routes:[{code:"auth-desktop-default",path:"/auth-desktop-default",surface:"user"},{code:"auth-mobile-default",path:"/m/auth-mobile-default",surface:"user"}],user:{applicationTodoCenter:!1},admin:{navigation:[]},authentication:e}},n=I(e,t),s=I(n.surfaces,`${t}/surfaces`),r={...n,surfaces:{...s,desktop:{...I(s.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...I(s.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};yn(r,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:r}},t)}function $s(e){let t=e.frontend.authentication;return t===null?null:{accountMode:t.accountMode,registration:{mode:t.registration.mode},methods:t.methods.map(o=>({...o})),surfaces:{desktop:{...t.surfaces.desktop},mobile:{...t.surfaces.mobile}}}}var hs=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function Rs(e,t,o){let n=I(e,o);C(n,["policies"],o);let s=$(n.policies,`${o}/policies`,16);s.length<1&&u("NATIVE_PUBLIC_POLICY_REQUIRED",o);let r=new Map(t.frontend.routes.map(p=>[p.code,p])),a=new Map(t.data.resources.map(p=>[p.code,p])),i=new Set,l=new Set(s.map(p=>String(p?.code||"")));s.forEach((p,_)=>{let d=`${o}/policies/${_}`,c=I(p,d);C(c,["code","routeCode","mode","resourceCode","operations","fields"],d,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let A=y(c.code,`${d}/code`);i.has(A)&&u("NATIVE_PUBLIC_POLICY_DUPLICATE",`${d}/code`);let f=y(c.routeCode,`${d}/routeCode`),E=r.get(f);(!E||E.surface!=="user"||E.capability!==void 0||E.access!==void 0||/[:*]/.test(String(E.path)))&&u("NATIVE_PUBLIC_ROUTE_INVALID",`${d}/routeCode`),v(c.mode,"anonymous",`${d}/mode`);let N=G(c.resourceCode,`${d}/resourceCode`),m=a.get(N);m||u("NATIVE_PUBLIC_RESOURCE_MISSING",`${d}/resourceCode`);let g=new Map(m.schema.fields.map(S=>[String(S.code),String(S.type)])),T=F(c.operations,`${d}/operations`,8);(T.length<1||T.some(S=>!hs.has(S)))&&u("NATIVE_PUBLIC_OPERATION_INVALID",`${d}/operations`),T.includes("draft.read")!==T.includes("draft.update")&&u("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${d}/operations`);let D=F(c.fields,`${d}/fields`,64);(D.length<1||D.some(S=>!g.has(S)))&&u("NATIVE_PUBLIC_FIELD_INVALID",`${d}/fields`);for(let S of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(c,S))continue;F(c[S],`${d}/${S}`,64).some(L=>!D.includes(L))&&u("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${d}/${S}`)}let b=Object.prototype.hasOwnProperty.call(c,"serverGeneratedFields")?$(c.serverGeneratedFields,`${d}/serverGeneratedFields`,16):[],O=new Set;b.forEach((S,k)=>{let L=`${d}/serverGeneratedFields/${k}`,W=I(S,L);C(W,["field","kind"],L);let J=z(W.field,`${L}/field`);(O.has(J)||!g.has(J)||D.includes(J)||g.get(J)!=="text.short"&&g.get(J)!=="text.long")&&u("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${L}/field`),v(W.kind,"random-token",`${L}/kind`),O.add(J)});let V=Object.prototype.hasOwnProperty.call(c,"schedule")?I(c.schedule,`${d}/schedule`):null;if(V){let S=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];C(V,S,`${d}/schedule`);for(let k of["campusPolicyCode","rulePolicyCode"])y(V[k],`${d}/schedule/${k}`);for(let k of S.filter(L=>!["campusPolicyCode","rulePolicyCode"].includes(L)))z(V[k],`${d}/schedule/${k}`);for(let k of[V.campusField,V.dateField,V.timeField])D.includes(String(k))||u("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${d}/schedule`);(!l.has(String(V.campusPolicyCode))||!l.has(String(V.rulePolicyCode)))&&u("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${d}/schedule`)}let w=Object.prototype.hasOwnProperty.call(c,"publicFilters")?$(c.publicFilters,`${d}/publicFilters`,16):[],x=new Set;w.forEach((S,k)=>{let L=`${d}/publicFilters/${k}`,W=I(S,L);C(W,["field","operator","value"],L);let J=z(W.field,`${L}/field`);x.has(J)&&u("NATIVE_PUBLIC_FILTER_DUPLICATE",`${L}/field`),D.includes(J)||u("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${L}/field`),v(W.operator,"eq",`${L}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(g.get(J)||"")||u("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${L}/field`),W.value!==null&&typeof W.value!="string"&&typeof W.value!="number"&&typeof W.value!="boolean"&&u("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${L}/value`),x.add(J)});let M=Object.prototype.hasOwnProperty.call(c,"publicSubtableFields")?I(c.publicSubtableFields,`${d}/publicSubtableFields`):null;if(M){Object.keys(M).length>64&&u("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields`);for(let[S,k]of Object.entries(M)){let L=m.schema.fields.find(Y=>String(Y.code)===S),W=String(L?.subtable?.resourceCode||""),J=a.get(W),de=new Map((J?.schema?.fields||[]).map(Y=>[String(Y.code),String(Y.type)])),j=F(k,`${d}/publicSubtableFields/${S}`,64);(!D.includes(S)||g.get(S)!=="subtable"||!J||j.length<1||j.some(Y=>!de.has(Y))||j.some(Y=>de.get(Y)==="subtable")||j.some(Y=>de.get(Y)==="signature"))&&u("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields/${S}`)}}if(T.some(S=>S.startsWith("public."))){Object.prototype.hasOwnProperty.call(c,"publicRecordFields")||u("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${d}/publicRecordFields`);let S=F(c.publicRecordFields,`${d}/publicRecordFields`,64);(S.length<1||S.some(k=>!D.includes(k))||S.some(k=>g.get(k)==="signature"||g.get(k)==="subtable"&&!M?.[k]))&&u("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${d}/publicRecordFields`)}let ee=Object.prototype.hasOwnProperty.call(c,"requiredFields")?F(c.requiredFields,`${d}/requiredFields`,64):[],B=m.surface||{},Ie=B.fields||{},ge=String(B.mutationOwner||"native")==="native"&&B.generated?.create!==!1,q=m.schema.fields.filter(S=>We(S,Ie[S.code])).map(S=>String(S.code));if(T.includes("create")&&!ge&&u("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/fields`),T.includes("create")&&!Object.prototype.hasOwnProperty.call(c,"draft")&&u("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`),T.includes("create"))for(let S of q){let k=D.includes(S)?ee.includes(S)?null:"requiredFields":"fields";k&&u("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/${k}`,{resourceCode:G,fieldCode:S})}if(Object.prototype.hasOwnProperty.call(c,"draft")){let S=I(c.draft,`${d}/draft`);C(S,["enabled","inactivityTtlSeconds","maxBytes"],`${d}/draft`),v(S.enabled,!0,`${d}/draft/enabled`),Z(S.inactivityTtlSeconds,`${d}/draft/inactivityTtlSeconds`,3600,7776e3),Z(S.maxBytes,`${d}/draft/maxBytes`,4096,262144)}else T.includes("draft.read")&&u("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`);let Te=Object.prototype.hasOwnProperty.call(c,"validations")?$(c.validations,`${d}/validations`,16):[],me=new Set;Te.forEach((S,k)=>{let L=`${d}/validations/${k}`,W=I(S,L);C(W,["code","kind","fields","result"],L);let J=y(W.code,`${L}/code`);me.has(J)&&u("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${L}/code`),v(W.kind,"duplicate",`${L}/kind`),v(W.result,"availability",`${L}/result`);let de=F(W.fields,`${L}/fields`,8);(de.length<1||de.some(j=>!D.includes(j))||de.some(j=>["file","subtable"].includes(g.get(j)||"")))&&u("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${L}/fields`),me.add(J)}),i.add(A)})}function Ds(e,t){let o=I(e,t);C(o,["policies"],t),$(o.policies,`${t}/policies`,16).length<1&&u("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function Ss(e){return{policies:ne(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:U(t.operations),fields:U(t.fields),...t.requiredFields?{requiredFields:U(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:U(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:U(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(o=>({field:o.field,operator:o.operator,value:o.value})).sort((o,n)=>se(o.field,n.field))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>[o,U(Array.isArray(n)?n.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(o=>({field:o.field,kind:o.kind})).sort((o,n)=>se(o.field,n.field))}:{},...t.schedule?{schedule:{campusPolicyCode:t.schedule.campusPolicyCode,rulePolicyCode:t.schedule.rulePolicyCode,campusField:t.schedule.campusField,ruleCampusField:t.schedule.ruleCampusField,ruleWeekdaysField:t.schedule.ruleWeekdaysField,ruleOpenAtField:t.schedule.ruleOpenAtField,ruleCloseAtField:t.schedule.ruleCloseAtField,ruleSlotMinutesField:t.schedule.ruleSlotMinutesField,ruleAdvanceHoursField:t.schedule.ruleAdvanceHoursField,ruleAdvanceDaysField:t.schedule.ruleAdvanceDaysField,campusEnabledField:t.schedule.campusEnabledField,ruleEnabledField:t.schedule.ruleEnabledField,dateField:t.schedule.dateField,timeField:t.schedule.timeField}}:{},...t.draft?{draft:{...t.draft}}:{},...t.validations?{validations:ne(t.validations.map(o=>({code:o.code,kind:o.kind,fields:U(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function Vn(e){let t=[{owner:"platform:admin-entry",path:"/"},{owner:"platform:admin-entry",path:"/admin"},{owner:"platform:file-preview",path:"/files/:resourceCode/:fileId/preview"}];e.frontend.authentication&&t.push({owner:"authentication:desktop",path:e.frontend.authentication.surfaces.desktop.path},{owner:"authentication:mobile",path:e.frontend.authentication.surfaces.mobile.path});for(let o of e.data.resources){let n=wn(o),s=`/admin/resources/${o.code}`,r=[["list",s],["detail",`${s}/:id`],["create",`${s}/new`],["update",`${s}/:id/edit`]];for(let[a,i]of r)n[a]&&t.push({owner:`resource:${o.code}:${a}`,path:i},{owner:`resource:${o.code}:${a}:mobile`,path:`/m${i}`})}if(e.frontend.user.applicationTodoCenter===!0&&t.push({owner:"application:todo-center",path:"/todos"},{owner:"application:todo-center:mobile",path:"/m/todos"}),e.workflows.definitions.length>0){t.push({owner:"workflow:work-center",path:"/work-center"},{owner:"workflow:work-center:mobile",path:"/m/work-center"},{owner:"workflow:task",path:"/tasks/:taskId"},{owner:"workflow:task:mobile",path:"/m/tasks/:taskId"},{owner:"workflow:instance",path:"/workflows/:instanceId"},{owner:"workflow:instance:mobile",path:"/m/workflows/:instanceId"});let o=!1;for(let n of e.workflows.definitions)["standalone","hidden-handoff"].includes(n.launch.mode)&&(o=!0);o&&t.push({owner:"workflow:launch",path:"/workflows/:workflowCode/start"},{owner:"workflow:launch:mobile",path:"/m/workflows/:workflowCode/start"})}return t}function qe(e){let t=new Map(Vn(e).map(o=>[Ye(o.path),o]));return ne(e.frontend.routes.map((o,n)=>{let s=`/config/frontend/routes/${n}`,r=I(o,s);C(r,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],s,!0),["admin","user"].includes(r.surface)||u("NATIVE_ROUTE_SURFACE_INVALID",`${s}/surface`);let a=ie(r.path,`${s}/path`);r.surface==="admin"&&a!=="/admin"&&!a.startsWith("/admin/")&&u("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${s}/path`),r.surface==="user"&&(a==="/admin"||a.startsWith("/admin/"))&&u("NATIVE_USER_ROUTE_PATH_RESERVED",`${s}/path`);let i=Ye(a),l=t.get(i);l&&u("NATIVE_ROUTE_PATH_CONFLICT",`${s}/path`,{path:a,owner:l.owner}),t.set(i,{owner:`frontend:${String(r.code||n)}`,path:a});let p=/[:*]/.test(a),_=Dt(r,s,e.appCode),d=r.pinned===void 0?void 0:De(r.pinned,`${s}/pinned`),c=r.tabPersistence===void 0?p?"none":"session":R(r.tabPersistence,`${s}/tabPersistence`,16),A=r.keepAlive===void 0?"none":R(r.keepAlive,`${s}/keepAlive`,16);return["session","none"].includes(c)||u("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${s}/tabPersistence`),["none","memory"].includes(A)||u("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${s}/keepAlive`),p&&d===!0&&u("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${s}/pinned`),p&&c==="session"&&u("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${s}/tabPersistence`),p&&A==="memory"&&u("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${s}/keepAlive`),{code:y(r.code,`${s}/code`),path:a,label:R(r.label,`${s}/label`,255),surface:r.surface,...r.parentCode===void 0?{}:{parentCode:y(r.parentCode,`${s}/parentCode`)},..._,...d===void 0?{}:{pinned:d},tabPersistence:c,keepAlive:A}}),o=>o.code)}function wn(e){let t=e.surface===void 0?{}:I(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:I(t.generated,"/surface/generated"),s=o==="native";return{list:n.list??!0,detail:n.detail??!0,create:n.create??s,update:n.update??s,delete:n.delete??s}}function Pn(e){let t=[];for(let o of ne(e.data.resources,n=>n.code).flatMap(n=>[{resource:n,viewCode:void 0},...(n.surface?.views||[]).map(s=>({viewCode:s.code,resource:{...n,name:s.name,surface:pt(n.surface,s.code)}}))])){let{resource:n,viewCode:s}=o,r=`/admin/resources/${n.code}${s?`/views/${s}`:""}`,a=wn(n),i=[{operation:"list",kind:"resource-list",path:`${r}`,label:n.name,capability:n.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${r}/:id`,label:`${n.name}\u8BE6\u60C5`,capability:n.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${r}/new`,label:`\u65B0\u589E${n.name}`,capability:n.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${r}/:id/edit`,label:`\u7F16\u8F91${n.name}`,capability:n.capabilities.update,navigationEligible:!1}];for(let l of i)a[l.operation]&&t.push({code:`resource:${n.code}${s?`:view:${s}`:""}:${l.operation}`,kind:l.kind,path:l.path,label:l.label,navigationEligible:l.navigationEligible,capability:l.capability,resourceCode:n.code,...s?{viewCode:s}:{}})}for(let o of qe(e))o.surface==="admin"&&t.push({code:`operation:${o.code}`,kind:"operation",path:o.path,label:o.label,navigationEligible:!/[:*]/.test(o.path),routeCode:o.code});return t.sort((o,n)=>se(o.code,n.code))}function Fn(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function ys(e){return e.frontend.admin.navigation.map((t,o)=>({code:t.code,label:t.label,...t.icon===void 0?{}:{icon:t.icon},order:t.order??o,items:t.items.map((n,s)=>({pageCode:Fn(n.page),...n.label===void 0?{}:{label:n.label},...n.icon===void 0?{}:{icon:n.icon},order:n.order??s})).sort((n,s)=>n.order-s.order||se(n.pageCode,s.pageCode))})).sort((t,o)=>t.order-o.order||se(t.code,o.code))}function Vs(e,t){let o=$(e,t,K.adminNavigationGroups),n=0;o.forEach((s,r)=>{let a=`${t}/${r}`,i=I(s,a);C(i,["code","label","icon","order","items"],a,!0),y(i.code,`${a}/code`),R(i.label,`${a}/label`,255),He(i.icon,`${a}/icon`),mn(i.order,`${a}/order`);let l=$(i.items,`${a}/items`,500);l.length===0&&u("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),n+=l.length,n>K.adminNavigationItems&&u("NATIVE_ARRAY_LIMIT_EXCEEDED",t),l.forEach((p,_)=>{let d=`${a}/items/${_}`,c=I(p,d);C(c,["page","label","icon","order"],d,!0),ws(c.page,`${d}/page`),c.label!==void 0&&R(c.label,`${d}/label`,255),He(c.icon,`${d}/icon`),mn(c.order,`${d}/order`)})})}function ws(e,t){let o=I(e,t),n=R(o.kind,`${t}/kind`,64);if(n==="resource"){C(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&y(o.viewCode,`${t}/viewCode`),G(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){C(o,["kind","routeCode"],t),y(o.routeCode,`${t}/routeCode`);return}u("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function Ps(e){let t=new Map(Pn(e).map(s=>[String(s.code),s])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((s,r)=>{let a=`/config/frontend/admin/navigation/${r}`;o.has(s.code)&&u("NATIVE_ADMIN_GROUP_DUPLICATE",`${a}/code`),o.add(s.code),s.label===s.code&&u("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${a}/label`),s.items.forEach((i,l)=>{let p=`${a}/items/${l}`,_=Fn(i.page),d=t.get(_);(!d||d.navigationEligible!==!0)&&u("NATIVE_ADMIN_PAGE_NOT_FOUND",`${p}/page`),n.has(_)&&u("NATIVE_ADMIN_PAGE_DUPLICATE",`${p}/page`),n.add(_);let c=i.page.resourceCode||i.page.routeCode||i.page.workflowCode||_,A=i.label||d.label;(!A||A===c||A===_)&&u("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${p}/label`)})})}function Fs(e,t){let o=$(e,t,K.adminPages),n=new Set;o.forEach((s,r)=>{let a=`${t}/${r}`,i=I(s,a);C(i,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],a,!0);let l=R(i.code,`${a}/code`,255);n.has(l)&&u("NATIVE_ADMIN_PAGE_DUPLICATE",`${a}/code`),n.add(l);let p=R(i.kind,`${a}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(p)||u("NATIVE_ADMIN_PAGE_KIND_INVALID",`${a}/kind`),ie(i.path,`${a}/path`),R(i.label,`${a}/label`,255),De(i.navigationEligible,`${a}/navigationEligible`),i.capability!==void 0&&i.access!==void 0&&u("NATIVE_ROUTE_ACCESS_CONFLICT",`${a}/access`),i.capability!==void 0&&R(i.capability,`${a}/capability`,255),i.access!==void 0){let _=I(i.access,`${a}/access`);C(_,["allOf","anyOf"],`${a}/access`,!0);for(let d of["allOf","anyOf"])_[d]!==void 0&&F(_[d],`${a}/access/${d}`,50)}for(let _ of["resourceCode","viewCode","routeCode"])i[_]!==void 0&&y(i[_],`${a}/${_}`)})}function vs(e,t){let o=$(e,t,K.adminNavigationGroups),n=0;o.forEach((s,r)=>{let a=`${t}/${r}`,i=I(s,a);C(i,["code","label","icon","order","items"],a,!0),y(i.code,`${a}/code`),R(i.label,`${a}/label`,255),He(i.icon,`${a}/icon`),Z(i.order,`${a}/order`,-1e4,1e4);let l=$(i.items,`${a}/items`,500);l.length===0&&u("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),n+=l.length,n>K.adminNavigationItems&&u("NATIVE_ARRAY_LIMIT_EXCEEDED",t),l.forEach((p,_)=>{let d=`${a}/items/${_}`,c=I(p,d);C(c,["pageCode","label","icon","order"],d,!0),R(c.pageCode,`${d}/pageCode`,255),c.label!==void 0&&R(c.label,`${d}/label`,255),He(c.icon,`${d}/icon`),Z(c.order,`${d}/order`,-1e4,1e4)})})}var Ls=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function ks(e,t,o){let n=I(e,t);C(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),v(n.schemaVersion,Dn,`${t}/schemaVersion`),v(n.appCode,o,`${t}/appCode`),Rt(n.devicePolicy,`${t}/devicePolicy`),xs(n.rootEntry,`${t}/rootEntry`),Us(n.authentication,`${t}/authentication`),$t(n.digest,`${t}/digest`);let s=$(n.routes,`${t}/routes`,K.routes),r=new Set;s.forEach((a,i)=>{let l=`${t}/routes/${i}`,p=I(a,l),_=p.kind==="resource-records"||p.kind==="resource-submit";C(p,["code","kind","desktop","mobile"],l,["workflowCode",..._?["resourceCode"]:[]]);let d=R(p.code,`${l}/code`,255);r.has(d)&&u("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${l}/code`),r.add(d);let c=R(p.kind,`${l}/kind`,64);if(Ls.has(c)||u("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${l}/kind`),p.workflowCode!==void 0&&y(p.workflowCode,`${l}/workflowCode`),_){let E=G(p.resourceCode,`${l}/resourceCode`);v(d,`user.${E}.${p.kind==="resource-records"?"records":"submit"}`,`${l}/code`)}else p.resourceCode!==void 0&&u("NATIVE_PROPERTY_UNKNOWN",`${l}/resourceCode`);let A=En(p.desktop,`${l}/desktop`,o),f=En(p.mobile,`${l}/mobile`,o);A.surface!=="user"&&u("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${l}/desktop/surface`),f.surface!=="user"&&u("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${l}/mobile/surface`),A.routeCode===f.routeCode&&u("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",l)}),v(n.digest,X({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function Rt(e,t){let o=I(e,t);C(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),v(o.kind,"viewport-family",`${t}/kind`);let n=Z(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),s=Z(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return s!==n+1&&u("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:s}}function xs(e,t){let o=I(e,t);C(o,["code","desktop","mobile"],t);let n=y(o.code,`${t}/code`),s=Ot(o.desktop,`${t}/desktop`),r=Ot(o.mobile,`${t}/mobile`);return(s===r||r==="/"||!r.startsWith("/m/"))&&u("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),s.startsWith("/m/")&&u("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:s,mobile:r}}function Us(e,t){let o=I(e,t);C(o,["desktop","mobile"],t);let n=_n(o.desktop,`${t}/desktop`,!1),s=_n(o.mobile,`${t}/mobile`,!0);return(n.routeCode===s.routeCode||n.path===s.path)&&u("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:s}}function _n(e,t,o){let n=I(e,t);C(n,["routeCode","path"],t);let s=y(n.routeCode,`${t}/routeCode`),r=Ot(n.path,`${t}/path`);return(o?!r.startsWith("/m/"):r.startsWith("/m/"))&&u("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:s,path:r}}function Ot(e,t){let o=ie(e,t);return/[:*?#\\\\]/.test(o)&&u("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function En(e,t,o){let n=I(e,t);C(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),y(n.routeCode,`${t}/routeCode`);let s=ie(n.path,`${t}/path`),r=R(n.surface,`${t}/surface`,16);["admin","user"].includes(r)||u("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let a=F(n.pathParams,`${t}/pathParams`,8);return a.forEach((i,l)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(i)||i.length>64)&&u("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${l}`)}),H(a)!==H(vn(s))&&u("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),Dt(n,t,o),n.requiresAuthentication!==!0&&u("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function vn(e){return U([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function An(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:vn(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function In(e,t,o,n){return e==="workflow-launch"?`workflow.${o}.launch.${t}`:e==="application-todo-center"?`application.todo-center.${t}`:e==="resource-records"?`user.${n}.records.${t}`:e==="resource-submit"?`user.${n}.submit.${t}`:`${e.replace(/-/g,".")}.${t}`}function Ms(e){let t=e.appCode,o=[],n=(A,f,E,N,m,g,T)=>{o.push({code:A,kind:f,...m?{workflowCode:m}:{},...T?{resourceCode:T}:{},desktop:An(In(f,"desktop",m,T),E,"user",g),mobile:An(In(f,"mobile",m,T),N,"user",g)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let s=Ln(e);s.length>0&&(n("workflow:work-center","workflow-work-center","/work-center","/m/work-center"),n("workflow:task","workflow-task","/tasks/:taskId","/m/tasks/:taskId"),n("workflow:instance","workflow-instance","/workflows/:instanceId","/m/workflows/:instanceId"));for(let A of s){if(!["standalone","hidden-handoff"].includes(A.launch.mode))continue;let f=U([A.launch.submission?.create?.requiredCapability,A.launch.submission?.existing?.requiredCapability].filter(E=>!!E));n(`workflow:${A.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",A.code,f.length===1?{capability:f[0]}:f.length>1?{access:{anyOf:f}}:void 0)}let r=o.sort((A,f)=>se(String(A.code),String(f.code))),a=qe(e),i=A=>{let f=A==="mobile"?"/m/":"/",E=a.filter(m=>m.surface==="user"&&!/[:*?#\\\\]/.test(m.path)&&m.path===f).sort((m,g)=>se(m.code,g.code))[0];if(E)return{code:E.code,path:E.path};let N=a.filter(m=>m.surface==="user"&&!/[:*?#\\\\]/.test(m.path)&&(A==="mobile"?m.path.startsWith("/m/"):!m.path.startsWith("/m/"))).sort((m,g)=>se(m.code,g.code))[0];return N?{code:N.code,path:N.path}:{code:A==="mobile"?"application-root-mobile":"application-root",path:f}},l=e.frontend.authentication?{desktop:{routeCode:e.frontend.authentication.surfaces.desktop.routeCode,path:e.frontend.authentication.surfaces.desktop.path},mobile:{routeCode:e.frontend.authentication.surfaces.mobile.routeCode,path:e.frontend.authentication.surfaces.mobile.path}}:{desktop:{routeCode:"application-login",path:"/login"},mobile:{routeCode:"application-login-mobile",path:"/m/login"}},p=Rt(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),_=i("desktop"),d=i("mobile"),c={schemaVersion:Dn,appCode:t,devicePolicy:p,rootEntry:{code:_.code,desktop:_.path,mobile:d.path},authentication:l,routes:r};return{...c,digest:X(c)}}function He(e,t){if(e===void 0)return;let o=R(e,t,32);ts.has(o)||u("NATIVE_ADMIN_ICON_INVALID",t)}function mn(e,t){e!==void 0&&Z(e,t,-1e4,1e4)}function Dt(e,t,o){return e.capability!==void 0&&e.access!==void 0&&u("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:Ae(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:Xe(e.access,`${t}/access`,o)}}function Xe(e,t,o){let n=I(e,t);C(n,["allOf","anyOf"],t,!0);let s=n.allOf===void 0?void 0:U(F(n.allOf,`${t}/allOf`,50).map((a,i)=>Ae(a,`${t}/allOf/${i}`,o))),r=n.anyOf===void 0?void 0:U(F(n.anyOf,`${t}/anyOf`,50).map((a,i)=>Ae(a,`${t}/anyOf/${i}`,o)));return(s?.length||0)+(r?.length||0)===0&&u("NATIVE_ROUTE_ACCESS_EMPTY",t),{...s===void 0?{}:{allOf:s},...r===void 0?{}:{anyOf:r}}}function Ln(e){let t=new Map(Sn(e).map(s=>[String(s.code),s])),o=e.workflows.definitions.map((s,r)=>{let a=`/config/workflows/definitions/${r}`,i=I(s,a);C(i,["version","definition","launch"],a,["detailRouteCode"]);let l=I(i.definition,`${a}/definition`),p=i.detailRouteCode===void 0?void 0:xn(i.detailRouteCode,`${a}/detailRouteCode`);return{code:y(l.code,`${a}/definition/code`),title:R(l.title,`${a}/definition/title`,255),version:Re(i.version,`${a}/version`),launch:js(e,l,i.launch,`${a}/launch`,t),...p?{detailRouteCode:p}:{},definition:l}});return U(o.map(s=>s.code)).map(s=>{let r=o.filter(p=>p.code===s),a=e.workflows.activations.find(p=>p.workflowCode===s)?.definitionVersion,i=r.find(p=>p.version===a)||[...r].sort((p,_)=>_.version-p.version)[0],l=new Set;for(let p of r){let _=I(p.definition.nodes,"/config/workflows/definitions/nodes");for(let d of Object.values(_)){let c=I(d,"/config/workflows/definitions/nodes/*");if(c.kind==="approval")for(let A of F(c.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))l.add(A)}}return{code:s,title:i.title,acceptedCommandDeactivationPolicy:i.definition.acceptedCommandDeactivationPolicy,subject:i.definition.subject,launch:i.launch,...["standalone","hidden-handoff"].includes(i.launch.mode)&&!i.launch.submission?{processOperationCode:`openxiangda.workflow.${s}.submit`}:{},...i.detailRouteCode?{detailRouteCode:i.detailRouteCode}:{},definitionVersions:hn(r.map(p=>p.version)),bindingVersions:hn(e.workflows.bindings.map((p,_)=>{let d=`/config/workflows/bindings/${_}`,c=I(p,d),A=I(c.binding,`${d}/binding`);return{code:y(A.workflowCode,`${d}/binding/workflowCode`),version:Re(c.version,`${d}/version`)}}).filter(p=>p.code===s).map(p=>p.version)),providerCodes:U(e.workflows.providers.map((p,_)=>y(I(p,`/config/workflows/providers/${_}`).code,`/config/workflows/providers/${_}/code`))),allowedOperations:[...l].sort(se),editableParameterCodes:U(e.workflows.editableParameters.map((p,_)=>{let d=`/config/workflows/editableParameters/${_}`,c=I(p,d);return{code:y(c.code,`${d}/code`),workflowCode:y(c.workflowCode,`${d}/workflowCode`)}}).filter(p=>p.workflowCode===s).map(p=>p.code))}})}function kn(e,t){let o=I(e,t);C(o,["mode"],t,["submission"]);let n=R(o.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(n)||u("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:n,...o.submission===void 0?{}:{submission:I(o.submission,`${t}/submission`)}}}function js(e,t,o,n,s){let r=kn(o,n);if(!r.submission)return{mode:r.mode};["standalone","hidden-handoff"].includes(r.mode)||u("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let a=I(r.submission,`${n}/submission`);C(a,["kind"],`${n}/submission`,["create","existing","context"]),v(a.kind,"named-operation",`${n}/submission/kind`);let i=n.endsWith("/launch")?n.slice(0,-7):n,l=I(t.subject,`${i}/definition/subject`),p=G(l.resourceCode,`${i}/definition/subject/resourceCode`),_=e.data.resources.findIndex(O=>O.code===p),d=e.data.resources[_];(_<0||!d)&&u("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${i}/definition/subject/resourceCode`);let c=new Set(I(d.schema,`/config/data/resources/${_}/schema`).fields.map(O=>String(O.code))),A=new Map(e.backend.operations.map(O=>[String(O.code),O])),f=(O,V)=>{let w=`${n}/submission/${V}`,x=I(O,w);C(x,["operationCode","inputs","output"],w);let M=y(x.operationCode,`${w}/operationCode`),ee=A.get(M),B=s.get(M),Ie=B?.platformAccess?.workflow?.codes;(!ee||!B||B.method!=="POST"||!Array.isArray(Ie)||!Ie.includes(t.code))&&u("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",w);let ge=I(ee.requestSchema,`${w}/operation/requestSchema`),q=I(ge.properties,`${w}/operation/requestSchema/properties`),Te=new Set(ge.required===void 0?[]:F(ge.required,`${w}/operation/requestSchema/required`,64)),me=I(x.inputs,`${w}/inputs`),S=Object.entries(me);(!S.length||S.length>64)&&u("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${w}/inputs`);let k=new Set,L=new Map,W={};for(let[j,Y]of S){(!un.test(j)||!Object.prototype.hasOwnProperty.call(q,j))&&u("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${w}/inputs/${j}`);let Ce=`${w}/inputs/${j}`,Ze=I(Y,Ce),Ne=R(Ze.source,`${Ce}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(Ne)||u("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",Ce),C(Ze,["source"],Ce,Ne==="field"?["fieldCode"]:!1),L.set(Ne,(L.get(Ne)||0)+1),Ne==="field"){let xe=z(Ze.fieldCode,`${Ce}/fieldCode`);(k.has(xe)||!c.has(xe))&&u("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${Ce}/fieldCode`),k.add(xe),W[j]={source:Ne,fieldCode:xe}}else W[j]={source:Ne}}([...Te].some(j=>!(j in me))||(L.get("idempotency-key")||0)!==1||!S.some(([j,Y])=>I(Y,`${w}/inputs/${j}`).source==="idempotency-key"&&Te.has(j))||V==="create"&&((L.get("subject-id")||0)>0||(L.get("subject-revision")||0)>0)||V==="existing"&&((L.get("subject-id")||0)!==1||(L.get("subject-revision")||0)!==1))&&u("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${w}/inputs`);let J=I(x.output,`${w}/output`);C(J,["subjectId"],`${w}/output`,["subjectRevision","processCommand"]);let de=I(I(ee.responseSchema,`${w}/operation/responseSchema`).properties,`${w}/operation/responseSchema/properties`);for(let j of["subjectId","subjectRevision","processCommand"]){if(J[j]===void 0)continue;let Y=R(J[j],`${w}/output/${j}`,128);(!un.test(Y)||!Object.prototype.hasOwnProperty.call(de,Y))&&u("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${w}/output/${j}`)}return{operationCode:M,method:"POST",path:B.path,requiredCapability:B.requiredCapability,requestSchemaDigest:B.requestSchemaDigest,responseSchemaDigest:B.responseSchemaDigest,inputs:W,output:{...J},fieldCodes:k}},E=a.create===void 0?void 0:f(a.create,"create"),N=a.existing===void 0?void 0:f(a.existing,"existing");!E&&!N&&u("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let m=new Set([...E?.fieldCodes||[],...N?.fieldCodes||[]]),g=a.context===void 0?[]:$(a.context,`${n}/submission/context`,16),T=new Set,D=g.map((O,V)=>{let w=`${n}/submission/context/${V}`,x=I(O,w);C(x,["queryParameter","fieldCode"],w);let M=R(x.queryParameter,`${w}/queryParameter`,64),ee=z(x.fieldCode,`${w}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(M)||T.has(M)||!m.has(ee))&&u("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",w),T.add(M),{queryParameter:M,fieldCode:ee}}),b=O=>{let{fieldCodes:V,...w}=O;return w};return{mode:r.mode,submission:{kind:"named-operation",...E?{create:b(E)}:{},...N?{existing:b(N)}:{},context:D}}}function xn(e,t){let o=I(e,t);C(o,["desktop","mobile"],t);let n=y(o.desktop,`${t}/desktop`),s=y(o.mobile,`${t}/mobile`);return n===s&&u("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:s}}function Ws(e,t){let o=new Set(t.map(_=>_.code)),n=new Map;e.data.resources.forEach((_,d)=>{let c=`/config/data/resources/${d}`,A=I(_,c);for(let[N,m]of Object.entries(A.fieldPolicies||{})){if(!Se(N))continue;let g=`${c}/fieldPolicies/${N}/read`,T=I(m,`${c}/fieldPolicies/${N}`);for(let D of F(T.read||[],g,2e3))o.has(D)||u("NATIVE_CAPABILITY_REFERENCE_MISSING",g)}if(((A.surface===void 0?{}:I(A.surface,`${c}/surface`)).mutationOwner||"native")==="native")return;let E=I(A.capabilities,`${c}/capabilities`);for(let N of["create","update","delete"])n.set(String(E[N]),N)});let s=new Set;for(let[_,d]of e.authz.roles.entries()){let c=`/config/authz/roles/${_}`,A=I(d,c);C(A,["code","name","description","capabilities"],c,!0);let f=y(A.code,`${c}/code`);s.has(f)&&u("NATIVE_ROLE_DUPLICATE",`${c}/code`),s.add(f),R(A.name,`${c}/name`,255);let E=F(A.capabilities,`${c}/capabilities`,2e3);for(let[N,m]of E.entries())n.has(m)&&u("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${c}/capabilities/${N}`,{operation:n.get(m)}),o.has(m)||u("NATIVE_CAPABILITY_REFERENCE_MISSING",`${c}/capabilities`)}let r=e.authz.authenticatedUserRoleCode===void 0?"":y(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");r&&!s.has(r)&&u("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let a=new Set,i=0;for(let[_,d]of e.perspectives.entries()){let c=`/config/perspectives/${_}`,A=I(d,c);C(A,["code","name","description","roleCodes","capabilityCodes","default"],c,!0);let f=y(A.code,`${c}/code`);a.has(f)&&u("NATIVE_PERSPECTIVE_DUPLICATE",`${c}/code`),a.add(f),R(A.name,`${c}/name`,255);let E=F(A.roleCodes,`${c}/roleCodes`,20);E.length<1&&u("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${c}/roleCodes`),E.forEach((g,T)=>{s.has(g)||u("NATIVE_PERSPECTIVE_ROLE_MISSING",`${c}/roleCodes/${T}`)});let N=U(e.authz.roles.filter(g=>E.includes(g.code)).flatMap(g=>g.capabilities)),m=F(A.capabilityCodes,`${c}/capabilityCodes`,2e3);H(N)!==H(m)&&u("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${c}/capabilityCodes`),A.default===!0?i+=1:A.default!==void 0&&u("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${c}/default`)}i>1&&u("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[_,d]of e.backend.operations.entries()){let c=I(d,`/config/backend/operations/${_}`);o.has(c.capability)||u("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${_}/capability`)}let l=new Set,p=new Set;for(let[_,d]of e.frontend.routes.entries()){let c=`/config/frontend/routes/${_}`,A=I(d,c),f=y(A.code,`${c}/code`);l.has(f)&&u("NATIVE_ROUTE_DUPLICATE",`${c}/code`),l.add(f);let E=ie(A.path,`${c}/path`);p.has(E)&&u("NATIVE_ROUTE_PATH_DUPLICATE",`${c}/path`),p.add(E);let N=Dt(A,c,e.appCode);N.capability&&!o.has(N.capability)&&u("NATIVE_CAPABILITY_REFERENCE_MISSING",`${c}/capability`);let m=A.access===void 0?void 0:I(A.access,`${c}/access`);for(let g of["allOf","anyOf"]){let T=m?.[g]===void 0?[]:$(m[g],`${c}/access/${g}`,50);for(let[D,b]of T.entries()){let O=Ae(b,`${c}/access/${g}/${D}`,e.appCode);o.has(O)||u("NATIVE_CAPABILITY_REFERENCE_MISSING",`${c}/access/${g}/${D}`)}}}if(e.frontend.admin.access!==void 0){let _=Xe(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let d of["allOf","anyOf"])for(let[c,A]of(_[d]||[]).entries())o.has(A)||u("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${d}/${c}`)}for(let[_,d]of e.frontend.routes.entries()){let c=I(d,`/config/frontend/routes/${_}`);c.parentCode&&!l.has(c.parentCode)&&u("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${_}/parentCode`)}}function Bs(e){let t=new Set(e.authz.roles.map(p=>String(p.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":y(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(p=>[String(p.code),{valueType:p.valueType==="uuid"?"uuid":"string",...p.valueSource?.resourceCode?{valueSourceResourceCode:String(p.valueSource.resourceCode)}:{}}])),s=new Set(n.keys()),r=new Map(e.data.resources.map((p,_)=>{let d=ke(p,`/config/data/resources/${_}`,e.appCode);return[d.code,new Map(d.schema.fields.map(c=>[String(c.code),c]))]}));for(let[p,_]of e.authz.scopeDimensions.entries()){let d=`/config/authz/scopeDimensions/${p}`,c=I(_,d);if(C(c,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],d,!0),c.valueSource===void 0)continue;let A=I(c.valueSource,`${d}/valueSource`);C(A,["kind","resourceCode","labelField","enabledField"],`${d}/valueSource`,!0),A.kind!=="native_resource"&&u("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${d}/valueSource/kind`),c.valueType!=="uuid"&&u("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${d}/valueType`);let f=G(A.resourceCode,`${d}/valueSource/resourceCode`),E=r.get(f);E||u("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${d}/valueSource/resourceCode`);let N=z(A.labelField,`${d}/valueSource/labelField`);if(["text.short","text.long"].includes(String(E.get(N)?.type||""))||u("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${d}/valueSource/labelField`),A.enabledField!==void 0){let m=z(A.enabledField,`${d}/valueSource/enabledField`);E.get(m)?.type!=="boolean"&&u("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${d}/valueSource/enabledField`)}}let a=new Set,i=new Set;for(let[p,_]of e.authz.scopeSources.entries()){let d=`/config/authz/scopeSources/${p}`,c=I(_,d);C(c,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],d,!0);let A=y(c.code,`${d}/code`);a.has(A)&&u("NATIVE_SCOPE_SOURCE_DUPLICATE",`${d}/code`),a.add(A),R(c.name,`${d}/name`,255);let f=G(c.resourceCode,`${d}/resourceCode`),E=r.get(f);E||u("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${d}/resourceCode`);let N=I(c.subject,`${d}/subject`),m=R(N.type,`${d}/subject/type`,32);C(N,m==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${d}/subject`),["user","role_membership"].includes(m)||u("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${d}/subject/type`);let g=Ve(N.userIdField,E);At(g)||u("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${d}/subject/userIdField`),m==="role_membership"&&!t.has(String(N.roleCode))&&u("NATIVE_ROLE_REFERENCE_MISSING",`${d}/subject/roleCode`);let T=new Set;for(let[D,b]of $(c.grants,`${d}/grants`,100).entries()){let O=`${d}/grants/${D}`,V=I(b,O);C(V,["dimensionCode","valueField","parentValueField"],O,!0);let w=y(V.dimensionCode,`${O}/dimensionCode`);(!s.has(w)||T.has(w))&&u("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${O}/dimensionCode`),T.add(w),c.failureMode==="last_known_good"&&i.add(w);for(let x of["valueField","parentValueField"]){if(V[x]===void 0)continue;let M=Ve(V[x],E);en(M,n.get(w),r)||u("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${O}/${x}`)}}T.size===0&&u("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${d}/grants`),["strict","last_known_good"].includes(c.failureMode)||u("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${d}/failureMode`);for(let D of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(c[D]===void 0)continue;let b=z(c[D],`${d}/${D}`);E.has(b)||u("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${d}/${D}`)}}Gs(e,t,r,o);let l=new Set;for(let[p,_]of e.authz.dataPolicies.entries()){let d=`/config/authz/dataPolicies/${p}`,c=I(_,d);C(c,["code","name","resourceCode","unrestrictedRoleCodes","operations","matchMode","rules","readExpression","writeBoundary"],d,!0);let A=y(c.code,`${d}/code`);l.has(A)&&u("NATIVE_DATA_POLICY_DUPLICATE",`${d}/code`),l.add(A);let f=c.readExpression!==void 0,E=F(c.operations||[],`${d}/operations`,4);c.operations!==void 0&&(E.length===0||E.some(b=>!["read","create","update","delete"].includes(b)))&&u("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${d}/operations`),["AND","OR"].includes(c.matchMode)||u("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${d}/matchMode`),f&&c.operations!==void 0&&u("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${d}/operations`);let N=e.data.resources.find(b=>b.dataPolicyCode===A),m=c.resourceCode||N?.code,g=m?r.get(G(m,`${d}/resourceCode`)):void 0;f&&!g&&u("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${d}/resourceCode`);let T=F(c.unrestrictedRoleCodes||[],`${d}/unrestrictedRoleCodes`,100);c.unrestrictedRoleCodes!==void 0&&T.length===0&&u("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${d}/unrestrictedRoleCodes`);for(let b of T)t.has(b)||u("NATIVE_ROLE_REFERENCE_MISSING",`${d}/unrestrictedRoleCodes`);let D;try{let b=$(c.rules,`${d}/rules`,100).map((O,V)=>({rule:I(O,`${d}/rules/${V}`),pointer:`${d}/rules/${V}`}));b.length===0?(!f||c.matchMode!=="AND"||c.writeBoundary!=="capability_only")&&u("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",d):c.writeBoundary!==void 0&&u("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${d}/writeBoundary`),D=[...b],f&&(D.push(...ze(c.readExpression,`${d}/readExpression`)),cn(c.readExpression,`${d}/readExpression`))}catch(b){throw b instanceof Fe&&u(b.code,b.pointer),b}for(let{rule:b,pointer:O}of D){C(b,["subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],O,!0);let V=z(b.field,`${O}/field`),w=g?.get(V);f&&!w&&u("NATIVE_DATA_POLICY_FIELD_MISSING",`${O}/field`);for(let q of F(b.roleCodes||[],`${O}/roleCodes`,100))t.has(q)||u("NATIVE_ROLE_REFERENCE_MISSING",`${O}/roleCodes`);let x=String(b.operator||""),M=b.operand==="db_now",ee=["is_null","is_not_null"].includes(x),B=["eq","not_eq","in","not_in"].includes(x),Ie=!M&&(b.operator!==void 0||b.value!==void 0);if([b.subject==="current_user"?"current_user":"",typeof b.dimensionCode=="string"?"dimension":"",typeof b.relationCode=="string"?"relationship":"",Ie?"constant":"",M?"db_now":""].filter(Boolean).length!==1&&u("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",O),b.subject!==void 0&&b.subject!=="current_user"&&u("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${O}/subject`),Ie){if(!B&&!ee&&u("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${O}/operator`),["in","not_in"].includes(x)){let q=$(b.value,`${O}/value`,100).map((Te,me)=>R(Te,`${O}/value/${me}`,2048));(q.length===0||new Set(q).size!==q.length)&&u("NATIVE_DATA_POLICY_VALUE_INVALID",`${O}/value`)}else["eq","not_eq"].includes(x)?R(b.value,`${O}/value`,2048):(b.value!==void 0||b.operand!==void 0)&&u("NATIVE_DATA_POLICY_VALUE_INVALID",`${O}/value`);for(let q of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])b[q]!==void 0&&u("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${O}/${q}`)}if(M){(!["lt","lte","gt","gte"].includes(x)||b.value!==void 0||w?.type!=="datetime")&&u("NATIVE_DATA_POLICY_DB_NOW_INVALID",O);for(let q of["operation","valuePath","emptyMatchesAll","resourceCode","value"])b[q]!==void 0&&u("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${O}/${q}`)}b.dimensionCode&&!s.has(b.dimensionCode)&&u("NATIVE_SCOPE_DIMENSION_MISSING",`${O}/dimensionCode`),i.has(String(b.dimensionCode||""))&&b.operation!=="read"&&u("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${O}/operation`)}}for(let[p,_]of e.data.resources.entries()){let d=I(_,`/config/data/resources/${p}`);d.dataPolicyCode&&!l.has(d.dataPolicyCode)&&u("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${p}/dataPolicyCode`)}}function Js(e){try{kt(e.data.resources,"/config/data/resources")}catch(t){throw t instanceof ue&&u(t.code,t.pointer),t}}function Gs(e,t,o,n){let s=new Set;for(let[r,a]of e.authz.roleMembershipSources.entries()){let i=`/config/authz/roleMembershipSources/${r}`,l=I(a,i);C(l,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],i,!0);let p=y(l.code,`${i}/code`);p.length>100&&u("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${i}/code`),s.has(p)&&u("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${i}/code`),s.add(p),R(l.name,`${i}/name`,255);let _=Nn(l.resourceCode,`${i}/resourceCode`,o);gn(l.userIdField,`${i}/userIdField`,_),t.has(String(l.roleCode||""))||u("NATIVE_ROLE_REFERENCE_MISSING",`${i}/roleCode`),n&&l.roleCode===n&&u("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${i}/roleCode`),Tn(l,i,_)}for(let[r,a]of e.authz.relationshipGrantSources.entries()){let i=`/config/authz/relationshipGrantSources/${r}`,l=I(a,i);C(l,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],i,!0);let p=y(l.code,`${i}/code`);p.length>100&&u("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${i}/code`),s.has(p)&&u("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${i}/code`),s.add(p),R(l.name,`${i}/name`,255);let _=Nn(l.resourceCode,`${i}/resourceCode`,o),d=I(l.subject,`${i}/subject`),c=R(d.type,`${i}/subject/type`,32);C(d,c==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${i}/subject`),["user","role_membership"].includes(c)||u("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${i}/subject/type`),gn(d.userIdField,`${i}/subject/userIdField`,_),c==="role_membership"&&!t.has(String(d.roleCode||""))&&u("NATIVE_ROLE_REFERENCE_MISSING",`${i}/subject/roleCode`),y(l.relationCode,`${i}/relationCode`);let A=G(l.targetResourceCode,`${i}/targetResourceCode`);o.has(A)||u("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${i}/targetResourceCode`);let f=Ve(l.resourceIdField,_),E=f?.field.type==="resource-ref.single"&&f.valuePath==="value"&&f.field.source?.resourceCode===A;(l.resourceIdField==="id"?A!==String(l.resourceCode):!E)&&u("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${i}/resourceIdField`);let N=F(l.operations,`${i}/operations`,20);(N.length===0||N.some(m=>m.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(m)))&&u("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${i}/operations`),Tn(l,i,_)}}function Nn(e,t,o){let n=G(e,t),s=o.get(n);return s||u("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),s}function gn(e,t,o){let n=Ve(e,o);At(n)||u("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function Tn(e,t,o){if(e.failureMode!=="strict"&&u("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=z(e.enabledField,`${t}/enabledField`);o.get(n)?.type!=="boolean"&&u("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let n of["effectiveFromField","effectiveToField"]){if(e[n]===void 0)continue;let s=z(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(s)?.type))||u("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function zs(e){let t=new Set,o=new Set;e.forEach((n,s)=>{let r=`/config/backend/secrets/${s}`,a=I(n,r);C(a,["name","env","description","required","exposure"],r,!0);let i=R(a.name,`${r}/name`,128),l=R(a.env,`${r}/env`,128);Yo.test(i)||u("NATIVE_SECRET_NAME_INVALID",`${r}/name`),(!Ho.test(l)||l.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(l))&&u("NATIVE_SECRET_ENV_INVALID",`${r}/env`),t.has(i)&&u("NATIVE_SECRET_NAME_DUPLICATE",`${r}/name`),o.has(l)&&u("NATIVE_SECRET_ENV_DUPLICATE",`${r}/env`),t.add(i),o.add(l),v(a.exposure,"active_only",`${r}/exposure`),a.required!==void 0&&De(a.required,`${r}/required`),a.description!==void 0&&St(a.description,`${r}/description`,2e3)})}function Ys(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(c=>[String(c.code),c])),s=new Map(e.frontend.routes.map((c,A)=>{let f=I(c,`/config/frontend/routes/${A}`);return[y(f.code,`/config/frontend/routes/${A}/code`),f]}));for(let[c,A]of e.workflows.definitions.entries()){let f=`/config/workflows/definitions/${c}`,E=I(A,f);if(C(E,["version","definition","launch"],f,["detailRouteCode"]),kn(E.launch,`${f}/launch`),E.detailRouteCode!==void 0){let T=xn(E.detailRouteCode,`${f}/detailRouteCode`);for(let[D,b,O]of[["desktop",T.desktop,"admin"],["mobile",T.mobile,"user"]]){let V=`${f}/detailRouteCode/${D}`,w=s.get(b);w||u("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",V),w.surface!==O&&u("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",V);let x=ie(w.path,V),M=[...x.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(ee=>ee[1]);(x.includes("*")||M.length!==1||M[0]!=="instanceId")&&u("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",V)}}let N=I(E.definition,`${f}/definition`),m=`${N.code}:${Re(E.version,`${f}/version`)}`;t.has(m)&&u("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",f),t.add(m),Ks(N,`${f}/definition`),Hs(N.subject,n,`${f}/definition/subject`);let g=sn(N,{appCode:e.appCode,capabilities:e.authz.capabilities.map(T=>T.code),fields:new Map((n.get(N.subject.resourceCode)?.schema.fields||[]).map(T=>[T.code,T]))});g.length&&u("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${f}/definition/instanceCommands`,{errors:g}),N.title===N.code&&u("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${f}/definition/title`),o.set(m,N)}let r=new Set,a=new Map;for(let[c,A]of e.workflows.bindings.entries()){let f=I(A,`/config/workflows/bindings/${c}`),E=I(f.binding,`/config/workflows/bindings/${c}/binding`),N=`${E.workflowCode}:${Re(f.version,`/config/workflows/bindings/${c}/version`)}`;r.has(N)&&u("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${c}`),r.add(N),qs(E,`/config/workflows/bindings/${c}/binding`),a.set(N,E)}let i=new Set,l=new Map;for(let[c,A]of e.workflows.activations.entries()){let f=`/config/workflows/activations/${c}`,E=I(A,f);C(E,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],f,["environmentKey"]);let N=y(E.workflowCode,`${f}/workflowCode`);i.has(N)&&u("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",f),i.add(N);let m=`${N}:${Re(E.definitionVersion,`${f}/definitionVersion`)}`,g=`${N}:${Re(E.bindingVersion,`${f}/bindingVersion`)}`;t.has(m)||u("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${f}/definitionVersion`),r.has(g)||u("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${f}/bindingVersion`);let T=o.get(m),D=a.get(g);(!["finish-pinned","cancel-on-deactivate"].includes(E.acceptedCommandDeactivationPolicy)||E.acceptedCommandDeactivationPolicy!==T.acceptedCommandDeactivationPolicy)&&u("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${f}/acceptedCommandDeactivationPolicy`),Xs(T,D,`/config/workflows/activations/${c}`),l.set(N,D)}let p=new Set;e.workflows.providers.forEach((c,A)=>{let f=`/config/workflows/providers/${A}`,E=I(c,f);C(E,["code","endpointPath","timeoutMs"],f,!0);let N=y(E.code,`${f}/code`);p.has(N)&&u("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${f}/code`),p.add(N),ie(E.endpointPath,`${f}/endpointPath`),E.timeoutMs!==void 0&&Z(E.timeoutMs,`${f}/timeoutMs`,100,1e4)});for(let[c,A]of l.entries())for(let[f,E]of Object.entries(I(A.bindings,"/config/workflows/bindings/*/binding/bindings"))){let N=I(E,`/config/workflows/${c}/bindings/${f}`);N.provider==="application_provider"&&!p.has(N.providerCode)&&u("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${c}/bindings/${f}/providerCode`)}let _=new Set(e.authz.roles.map(c=>c.code)),d=new Set;e.workflows.editableParameters.forEach((c,A)=>{let f=`/config/workflows/editableParameters/${A}`,E=I(c,f);C(E,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],f,!0);let N=y(E.code,`${f}/code`);d.has(N)&&u("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${f}/code`),d.add(N);let m=Qe(E.workflowCode,`${f}/workflowCode`),g=yt(E.bindingKey,`${f}/bindingKey`),T=l.get(m);(!T||!I(T.bindings,`${f}/bindingKey`)[g])&&u("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${f}/bindingKey`),R(E.label,`${f}/label`,255),["role_code","user_ids","provider_code"].includes(E.valueType)||u("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${f}/valueType`);for(let D of F(E.allowedRoleCodes||[],`${f}/allowedRoleCodes`,100))_.has(D)||u("NATIVE_ROLE_REFERENCE_MISSING",`${f}/allowedRoleCodes`);for(let D of F(E.allowedProviderCodes||[],`${f}/allowedProviderCodes`,100))p.has(D)||u("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${f}/allowedProviderCodes`);E.required!==void 0&&De(E.required,`${f}/required`),E.maxItems!==void 0&&Z(E.maxItems,`${f}/maxItems`,1,200)})}function Hs(e,t,o){let n=I(e,o);C(n,["resourceCode","factProjection"],o,["summaryFields"]);let s=G(n.resourceCode,`${o}/resourceCode`),r=t.get(s);r||u("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let a=new Set($(I(r.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((p,_)=>z(I(p,`${o}/resourceCode/${_}`).code,`${o}/resourceCode/${_}`))),i=I(n.factProjection,`${o}/factProjection`),l=Object.entries(i);(l.length<1||l.length>64)&&u("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[p,_]of l){Xo.test(p)||u("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${p}`);let d=z(_,`${o}/factProjection/${p}`);a.has(d)||u("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${p}`)}if(n.summaryFields!==void 0){let p=F(n.summaryFields,`${o}/summaryFields`,Qo).map((f,E)=>z(f,`${o}/summaryFields/${E}`)),_=t.get(s),d=_.surface&&typeof _.surface=="object"&&!Array.isArray(_.surface)?_.surface:{},c=d.fields&&typeof d.fields=="object"&&!Array.isArray(d.fields)?d.fields:{},A=new Map($(I(_.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((f,E)=>{let N=I(f,`${o}/resourceCode/${E}`);return[String(N.code),N]}));for(let[f,E]of p.entries()){let N=A.get(E),m=c[E],g=String(N?.type||""),T=N?.maxLength;(!N||N.system===!0||m&&typeof m=="object"&&!Array.isArray(m)&&m.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(E)||!es.has(g)||g==="text.long"&&typeof T=="number"&&Number.isFinite(T)&&T>Zo)&&u("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${f}`)}}}function Ks(e,t){C(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands"]),v(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),Qe(e.code,`${t}/code`),R(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||u("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=I(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&u("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let s=R(e.startAt,`${t}/startAt`,128);o[s]||u("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let r=new Map;for(let[p,_]of Object.entries(o)){let d=`${t}/nodes/${p}`,c=I(_,d);v(c.id,p,`${d}/id`),["approval","condition","end"].includes(c.kind)||u("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${d}/kind`);let A=[];if(c.kind==="approval"){yt(c.binding,`${d}/binding`),["single","any","all","sequence"].includes(c.mode)||u("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${d}/mode`),A.push(R(c.onApprove,`${d}/onApprove`,128),R(c.onReject,`${d}/onReject`,128));for(let f of F(c.returnTargets||[],`${d}/returnTargets`,200))o[f]||u("NATIVE_WORKFLOW_TARGET_MISSING",`${d}/returnTargets`);for(let f of F(c.allowedOperations||[],`${d}/allowedOperations`,20))ns.has(f)||u("NATIVE_WORKFLOW_OPERATION_INVALID",`${d}/allowedOperations`)}else if(c.kind==="condition"){let f=$(c.branches,`${d}/branches`,100);f.length===0&&u("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${d}/branches`),f.forEach((E,N)=>{let m=I(E,`${d}/branches/${N}`);ve(m.when,`${d}/branches/${N}/when`,0),A.push(R(m.target,`${d}/branches/${N}/target`,128))}),A.push(R(c.otherwise,`${d}/otherwise`,128))}else R(c.outcome,`${d}/outcome`,128);for(let f of A)o[f]||u("NATIVE_WORKFLOW_TARGET_MISSING",d);r.set(p,A)}let a=new Set,i=new Set,l=p=>{if(i.has(p)&&u("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${p}`),!a.has(p)){a.add(p),i.add(p);for(let _ of r.get(p)||[])l(_);i.delete(p)}};l(s),a.size!==n.length&&u("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function ve(e,t,o){o>20&&u("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=I(e,t),s=R(n.op,`${t}/op`,16);if(s!=="literal"){if(s==="path"){let r=R(n.path,`${t}/path`,255);/^[A-Za-z][A-Za-z0-9_.]{0,254}$/.test(r)||u("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(s)){ve(n.left,`${t}/left`,o+1),ve(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(s)){let r=$(n.values,`${t}/values`,100);r.length===0&&u("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),r.forEach((a,i)=>ve(a,`${t}/values/${i}`,o+1));return}if(["not","exists"].includes(s)){ve(n.value,`${t}/value`,o+1);return}u("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function qs(e,t){v(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),Qe(e.workflowCode,`${t}/workflowCode`);let o=I(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&u("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,s]of Object.entries(o)){yt(n,`${t}/bindings/${n}`);let r=I(s,`${t}/bindings/${n}`),a=R(r.provider,`${t}/bindings/${n}/provider`,64);["fixed_users","initiator","input_users","form_field_users","department_supervisor","app_role","app_role_in_scope","business_relation","previous_node_actor","initiator_select","application_provider"].includes(a)||u("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${n}/provider`),a==="fixed_users"&&$(r.users,`${t}/bindings/${n}/users`,200).length===0&&u("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),["input_users","form_field_users"].includes(a)&&R(r.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(a)&&y(r.roleCode,`${t}/bindings/${n}/roleCode`),a==="department_supervisor"&&R(r.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),a==="application_provider"&&y(r.providerCode,`${t}/bindings/${n}/providerCode`)}}function Xs(e,t,o){v(t.workflowCode,e.code,`${o}/workflowCode`);let n=I(t.bindings,`${o}/bindings`);for(let[s,r]of Object.entries(I(e.nodes,`${o}/nodes`))){let a=I(r,`${o}/nodes/${s}`);a.kind==="approval"&&!n[a.binding]&&u("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${s}/binding`)}}function Qs(e,t,o){let n=I(t.routeManifest,"/contracts/routeManifest"),s=I(e.routeManifest,"/contracts/routeManifest"),r=new Map;for(let _ of $(o.data?.resources,"/config/data/resources",100)){let d=I(_,"/config/data/resources");r.set(String(d.code||""),d)}let a=new Set($(s.routes,"/contracts/routeManifest/routes",1e3).map(_=>String(I(_,"/contracts/routeManifest/routes").code||""))),i=[];for(let _ of $(n.routes,"/contracts/routeManifest/routes",1e3)){let d=I(_,"/contracts/routeManifest/routes"),c=String(d.kind||"");if(c!=="resource-records"&&c!=="resource-submit")continue;let A=String(d.resourceCode||""),f=r.get(A);f||u("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let N=`user.${A}.${c==="resource-records"?"records":"submit"}`;v(String(d.code||""),N,"/contracts/routeManifest/routes/code");let m=c==="resource-records"?"read":"create",g=String(I(f.capabilities,"/config/data/resources/capabilities")[m]||"");for(let T of["desktop","mobile"]){let D=I(d[T],`/contracts/routeManifest/routes/${T}`),b=T==="mobile"?"/m/my/":"/my/",O=c==="resource-records"?`${b}${A}`:`${b}${A}/submit`;v(String(D.path||""),O,`/contracts/routeManifest/routes/${T}/path`),v(String(D.capability||""),g,`/contracts/routeManifest/routes/${T}/capability`),v(String(D.routeCode||""),`${N}.${T}`,`/contracts/routeManifest/routes/${T}/routeCode`)}(a.has(N)||i.some(T=>String(T.code)===N))&&u("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),i.push(d)}if(!i.length)return;s.routes=$([...s.routes,...i],"/contracts/routeManifest/routes",1e3).sort((_,d)=>se(String(I(_,"x").code||""),String(I(d,"x").code||"")));let l=String(I(n.rootEntry,"x").code||"");if(i.find(_=>String(_.code)===l&&_.kind==="resource-records")){let _=I(n.rootEntry,"x");s.rootEntry={code:l,desktop:String(_.desktop||""),mobile:String(_.mobile||"")}}s.digest=X({schemaVersion:s.schemaVersion,appCode:s.appCode,devicePolicy:s.devicePolicy,rootEntry:s.rootEntry,authentication:s.authentication,routes:s.routes})}function ke(e,t,o){let n=I(e,t);C(n,["schemaVersion","appCode","code","name","schema","surface","invariants","capabilities","dataPolicyCode","fieldPolicies"],t,!0),v(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),v(n.appCode,o,`${t}/appCode`);let s=G(n.code,`${t}/code`),r=R(n.name,`${t}/name`,255),a=I(n.schema,`${t}/schema`);C(a,["fields"],`${t}/schema`);let i,l;try{i=st(a.fields,`${t}/schema/fields`),l=xt(n.invariants,i,`${t}/invariants`),ft(n.surface,i,`${t}/surface`)}catch(c){throw c instanceof ue&&u(c.code,c.pointer),c}let p=new Set(i.map(c=>c.code)),_=I(n.capabilities,`${t}/capabilities`);C(_,["read","create","update","delete"],`${t}/capabilities`);let d=I(n.fieldPolicies,`${t}/fieldPolicies`);for(let[c,A]of Object.entries(d)){!p.has(c)&&!Se(c)&&u("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${c}`);let f=`${t}/fieldPolicies/${c}`,E=I(A,f);Se(c)&&(C(E,["read"],f,!0),(!Array.isArray(E.read)||E.read.length>20||E.read.some(N=>typeof N!="string"||!N.trim())||new Set(E.read).size!==E.read.length)&&u("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${f}/read`)),C(E,["read","create","update","mask"],f,!0),E.mask!==void 0&&!["omit","null"].includes(E.mask)&&u("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${f}/mask`)}return{...n,code:s,name:r,schema:{fields:i},...n.invariants===void 0?{}:{invariants:l},capabilities:_,fieldPolicies:d}}function Un(e){return[{code:`app:${e}:directory:read`,kind:"platform",name:"\u8BFB\u53D6\u53D7\u9650\u7EC4\u7EC7\u76EE\u5F55",source:"platform"},...[["app:role:read","\u67E5\u770B\u89D2\u8272\u4E0E\u6388\u6743"],["app:role:define","\u5B9A\u4E49\u624B\u5DE5\u89D2\u8272"],["app:role:assign","\u5206\u914D\u89D2\u8272\u6210\u5458"],["app:role:grant-capability","\u6388\u4E88\u89D2\u8272\u80FD\u529B"],["app:scope-grant:manage","\u7BA1\u7406\u6570\u636E\u8303\u56F4"],["app:super-admin:manage","\u7BA1\u7406\u5E94\u7528\u6700\u9AD8\u7BA1\u7406\u5458"]].map(([t,o])=>({code:t,kind:"platform",name:o,source:"platform"}))]}function Cn(e,t,o,n){let s=e.toString("utf8"),r;try{r=JSON.parse(s)}catch{u(o,t)}let a=I(r,t);return H(a)!==s&&u(n,t),a}function bn(e,t){let o=0,n=(s,r,a)=>{if(o+=1,o>rs&&u("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",r),a>is&&u("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",r),typeof s=="string"){Buffer.byteLength(s)>gt&&u("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",r);return}if(Array.isArray(s)){s.forEach((i,l)=>n(i,`${r}/${l}`,a+1));return}if(!(!s||typeof s!="object"))for(let[i,l]of Object.entries(s))["__proto__","prototype","constructor"].includes(i)&&u("NATIVE_ARTIFACT_DANGEROUS_KEY",`${r}/${i}`),Zs(i)&&u("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${r}/${i}`),n(l,`${r}/${i}`,a+1)};n(e,t,0)}function Zs(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function he(e){return{value:e,digest:X(e)}}function On(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&u("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let s=Buffer.isBuffer(e)?e:Buffer.from(e);return s.byteLength===0&&u("NATIVE_ARTIFACT_EMPTY",o),s.byteLength>t&&u(n,o),s}function $n(e,t,o,n){let s=Ke.createHash("sha256").update(e).digest("hex");Ke.timingSafeEqual(Buffer.from(s),Buffer.from(t))||u(n,o)}function I(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&u("NATIVE_OBJECT_REQUIRED",t),e}function $(e,t,o){return Array.isArray(e)||u("NATIVE_ARRAY_REQUIRED",t),e.length>o&&u("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function F(e,t,o){let n=$(e,t,o).map((s,r)=>R(s,`${t}/${r}`,255));return new Set(n).size!==n.length&&u("NATIVE_ARRAY_DUPLICATE",t),n}function R(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&u("NATIVE_STRING_INVALID",t),e}function St(e,t,o){return(typeof e!="string"||e.length>o)&&u("NATIVE_STRING_INVALID",t),e}function y(e,t){let o=R(e,t,128);return Bo.test(o)||u("NATIVE_CODE_INVALID",t),o}function G(e,t){let o=R(e,t,64);return Go.test(o)||u("NATIVE_RESOURCE_CODE_INVALID",t),o}function z(e,t){let o=R(e,t,63);return zo.test(o)||u("NATIVE_FIELD_CODE_INVALID",t),o}function Qe(e,t){let o=R(e,t,128);return Ko.test(o)||u("NATIVE_WORKFLOW_CODE_INVALID",t),o}function yt(e,t){let o=R(e,t,128);return qo.test(o)||u("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function Ae(e,t,o){let n=R(e,t,255);return Wo.test(n)||u("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!Un(o).some(s=>s.code===n)&&u("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function ie(e,t){let o=R(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&u("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function Re(e,t){return(!Number.isInteger(e)||Number(e)<1)&&u("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function Z(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&u("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function De(e,t){return typeof e!="boolean"&&u("NATIVE_BOOLEAN_REQUIRED",t),e}function $t(e,t){let o=R(e,t,64).toLowerCase();return Mo.test(o)||u("NATIVE_DIGEST_INVALID",t),o}function v(e,t,o){e!==t&&u("NATIVE_VALUE_MISMATCH",o)}function C(e,t,o,n=!1){let s=new Set([...t,...Array.isArray(n)?n:[]]);for(let r of Object.keys(e))s.has(r)||u("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`);if(n!==!0)for(let r of t)Object.prototype.hasOwnProperty.call(e,r)||u("NATIVE_PROPERTY_REQUIRED",`${o}/${r}`)}function ne(e,t){return[...e].sort((o,n)=>se(t(o),t(n)))}function U(e){return[...new Set(e)].sort(se)}function hn(e){return[...new Set(e)].sort((t,o)=>t-o)}function se(e,t){return e===t?0:e<t?-1:1}function Mn(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>Mn(t))),e}function ht(e,t,o){if(Nt(e,t))return o;if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length);for(let s=0;s<n;s+=1)if(!Nt(e[s],t[s]))return ht(e[s],t[s],`${o}/${s}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=U([...Object.keys(e),...Object.keys(t)]);for(let s of n){let r=e[s],a=t[s];if(!Nt(r,a))return ht(r,a,`${o}/${s}`)}}return o}function Nt(e,t){return e===void 0||t===void 0?e===t:H(e)===H(t)}function u(e,t,o={}){throw new bt(e,t,o)}var cr="e9986e0005e48fcaec6df2468c5763dbf9444cf919bd8a276b602738df5dd34c";export{Ut as DATA_AUDIT_METADATA_FIELDS,Tt as DATA_EVENT_TYPES_V2,eo as DATA_SYSTEM_SORT_FIELD_CODES,cr as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,K as NATIVE_CONTRACT_CAPACITY_V2,Gi as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,Wi as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,Bi as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,Ji as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,zi as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,to as NATIVE_DATA_QUERY_OPERATORS_V2,bt as NativeConfigurationCompilerError,ue as NativeDataFieldContractV2Error,Fe as NativeDataPolicyExpressionV2Error,It as NativeEventActionContractError,Et as NativeScopeSourceFieldPathV2Error,Bn as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,pe as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,ot as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,ni as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,Ct as WORKFLOW_EVENT_TYPES_V2,rr as compileNativeApplicationConfiguration,nn as compileNativeEventAction,us as compileNativeEventCapturePlansV2,ls as compileRequiredPlatformCapabilitiesV3,Mt as hasDataAuditReadPolicy,Se as isDataAuditMetadataField,jt as isDataSystemSortField,ri as isNativeDataQueryOperatorV2,je as isNativeMultiValueFieldV2,Pi as materializeNativeDataQueryPathTypesV2,ze as nativeDataPolicyExpressionLeavesV2,cn as nativeDataPolicyExpressionToCnfV2,Fi as nativeDataQueryPathPlanV2,ci as nativeFieldAggregatePlanV2,Ci as nativeFieldColumnDefinitionV2,bi as nativeFieldDefaultSqlV2,Oi as nativeFieldHasDefaultV2,Di as nativeFieldIndexStatementsV2,We as nativeFieldRequiresCreateInputV2,Ri as nativeFieldSequenceGrantStatementsV2,hi as nativeFieldSequenceOwnershipStatementsV2,$i as nativeFieldSequenceStatementsV2,Gt as nativeFieldSupportsFilterV2,ai as nativeFieldSupportsOperatorV2,ct as nativeFieldSupportsSearchV2,dt as nativeFieldSupportsSortV2,Jt as nativeOperatorsForFieldV2,Co as nativePhysicalFieldV2,Ti as nativePhysicalFieldsV2,_e as nativePhysicalObjectNameV2,Vi as nativeScopeSourceFieldValueV2,en as nativeScopeSourceGrantPathSupportedV2,At as nativeScopeSourceSubjectPathSupportedV2,Si as nativeSubtableConstraintStatementsV2,st as parseNativeDataFieldsV2,xt as parseNativeDataResourceInvariantsV2,pt as projectNativeDataResourceViewV2,te as quoteNativeIdentifierV2,Ve as resolveNativeScopeSourceFieldPathV2,kt as validateNativeDataResourceReferencesV2,ft as validateNativeDataResourceSurfaceV2,sn as validateWorkflowInstanceCommandPolicies,Ui as workflowInstanceCommandDeadlineError,xi as workflowInstanceTerminateCapabilityAllowed,on as workflowPolicyTimestamp};
8
+ END $native_subtable$`]}function _e(e,...t){return`${e}_${mo("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function te(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function Oo(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":_t.has(e.type)?"btree-snapshot-expressions":No.has(e.type)?"gin-jsonb-path":"btree":"none"}function $o(e){switch(e.type){case"text.short":return`varchar(${e.maxLength??255})`;case"text.long":case"text.rich":return"text";case"number.integer":return"bigint";case"number.decimal":return`numeric(${e.precision??38},${e.scale??10})`;case"boolean":return"boolean";case"date":return"date";case"time":return"time(0)";case"datetime":return"timestamptz";case"date-range":return"daterange";case"datetime-range":return"tstzrange";case"uuid":return"uuid";case"serial-number":return"varchar(255)";case"subtable":return"child-resource";default:return To.has(e.type),"jsonb"}}function Xt(e,t){if(je(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=Kt(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${Kt(Ge(e,t.code))})::text, ${n}, '0'))`}function ho(e,t){return qt.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:go.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function Je(e){return`"app_data".${te(e)}`}function Ge(e,t){let o=_e("seq",e,t);return`"app_data".${te(o)}`}function Kt(e){return`'${e.replace(/'/g,"''")}'`}var Qt=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),Ro=new Set([...Qt,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),Zt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Do=new Set(["__proto__","prototype","constructor"]),Et=class extends Error{constructor(o){super("OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID");this.path=o;this.name="NativeScopeSourceFieldPathV2Error"}path;code="OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID"};function Ve(e,t){let o=tn(e);if(!o)return null;let n=t.get(o[0]);if(!n)return null;let i=o.slice(1).join(".")||void 0;return{field:n,...i?{valuePath:i}:{}}}function At(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function en(e,t,o){if(!e||!t||!So(e))return!1;let{field:n,valuePath:i}=e;if(!i)return t.valueType==="uuid"?n.type==="uuid":["text.short","text.long","serial-number"].includes(n.type);if(i==="value")return!(t.valueSourceResourceCode&&n.type.startsWith("resource-ref.")&&n.source?.resourceCode!==t.valueSourceResourceCode);let r=i.slice(9),s=o.get(n.source?.resourceCode||"")?.get(r)?.type;return t.valueType==="uuid"?s==="uuid":["text.short","text.long","serial-number"].includes(s||"")}function Vs(e,t){let o=tn(t);if(!o)throw new Et(String(t||""));let n=e;for(let i of o){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,i))return;n=n[i]}return n}function So(e){let{field:t,valuePath:o}=e;if(!o)return!Ro.has(t.type);if(o==="value")return Qt.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return Zt.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function tn(e){if(typeof e!="string"||e.length===0||e.length>192)return null;let t=e.split(".");return![1,2,3].includes(t.length)||t.some(o=>!Zt.test(o)||Do.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var yo=new Set(["option.single","user.single","department.single","resource-ref.single"]),Vo=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),wo=new Set(["value","label","description","color"]),Po=new Set(["avatarUrl","employeeNo","title","mobile","email"]),Fo=new Set(["fullPath","parent.value","parent.label"]),vo=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),Lo=new Set(["longitude","latitude","accuracy"]),ko=new Set(["address","name","province","city","district","source"]);function Ps(e){let t=new Map(e.map(o=>[o.code,new Map(o.schema.fields.map(n=>[n.code,n]))]));return e.map(o=>({...o,schema:{...o.schema,fields:o.schema.fields.map(n=>{let i=xo(n,t);if(!Object.keys(i).length)return n;let r={...n};return Object.defineProperty(r,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(i)}),r})}}))}function Fs(e,t){if(yo.has(e.type)&&wo.has(t)||e.type==="user.single"&&Po.has(t)||e.type==="department.single"&&Fo.has(t))return we(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&vo.has(t))return we(t);if(e.type==="location"){if(Lo.has(t))return{parts:[t],type:"number.decimal"};if(ko.has(t))return we(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function xo(e,t){if(e.type!=="resource-ref.single"||!e.source)return{};let o=t.get(e.source.resourceCode);return o?Object.fromEntries((e.source.snapshotFields||[]).flatMap(n=>{let i=o.get(n);return i?[[`snapshot.${n}`,Vo.has(i.type)?i.type:"json"]]:[]})):{}}function we(e){return{parts:e.split("."),type:"text.short"}}var It=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function nn(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(E,N)=>{throw new It(`${o}${E}`,N)},i=(E,N,m)=>((!E||typeof E!="object"||Array.isArray(E)||Object.keys(E).some(g=>!m.includes(g)))&&n(N,"Invalid action object or unsupported property"),E),r=i(e.execution,"/execution",["kind","version","operations"]);(r.kind!=="native-data"||r.version!==1)&&n("/execution","Expected native-data version 1"),e.platformAccess&&n("/platformAccess","Native actions do not use application runtime capabilities"),(!Array.isArray(e.eventTypes)||!e.eventTypes.length||e.eventTypes.some(E=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(E)))&&n("/eventTypes","Native data actions require declared data events");let a=e.filter?.resourceCodes;(!Array.isArray(a)||!a.length||a.length>20)&&n("/filter/resourceCodes","Native actions require explicit source resources");let s=new Map(t.map(E=>[E.code,E])),l=a.map(E=>{let N=s.get(E);return N||n("/filter/resourceCodes","Unknown source resource"),new Set((N.schema?.fields||[]).map(m=>m.code))}),p=new Set(e.payload?.fields||[]),_=e.payload?.includeChanges===!0,d=(E,N)=>{let m=i(E,N,["source","path","value"]);if(m.source==="literal"){(!Object.hasOwn(m,"value")||Object.hasOwn(m,"path"))&&n(N,"Literal binding requires only value");let b;try{b=JSON.stringify(m.value)}catch{n(N,"Literal must be JSON")}return(b===void 0||Buffer.byteLength(b)>65536)&&n(N,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(b)}}(m.source!=="event"||typeof m.path!="string"||Object.hasOwn(m,"value"))&&n(N,"Expected a literal or event binding");let g=m.path.split(".");(g.length>8||g.some(b=>!/^[A-Za-z0-9_-]+$/.test(b)||["__proto__","prototype","constructor"].includes(b)))&&n(N,"Invalid event path");let T=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(m.path),D=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(m.path);if(T||D){let b=(T||D)[1];l.some(O=>!O.has(b))&&n(N,"Source field must exist on every filtered resource"),p.add(b),D&&(_=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(m.path)||n(N,"Event path is not part of the data event contract");return{source:"event",path:m.path}};(!Array.isArray(r.operations)||r.operations.length<1||r.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let c={},A=r.operations.map((E,N)=>{let m=`/execution/operations/${N}`,g=i(E,m,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(g.operation)||n(m,"Unsupported Native operation");let T=s.get(g.resourceCode);T||n(m,"Unknown action target resource");let D=new Map((T.schema?.fields||[]).map(O=>[O.code,O])),b=g.data===void 0?{}:i(g.data,`${m}/data`,[...D.keys()]);return Object.keys(b).length>32&&n(m,"Maximum 32 mapped fields per operation"),g.operation==="create"&&(g.id!==void 0||g.expectedRevision!==void 0)&&n(m,"Create does not accept id or expectedRevision"),g.operation==="delete"&&g.data!==void 0&&n(m,"Delete does not accept data"),Object.keys(b).some(O=>D.get(O)?.type==="serial-number")&&n(m,"Generated fields cannot be assigned"),c[g.resourceCode]=X(T),{operation:g.operation,resourceCode:g.resourceCode,...g.operation==="create"?{}:{id:d(g.id,`${m}/id`),expectedRevision:d(g.expectedRevision,`${m}/expectedRevision`)},...g.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(b).map(([O,V])=>[O,d(V,`${m}/data/${O}`)]))}}});(p.size>32||[...p].some(E=>l.some(N=>!N.has(E))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let f={kind:"native-data",version:1,operations:A,resourceDigests:c};return Buffer.byteLength(JSON.stringify(f))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...f,digest:X(f)},payload:{includeChanges:_,fields:[...p].sort()}}}function Ee(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function sn(e,t){if(e?.instanceCommands===void 0)return[];let o=Ee(e.instanceCommands);if(!o||!Object.keys(o).length||Object.keys(o).some(i=>!["withdraw","terminate"].includes(i)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let n=[];for(let[i,r]of Object.entries(o)){let a=Ee(r),s=i==="withdraw"?["beforeFact"]:["beforeFact","capability"];if(!a||Object.keys(a).some(l=>!s.includes(l))){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${i}`);continue}if(i==="terminate"){let l=a.capability;(typeof l!="string"||l.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(l)||t&&(!l.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(l)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(i==="withdraw"||a.beforeFact!==void 0){let l=a.beforeFact,p=Ee(e.inputSchema),_=Ee(Ee(p?.properties)?.[l]),d=Ee(Ee(e.subject)?.factProjection)?.[l],c=t?.fields.get(d);(typeof l!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(l)||!Array.isArray(p?.required)||!p.required.includes(l)||_?.type!=="string"||_?.format!=="date-time"||typeof d!="string"||t&&(c?.type!=="datetime"||c.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${i}`)}}return n}function xs(e,t){let o=e?.terminate?.capability;return typeof o=="string"&&/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(o)&&t.includes(o)}function on(e){if(typeof e!="string")return null;let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/.exec(e);if(!t)return null;let[,o,n,i,r,a,s]=t,l=t[8],p=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(i)<1||Number(i)>p||Number(r)>23||Number(a)>59||Number(s)>59||l!=="Z"&&(Number(l.slice(1,3))>23||Number(l.slice(4))>59))return null;let _=Date.parse(e);return Number.isFinite(_)?_:null}function Us(e,t,o,n){let i=e?.[t];if(!i||t==="terminate"&&i.beforeFact===void 0)return null;let r=i.beforeFact,a=Ee(o),s=r&&a&&Object.hasOwn(a,r)?on(a[r]):null,l=n instanceof Date?n.getTime():on(n);return s===null||l===null||!Number.isFinite(l)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":l<s?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}import*as Ke from"crypto";var rn="native-4",an={"application-native-2":"1.0.0","authz.native-batch-explain":"1.0.0","authz.native-management":"1.0.0","deployment.durable-runs":"1.0.0","deployment.platform-executor":"1.0.0","environment.on-demand-production":"1.0.0","environment.runtime-lifecycle":"1.0.0","data-api-v2":"1.1.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","workflow.named-input-sources":"1.0.0","directory-v2":"1.0.0","events-v2":"1.0.0","events.durable-receipts":"1.0.0","events.capture-policy":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","business-process.durable-command":"1.1.0","workflow.fresh-command-token":"1.0.0","notification-hub-v2":"1.0.0","authentication.application-login-surface":"1.0.0","public-access.anonymous-owner-records":"1.0.0"};var Ws=5,Bs=20,Js=50,Gs=50,zs=100,Fe=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function ze(e,t){let o=[],n=(i,r,a)=>{a>5&&Pe("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",r);let s=dn(i,r),l=["allOf","anyOf"].filter(d=>d in s);if(l.length===0){o.push({rule:s,pointer:r}),o.length>50&&Pe("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",r);return}let p=l[0],_=s[p];(l.length!==1||Object.keys(s).length!==1||!Array.isArray(_)||_.length<1||_.length>20)&&Pe("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",r),_.forEach((d,c)=>n(d,`${r}/${p}/${c}`,a+1))};return n(e,t,1),o}function cn(e,t){ze(e,t);let o=(n,i)=>{let r=dn(n,i);if(Array.isArray(r.allOf))return mt(r.allOf.flatMap((a,s)=>o(a,`${i}/allOf/${s}`)),i);if(Array.isArray(r.anyOf)){let a=[[]];return r.anyOf.forEach((s,l)=>{let p=o(s,`${i}/anyOf/${l}`);a=mt(a.flatMap(_=>p.map(d=>[..._,...d])),i)}),a}return[[r]]};return mt(o(e,t),t)}function mt(e,t){let o=e.reduce((n,i)=>n+i.length,0);return(e.length>50||o>100)&&Pe("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function dn(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&Pe("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function Pe(e,t){throw new Fe(e,t)}var Uo="openxiangda.config-bundle/v3",Rn="openxiangda.contract-bundle/v3",ln="openxiangda.native-configuration-projection/v1",Le=rn,Mo=/^[a-f0-9]{64}$/,jo=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Wo=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,Bo=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,Jo=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,Go=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,zo=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,un=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,Yo=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,Ho=/^[A-Z][A-Z0-9_]*$/,Ko=/^[a-z][a-z0-9-]{2,63}$/,qo=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Xo=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,Qo=16,Zo=2*1024,ei=new Set(["text.short","text.long","number.integer","number.decimal","boolean","date","time","datetime","option.single","option.multiple","cascade.single","cascade.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple","uuid","serial-number"]),ti=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),ni=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),oi=4*1024*1024,ii=8*1024*1024,si=40,ri=1e5,gt=1024*1024,ai="openxiangda.event-handler-manifest/v2",Dn="openxiangda.application-route-manifest/v3",fn=64,ci=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),K=Object.freeze({perspectives:100,resources:100,capabilities:2e3,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:100,routes:500,adminPages:500,adminNavigationGroups:100,adminNavigationItems:500}),Tt=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],Ct=["openxiangda.workflow.instance.started.v2","openxiangda.workflow.instance.cc_added.v2","openxiangda.workflow.instance.completed.v2","openxiangda.workflow.instance.rejected.v2","openxiangda.workflow.instance.returned.v2","openxiangda.workflow.instance.resumed.v2","openxiangda.workflow.instance.withdrawn.v2","openxiangda.workflow.instance.terminated.v2","openxiangda.workflow.task.created.v2","openxiangda.workflow.task.assigned.v2","openxiangda.workflow.task.assignment_pending.v2","openxiangda.workflow.task.assignment_resolution_failed.v2","openxiangda.workflow.task.approved.v2","openxiangda.workflow.task.completed.v2","openxiangda.workflow.task.rejected.v2","openxiangda.workflow.task.returned.v2","openxiangda.workflow.task.resubmitted.v2","openxiangda.workflow.task.transferred.v2","openxiangda.workflow.task.reassigned.v2","openxiangda.workflow.task.delegated.v2","openxiangda.workflow.task.assignee_added.v2","openxiangda.workflow.task.cancelled.v2","openxiangda.workflow.participant.activated.v2","openxiangda.workflow.participant.completed.v2","openxiangda.workflow.participant.rejected.v2","openxiangda.workflow.participant.returned.v2","openxiangda.workflow.participant.transferred.v2","openxiangda.workflow.participant.reassigned.v2","openxiangda.workflow.participant.delegated.v2","openxiangda.workflow.participant.added.v2","openxiangda.workflow.participant.suspended.v2","openxiangda.workflow.participant.resumed.v2","openxiangda.workflow.participant.cancelled.v2"],di=new Set(Ct),bt=class extends Error{code;pointer;identifiers;constructor(t,o,n={}){super(t),this.name="NativeConfigurationCompilerError",this.code=t,this.pointer=o,this.identifiers=Object.fromEntries(Object.entries(n).slice(0,8).map(([i,r])=>[i,String(r).slice(0,128)]))}};function rr(e){let t=$(e.appCode,"/appCode",128);jo.test(t)||u("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=$t(e.expectedConfigDigest,"/expectedConfigDigest"),n=$t(e.expectedContractDigest,"/expectedContractDigest"),i=On(e.configBytes,oi,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),r=On(e.contractBytes,ii,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");$n(i,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),$n(r,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let a=Cn(i,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),s=Cn(r,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");bn(a,"/config"),bn(s,"/contracts");let l=a,p=s;pi(l,t),_i(p,t,o);let _=Ei(l,o,p.generatorVersion);Qi(_,p,l),H(_)!==H(p)&&u("NATIVE_CONTRACT_CLOSURE_MISMATCH",ht(_,p,"/contracts"));let d={authz:{appCode:t,...l.authz,perspectives:l.perspectives,capabilityCatalog:_.capabilities},data:{appCode:t,resources:l.data.resources,resourceContracts:_.resources},events:{appCode:t,...l.events,consumers:_.eventConsumers,producers:_.eventProducers,handlerManifest:_.eventHandlerManifest,eventTypes:_.eventTypes,capturePlans:ui({resources:l.data.resources,dataPolicies:l.authz.dataPolicies,subscriptions:_.eventConsumers,capturePolicies:l.events.capturePolicies})},workflows:{appCode:t,...l.workflows,contracts:_.workflows},runtime:{appCode:t,requirements:l.runtime,backend:l.backend,frontend:l.frontend},contracts:_},c={authz:he(d.authz),data:he(d.data),events:he(d.events),workflows:he(d.workflows),runtime:he(d.runtime),contracts:he(d.contracts)},A={configDigest:o,contractDigest:n,generatorVersion:p.generatorVersion},f=li(l),E={schemaVersion:ln,compilerContractVersion:Le,appCode:t,source:A,projections:c,requiredPlatformCapabilities:f,aggregateDigest:X({schemaVersion:ln,compilerContractVersion:Le,appCode:t,source:A,requiredPlatformCapabilities:f,projectionDigests:Object.fromEntries(Object.entries(c).map(([N,m])=>[N,m.digest]))})};return Mn(E)}function li(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,i=t.some(f=>f.capabilities.some(E=>E.endsWith(":directory:read")))||o.some(f=>f.schema.fields.some(E=>["user.single","user.multiple","department.single","department.multiple"].includes(E.type)))||n.some(f=>f.platformAccess?.directory),r=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),a=n.some(f=>f.platformAccess?.managedFiles||f.platformAccess?.managedFileCopies)||e.events.subscriptions.some(f=>f.platformAccess?.managedFileCopies),s=n.some(f=>f.platformAccess?.notification)||e.events.subscriptions.some(f=>f.platformAccess?.notification),l=e.workflows.definitions.filter(f=>f.launch.mode==="standalone"||f.launch.mode==="hidden-handoff"),p=n.some(f=>f.platformAccess?.workflow)||l.length>0,_={resources:o},d={perspectives:e.perspectives,authz:e.authz},c={schemaVersion:e.schemaVersion,appCode:e.appCode,frontend:{routes:e.frontend.routes,user:e.frontend.user,admin:e.frontend.admin,devicePolicy:e.frontend.devicePolicy},backend:{operations:n.map(f=>({code:f.code,method:f.method,path:f.path,capability:f.capability,platformAccess:f.platformAccess||null,ai:f.ai||null}))}};return[{code:"application-native-2",declaration:c},{code:"authz.native-batch-explain",declaration:d},{code:"authz.native-management",declaration:d},{code:"deployment.durable-runs",declaration:c.backend},{code:"deployment.platform-executor",declaration:c.backend},{code:"environment.on-demand-production",declaration:{environments:["preproduction","production"]}},{code:"environment.runtime-lifecycle",declaration:{environments:["preproduction","production"]}},...o.length?[{code:"data-api-v2",declaration:_},{code:"data.native-golden-crud",declaration:_}]:[],...o.some(Mt)?[{code:"data.audit-read-access",declaration:_}]:[],...i?[{code:"directory-v2",declaration:{roles:t.map(f=>({code:f.code,capabilities:f.capabilities.filter(E=>E.endsWith(":directory:read"))})),resources:o.map(f=>({code:f.code,fields:f.schema.fields.filter(E=>["user.single","user.multiple","department.single","department.multiple"].includes(E.type))})),operations:n.filter(f=>f.platformAccess?.directory).map(f=>({code:f.code,directory:f.platformAccess.directory}))}}]:[],...a?[{code:"data.managed-files",declaration:{operations:n.filter(f=>f.platformAccess?.managedFiles||f.platformAccess?.managedFileCopies).map(f=>({code:f.code,...f.platformAccess?.managedFiles?{managedFiles:f.platformAccess.managedFiles}:{},...f.platformAccess?.managedFileCopies?{managedFileCopies:f.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(f=>f.platformAccess?.managedFileCopies).map(f=>({code:f.code,managedFileCopies:f.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(f=>f.execution)?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(f=>f.execution)}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...r?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(f=>f.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(f=>f.definition.instanceCommands!==void 0)}]:[],...p?[{code:"business-process.durable-command",declaration:{operations:n.filter(f=>f.platformAccess?.workflow).map(f=>({code:f.code,workflow:f.platformAccess.workflow})),definitions:l,activations:e.workflows.activations.filter(f=>l.some(E=>E.definition.code===f.workflowCode))}}]:[],...s?[{code:"notification-hub-v2",declaration:{operations:n.filter(f=>f.platformAccess?.notification).map(f=>({code:f.code,notification:f.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(f=>f.platformAccess?.notification).map(f=>({code:f.code,notification:f.platformAccess.notification}))}}]:[],...e.frontend.authentication?[{code:"authentication.application-login-surface",declaration:e.frontend.authentication}]:[],...e.frontend.publicAccess?[{code:"public-access.anonymous-owner-records",declaration:e.frontend.publicAccess}]:[]].map(({code:f,declaration:E})=>({code:f,contractVersion:an[f],usageDigest:`sha256:${X(E)}`})).sort((f,E)=>f.code===E.code?0:f.code<E.code?-1:1)}function ui(e){let t=new Map,o=new Set(e.resources.map(r=>String(r.code)));for(let[r,a]of h(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let s=`/capturePlan/capturePolicies/${r}`,l=I(a,s);C(l,["resourceCode","mode"],s);let p=G(l.resourceCode,`${s}/resourceCode`);o.has(p)||u("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",s,{resourceCode:p}),t.has(p)&&u("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",s,{resourceCode:p}),l.mode!=="all"&&l.mode!=="subscribed"&&u("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${s}/mode`),t.set(p,l.mode)}let n=new Map(e.dataPolicies.map((r,a)=>{let s=I(r,`/capturePlan/dataPolicies/${a}`);return[String(s.code),s]})),i=e.subscriptions.map((r,a)=>I(r,`/capturePlan/subscriptions/${a}`));return e.resources.map((r,a)=>{let s=`/capturePlan/resources/${a}`,l=I(r,s),p=G(l.code,`${s}/code`),_=l.schema?I(l.schema,`${s}/schema`):l,d=new Set(h(_.fields||[],`${s}/schema/fields`,500).map((O,V)=>z(I(O,`${s}/schema/fields/${V}`).code,`${s}/schema/fields/${V}/code`))),c=l.dataPolicyCode?y(l.dataPolicyCode,`${s}/dataPolicyCode`):null,A=c?n.get(c):void 0;c&&!A&&u("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",s,{resourceCode:p,dataPolicyCode:c});let f=new Set;for(let O of A?.rules||[])f.add(String(O.field));if(A?.readExpression)for(let O of ze(A.readExpression,`${s}/readExpression`))f.add(String(O.rule.field));let E=new Set,N=new Set,m=new Set;for(let[O,V]of i.entries()){let w=h(V.eventTypes,`/capturePlan/subscriptions/${O}/eventTypes`,20).map(String);if(!w.some(B=>B.startsWith("openxiangda.data.")))continue;let x=I(V.filter||{},`/capturePlan/subscriptions/${O}/filter`),M=Array.isArray(x.resourceCodes)?x.resourceCodes.map(String):[];if(M.length&&!M.includes(p))continue;for(let B of w)Tt.includes(B)&&m.add(B);for(let B of fi(x,`/capturePlan/subscriptions/${O}/filter`))E.add(B);let ee=I(V.payload||{},`/capturePlan/subscriptions/${O}/payload`);for(let B of h(ee.fields||[],`/capturePlan/subscriptions/${O}/payload/fields`,32))N.add(z(B,`/capturePlan/subscriptions/${O}/payload/fields`))}let g=new Set([...E,...N]),T=new Set([...g,...f]);T.size>fn&&u("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",s,{resourceCode:p,maximum:fn});for(let O of T)!d.has(O)&&!(f.has(O)&&ci.has(O))&&u("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",s,{resourceCode:p,field:O});let D=I(l.fieldPolicies||{},`${s}/fieldPolicies`);for(let O of g)D[O]?.mask==="omit"&&u("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",s,{resourceCode:p,field:O});let b={resourceCode:p,...t.get(p)==="subscribed"?{capturedEventTypes:[...m].sort()}:{},filterFields:[...E].sort(),projectionFields:[...N].sort(),authorizationFields:[...f].sort(),captureFields:[...T].sort()};return{...b,digest:X(b)}}).sort((r,a)=>r.resourceCode.localeCompare(a.resourceCode))}function fi(e,t){let o=new Set;for(let[a,s]of h(e.changes||[],`${t}/changes`,16).entries()){let l=I(s,`${t}/changes/${a}`);o.add(z(l.field,`${t}/changes/${a}/field`))}let n=I(e.changedFields||{},`${t}/changedFields`);for(let a of["anyOf","allOf","noneOf"])for(let[s,l]of h(n[a]||[],`${t}/changedFields/${a}`,32).entries())o.add(z(l,`${t}/changedFields/${a}/${s}`));let i=0,r=(a,s,l)=>{l>3&&u("NATIVE_EVENT_FILTER_DEPTH_LIMIT",s);let p=I(a,s);if(p.change){let d=I(p.change,`${s}/change`);o.add(z(d.field,`${s}/change/field`)),i+=1;return}if(p.not){r(p.not,`${s}/not`,l+1);return}let _=p.all?"all":p.any?"any":null;_||u("NATIVE_EVENT_FILTER_CONDITION_INVALID",s);for(let[d,c]of h(p[_],`${s}/${_}`,16).entries())r(c,`${s}/${_}/${d}`,l+1)};return e.where&&r(e.where,`${t}/where`,1),i+=Array.isArray(e.changes)?e.changes.length:0,i>16&&u("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function pi(e,t){C(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),v(e.schemaVersion,Uo,"/config/schemaVersion"),v(e.compilerContractVersion,Le,"/config/compilerContractVersion"),v(e.appCode,t,"/config/appCode"),h(e.perspectives,"/config/perspectives",100);let o=I(e.authz,"/config/authz");C(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),h(o.capabilities,"/config/authz/capabilities",2e3),h(o.roles,"/config/authz/roles",100),h(o.scopeDimensions,"/config/authz/scopeDimensions",100),h(o.scopeSources,"/config/authz/scopeSources",100),h(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),h(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),h(o.dataPolicies,"/config/authz/dataPolicies",100),h(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=I(e.backend,"/config/backend");C(n,["secrets","operations"],"/config/backend"),h(n.secrets,"/config/backend/secrets",100),h(n.operations,"/config/backend/operations",500),zi(n.secrets);let i=I(e.data,"/config/data");C(i,["resources"],"/config/data",["resourceDetailRoutes"]),h(i.resources,"/config/data/resources",100),i.resourceDetailRoutes!==void 0&&h(i.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let r=I(e.events,"/config/events");C(r,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),h(r.schemas,"/config/events/schemas",100),h(r.subscriptions,"/config/events/subscriptions",100),h(r.timers,"/config/events/timers",100),h(r.dateTriggers,"/config/events/dateTriggers",100);let a=I(e.workflows,"/config/workflows");C(a,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),h(a.definitions,"/config/workflows/definitions",100),h(a.bindings,"/config/workflows/bindings",100),h(a.activations,"/config/workflows/activations",100),h(a.providers,"/config/workflows/providers",100),h(a.editableParameters,"/config/workflows/editableParameters",100);let s=I(e.frontend,"/config/frontend");C(s,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),h(s.routes,"/config/frontend/routes",500);let l=I(s.user,"/config/frontend/user");C(l,["applicationTodoCenter"],"/config/frontend/user"),De(l.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),Rt(s.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(s,"authentication")&&yn(s.authentication,s.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(s,"publicAccess")&&Ri(s.publicAccess,e,"/config/frontend/publicAccess");let p=I(s.admin,"/config/frontend/admin");C(p,["navigation"],"/config/frontend/admin",["access"]),p.access!==void 0&&Xe(p.access,"/config/frontend/admin/access",e.appCode),Vi(p.navigation,"/config/frontend/admin/navigation");let _=I(e.runtime,"/config/runtime");C(_,["protocolCapabilities","health"],"/config/runtime"),F(_.protocolCapabilities,"/config/runtime/protocolCapabilities",100),C(I(_.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),v(_.health.livePath,"/__platform/health","/config/runtime/health/livePath"),v(_.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),v(_.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function _i(e,t,o){C(e,["schemaVersion","compilerContractVersion","generatorVersion","appCode","configDigest","perspectives","resources","capabilities","operations","eventConsumers","eventProducers","eventSchemas","eventHandlerManifest","eventTypes","workflows","routes","routeManifest","adminPages","adminNavigation"],"/contracts",["authentication","publicAccess","adminAccess"]),v(e.schemaVersion,Rn,"/contracts/schemaVersion"),v(e.compilerContractVersion,Le,"/contracts/compilerContractVersion"),$(e.generatorVersion,"/contracts/generatorVersion",128),v(e.appCode,t,"/contracts/appCode"),v(e.configDigest,o,"/contracts/configDigest"),h(e.perspectives,"/contracts/perspectives",K.perspectives),h(e.resources,"/contracts/resources",K.resources),h(e.capabilities,"/contracts/capabilities",K.capabilities),h(e.operations,"/contracts/operations",K.operations),h(e.eventConsumers,"/contracts/eventConsumers",K.eventConsumers),h(e.eventProducers,"/contracts/eventProducers",K.eventProducers),h(e.eventSchemas,"/contracts/eventSchemas",K.eventSchemas),I(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),F(e.eventTypes,"/contracts/eventTypes",K.eventTypes),h(e.workflows,"/contracts/workflows",K.workflows),h(e.routes,"/contracts/routes",K.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&Oi(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&Di(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&Xe(e.adminAccess,"/contracts/adminAccess",t),ki(e.routeManifest,"/contracts/routeManifest",t),Fi(e.adminPages,"/contracts/adminPages"),vi(e.adminNavigation,"/contracts/adminNavigation")}function Ei(e,t,o){let n=mi(e);Wi(e,n),Ji(e),Bi(e),Yi(e);let i=e.events.schemas.map((c,A)=>{let f=`/config/events/schemas/${A}`,E=I(c,f),N=$(E.eventType,`${f}/eventType`,255);return N.startsWith("openxiangda.")&&u("NATIVE_EVENT_SCHEMA_RESERVED",`${f}/eventType`,{eventType:N}),v(E.schemaDigest,X(I(E.jsonSchema,`${f}/jsonSchema`)),`${f}/schemaDigest`),E}),r=new Set([...Tt,...Ct,...i.map(c=>String(c.eventType))]),a=new Map(e.data.resources.map(c=>[String(c.code),new Map(c.schema.fields.map(A=>[String(A.code),String(A.type)]))])),s=ne(e.events.subscriptions.map((c,A)=>{let f=`/config/events/subscriptions/${A}`,E=I(c,f),N=F(E.eventTypes,`${f}/eventTypes`,20);N.forEach((D,b)=>{r.has(D)||u("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${f}/eventTypes/${b}`,{eventType:D})});let m=nn(E,e.data.resources,f),g=Ii(E.delivery,N,`${f}/delivery`),T=Ai(E.platformAccess,`${f}/platformAccess`,a);return{code:y(E.code,`${f}/code`),endpointPath:se(E.endpointPath,`${f}/endpointPath`),eventTypes:N,filter:I(E.filter,`${f}/filter`),payload:m?.payload||I(E.payload,`${f}/payload`),...m?{execution:m.execution}:{},...T?{platformAccess:T}:{},delivery:g}}),c=>c.code),l=new Map(i.map(c=>[String(c.eventType),String(c.dataSchemaVersion)])),p=ne([...e.data.resources.flatMap(c=>Tt.map(A=>({code:`data:${c.code}:${A}`,source:"data",eventType:A,dataSchemaVersion:"2.0.0",resourceCode:c.code}))),...i.map(c=>({code:`app:${c.eventType}`,source:"app",eventType:c.eventType,dataSchemaVersion:c.dataSchemaVersion})),...e.events.timers.map(c=>({code:c.code,source:"timer",eventType:c.eventType,dataSchemaVersion:l.get(String(c.eventType))||"2.0.0"})),...e.events.dateTriggers.map(c=>({code:c.code,source:"date",eventType:c.eventType,dataSchemaVersion:l.get(String(c.eventType))||"2.0.0",resourceCode:c.resourceCode,field:c.field})),...e.workflows.activations.length?Ct.map(c=>({code:`workflow:${c}`,source:"workflow",eventType:c,dataSchemaVersion:"2.0.0"})):[]],c=>`${c.source}:${c.code}:${c.eventType}`),_=U([...s.flatMap(c=>c.eventTypes),...p.map(c=>String(c.eventType))]);Pi(e);let d=Pn(e);return{schemaVersion:Rn,compilerContractVersion:Le,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:Ni(e),capabilities:ne(n,c=>c.code),operations:Sn(e),eventConsumers:s,eventProducers:p,eventSchemas:i,eventHandlerManifest:{schemaVersion:ai,appCode:e.appCode,handlers:s.filter(c=>!c.execution).map(c=>({code:c.code,endpointPath:c.endpointPath,eventTypes:c.eventTypes,dataSchemaVersions:U(c.eventTypes.map(A=>A.startsWith("openxiangda.")?"2.0.0":l.get(A)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2}))},eventTypes:_,workflows:Ln(e),routes:qe(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:$i(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:Si(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:Mi(e),adminPages:d,adminNavigation:yi(e)}}function Ai(e,t,o){if(e===void 0)return;let n=I(e,t);C(n,["notification","managedFileCopies"],t,!0);let i={};if(n.notification!==void 0){let r=I(n.notification,`${t}/notification`);C(r,["mode"],`${t}/notification`),v(r.mode,"business-standard",`${t}/notification/mode`),i.notification={mode:"business-standard"}}if(n.managedFileCopies!==void 0){let r=h(n.managedFileCopies,`${t}/managedFileCopies`,16);r.length||u("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let a=new Set;i.managedFileCopies=ne(r.map((s,l)=>{let p=`${t}/managedFileCopies/${l}`,_=I(s,p);C(_,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],p),v(_.mode,"copy",`${p}/mode`);let d=G(_.sourceResourceCode,`${p}/sourceResourceCode`),c=G(_.targetResourceCode,`${p}/targetResourceCode`),A=o.get(d),f=o.get(c);(!A||!f)&&u("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",p);let E=F(_.sourceFieldCodes,`${p}/sourceFieldCodes`,16),N=F(_.targetFieldCodes,`${p}/targetFieldCodes`,16);(!E.length||E.length!==N.length)&&u("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",p),E.forEach((g,T)=>{let D=A.get(g),b=f.get(N[T]);(!["file","image"].includes(String(D))||D!==b)&&u("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${p}/sourceFieldCodes/${T}`)});let m=`${d}:${E.join(",")}=>${c}:${N.join(",")}`;return a.has(m)&&u("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",p),a.add(m),{mode:"copy",sourceResourceCode:d,sourceFieldCodes:U(E),targetResourceCode:c,targetFieldCodes:U(N)}}),s=>`${s.sourceResourceCode}:${s.sourceFieldCodes.join(",")}=>${s.targetResourceCode}:${s.targetFieldCodes.join(",")}`)}return Object.keys(i).length||u("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),i}function Ii(e,t,o){let n=I(e,o);C(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),Z(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),Z(n.maxAttempts,`${o}/maxAttempts`,1,12);let i=Z(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);Z(n.maxBackoffMs,`${o}/maxBackoffMs`,i,18e5),Z(n.concurrency,`${o}/concurrency`,1,50);let r=$(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(r)||u("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),r==="workflow-instance"&&t.some(a=>!di.has(a))&&u("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function mi(e){let t=new Map;for(let o of Un(e.appCode))t.set(o.code,o);for(let[o,n]of e.authz.capabilities.entries()){let i=`/config/authz/capabilities/${o}`,r=I(n,i);C(r,["code","kind","name","description"],i,!0);let a=Ae(r.code,`${i}/code`,e.appCode);t.has(a)&&u("NATIVE_CAPABILITY_DUPLICATE",`${i}/code`),["backend","ui"].includes(r.kind)||u("NATIVE_CAPABILITY_KIND_INVALID",`${i}/kind`);let s={code:a,kind:r.kind,name:$(r.name,`${i}/name`,255),source:"explicit",...r.description===void 0?{}:{description:St(r.description,`${i}/description`,2e3)}};t.set(a,s)}for(let[o,n]of e.data.resources.entries()){let i=`/config/data/resources/${o}`,r=ke(n,i,e.appCode),a={read:`\u8BFB\u53D6${r.name}`,create:`\u65B0\u5EFA${r.name}`,update:`\u66F4\u65B0${r.name}`,delete:`\u5220\u9664${r.name}`};for(let s of["read","create","update","delete"]){let l=Ae(r.capabilities[s],`${i}/capabilities/${s}`,e.appCode);t.has(l)&&u("NATIVE_CAPABILITY_DUPLICATE",`${i}/capabilities/${s}`),t.set(l,{code:l,kind:"data",name:a[s],source:"data"})}for(let[s,l]of Object.entries(r.fieldPolicies)){if(Se(s))continue;let p=I(l,`${i}/fieldPolicies/${s}`);for(let _ of["read","create","update"])if(Array.isArray(p[_]))for(let d of F(p[_],`${i}/fieldPolicies/${s}/${_}`,2e3))Ae(d,`${i}/fieldPolicies/${s}/${_}`,e.appCode),!t.has(d)&&t.set(d,{code:d,kind:"data",name:`${r.name}.${s}.${_}`,source:"data"})}}return[...t.values()]}function Ni(e){let t=gi(e);return ne(e.data.resources.map((o,n)=>{let i=ke(o,`/config/data/resources/${n}`,e.appCode),r=t.get(i.code);return{code:i.code,schemaDigest:X(i.schema),fields:ne(i.schema.fields.map(a=>({code:a.code,type:a.type})),a=>a.code),...r?{detailRouteCode:r}:{}}}),o=>o.code)}function gi(e){let t=e.data.resourceDetailRoutes===void 0?[]:h(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((r,a)=>{let s=`/config/data/resources/${a}`,l=ke(r,s,e.appCode);return[l.code,l]})),n=new Map(qe(e).map(r=>[String(r.code),r])),i=new Map;for(let[r,a]of t.entries()){let s=`/config/data/resourceDetailRoutes/${r}`,l=I(a,s);C(l,["resourceCode","desktop","mobile"],s);let p=G(l.resourceCode,`${s}/resourceCode`);i.has(p)&&u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${s}/resourceCode`);let _=o.get(p);_||u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${s}/resourceCode`);let d=y(l.desktop,`${s}/desktop`),c=y(l.mobile,`${s}/mobile`);d===c&&u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",s);let A=String(_.capabilities.read);for(let[f,E]of[["desktop",d],["mobile",c]]){let N=`${s}/${f}`,m=n.get(E);m||u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",N),m.surface!=="user"&&u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",N);let g=se(m.path,`${N}/path`),T=[...g.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],D=f==="mobile"?!g.startsWith("/m/"):g==="/m"||g.startsWith("/m/");(g.includes("*")||g.includes("?")||g.includes("#")||g.split("/").includes("..")||T.length!==1||D)&&u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",N);let b=Array.isArray(m.access?.allOf)?m.access.allOf:[];m.capability!==A&&!b.includes(A)&&u("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",N)}i.set(p,{desktop:d,mobile:c})}return i}function Sn(e){let t=new Map(e.data.resources.map((i,r)=>{let a=`/config/data/resources/${r}`,s=ke(i,a,e.appCode);return[s.code,new Map(s.schema.fields.map(l=>[String(l.code),String(l.type)]))]})),o=new Set(t.keys()),n=new Set(e.workflows.activations.map((i,r)=>Qe(I(i,`/config/workflows/activations/${r}`).workflowCode,`/config/workflows/activations/${r}/workflowCode`)));return ne(e.backend.operations.map((i,r)=>{let a=`/config/backend/operations/${r}`,s=I(i,a);C(s,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","ai"],a,!0);let l=$(s.method,`${a}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(l)||u("NATIVE_OPERATION_METHOD_INVALID",`${a}/method`);let p=y(s.code,`${a}/code`);Ci(s.ai,a,p,l,o);let _=Ti(s.platformAccess,`${a}/platformAccess`,t,n,new Set(e.authz.roles.map(d=>String(d.code))));return{code:p,method:l,path:se(s.path,`${a}/path`),requiredCapability:Ae(s.capability,`${a}/capability`,e.appCode),requestSchemaDigest:X(I(s.requestSchema,`${a}/requestSchema`)),responseSchemaDigest:X(I(s.responseSchema,`${a}/responseSchema`)),...s.description===void 0?{}:{description:St(s.description,`${a}/description`,2e3)},..._?{platformAccess:_}:{}}}),i=>i.code)}function Ti(e,t,o,n,i){if(e===void 0)return null;let r=I(e,t);C(r,["directory","managedFiles","managedFileCopies","notification","workflow","roleAssertions"],t,!0),Object.keys(r).length===0&&u("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let a={};if(r.roleAssertions!==void 0){let s=I(r.roleAssertions,`${t}/roleAssertions`);C(s,["roleCodes"],`${t}/roleAssertions`);let l=F(s.roleCodes,`${t}/roleAssertions/roleCodes`,20);l.length||u("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),l.forEach((p,_)=>{i.has(p)||u("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${_}`)}),a.roleAssertions={roleCodes:U(l)}}if(r.directory!==void 0){let s=I(r.directory,`${t}/directory`);C(s,["mode","fields"],`${t}/directory`),s.mode!=="current-initiator"&&u("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let l=new Set(["displayName","employeeNumber","primaryDepartment","departments"]),p=F(s.fields,`${t}/directory/fields`,4);(!p.length||p.some(_=>!l.has(_)))&&u("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),a.directory={mode:"current-initiator",fields:U(p)}}if(r.managedFiles!==void 0){let s=h(r.managedFiles,`${t}/managedFiles`,16);s.length||u("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let l=new Set;a.managedFiles=ne(s.map((p,_)=>{let d=`${t}/managedFiles/${_}`,c=I(p,d);C(c,["resourceCode","fieldCodes","intents"],d);let A=G(c.resourceCode,`${d}/resourceCode`);(l.has(A)||!o.has(A))&&u("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${d}/resourceCode`),l.add(A);let f=F(c.fieldCodes,`${d}/fieldCodes`,16);(!f.length||f.some(N=>!["file","image","signature"].includes(String(o.get(A)?.get(N)||""))))&&u("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${d}/fieldCodes`);let E=F(c.intents,`${d}/intents`,2);return(!E.length||E.some(N=>!["create","update"].includes(N)))&&u("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${d}/intents`),{resourceCode:A,fieldCodes:U(f),intents:U(E)}}),p=>p.resourceCode)}if(r.managedFileCopies!==void 0){let s=h(r.managedFileCopies,`${t}/managedFileCopies`,16);s.length||u("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let l=new Set;a.managedFileCopies=ne(s.map((p,_)=>{let d=`${t}/managedFileCopies/${_}`,c=I(p,d);C(c,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],d),v(c.mode,"copy",`${d}/mode`);let A=G(c.sourceResourceCode,`${d}/sourceResourceCode`),f=G(c.targetResourceCode,`${d}/targetResourceCode`),E=o.get(A),N=o.get(f);(!E||!N)&&u("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",d);let m=F(c.sourceFieldCodes,`${d}/sourceFieldCodes`,16),g=F(c.targetFieldCodes,`${d}/targetFieldCodes`,16);(!m.length||m.length!==g.length)&&u("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",d),m.forEach((D,b)=>{let O=E.get(D),V=N.get(g[b]);(!["file","image"].includes(String(O))||O!==V)&&u("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${d}/sourceFieldCodes/${b}`)});let T=`${A}:${m.join(",")}=>${f}:${g.join(",")}`;return l.has(T)&&u("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",d),l.add(T),{mode:"copy",sourceResourceCode:A,sourceFieldCodes:U(m),targetResourceCode:f,targetFieldCodes:U(g)}}),p=>`${p.sourceResourceCode}:${p.sourceFieldCodes.join(",")}=>${p.targetResourceCode}:${p.targetFieldCodes.join(",")}`)}if(r.notification!==void 0){let s=I(r.notification,`${t}/notification`);C(s,["mode"],`${t}/notification`),s.mode!=="business-standard"&&u("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),a.notification={mode:"business-standard"}}if(r.workflow!==void 0){let s=I(r.workflow,`${t}/workflow`);C(s,["codes"],`${t}/workflow`);let l=F(s.codes,`${t}/workflow/codes`,16);(!l.length||l.some(p=>!n.has(p)))&&u("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`),a.workflow={codes:U(l)}}return a}function Ci(e,t,o,n,i){if(e===void 0)return;let r=`${t}/ai`,a=I(e,r);Jo.test(o)||u("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),C(a,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],r,!0),$(a.name,`${r}/name`,gt),$(a.description,`${r}/description`,gt);let s=$(a.risk,`${r}/risk`,16);["read","write","destructive","external"].includes(s)||u("NATIVE_OPERATION_AI_RISK_INVALID",`${r}/risk`),s==="read"!=(n==="GET")&&u("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`),n==="DELETE"&&!["destructive","external"].includes(s)&&u("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`);let l=F(a.resources,`${r}/resources`,16);l.length===0&&u("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${r}/resources`),l.forEach((_,d)=>{let c=G(_,`${r}/resources/${d}`);i.has(c)||u("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${r}/resources/${d}`)});let p=F(a.sideEffects,`${r}/sideEffects`,20);(s==="read"&&p.length!==0||s!=="read"&&p.length===0)&&u("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${r}/sideEffects`),a.concurrency!==void 0&&!["none","revision"].includes($(a.concurrency,`${r}/concurrency`,16))&&u("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${r}/concurrency`),a.timeoutMs!==void 0&&Z(a.timeoutMs,`${r}/timeoutMs`,100,3e4)}function Ye(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function bi(e,t){let o=I(e,t),n=$(o.type,`${t}/type`,32),i=["code","type","label","presentation","required"],r=n==="sso"?[...i,"provider"]:n==="dingtalk"?[...i,"flow"]:i;C(o,r,t);let a=y(o.code,`${t}/code`),s=$(o.label,`${t}/label`,255),l=$(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(l)||u("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let p=De(o.required,`${t}/required`);return["sso","password","dingtalk"].includes(n)||u("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),n==="sso"&&o.provider!=="tenant-default"&&u("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),n==="dingtalk"&&!["auto","jsapi","oauth"].includes($(o.flow,`${t}/flow`,16))&&u("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:a,type:n,label:s,presentation:l,required:p,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function pn(e,t,o){let n=I(e,o);C(n,["routeCode","path","defaultRouteCode"],o);let i=y(n.routeCode,`${o}/routeCode`),r=se(n.path,`${o}/path`),a=t==="desktop"?"/login":"/m/login";return(r!==a||/[:*?#\\]/.test(r))&&u("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:a}),{routeCode:i,path:r,defaultRouteCode:y(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function yn(e,t,o,n){if(e===null)return;let i=I(e,n);C(i,["accountMode","registration","methods","surfaces"],n),v(i.accountMode,"existing-platform-users-only",`${n}/accountMode`);let r=I(i.registration,`${n}/registration`);C(r,["mode"],`${n}/registration`),v(r.mode,"reject",`${n}/registration/mode`);let a=h(i.methods,`${n}/methods`,8);a.length===0&&u("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let s=a.map((m,g)=>bi(m,`${n}/methods/${g}`)),l=new Set,p=new Set;for(let[m,g]of s.entries())l.has(g.code)&&u("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${m}/code`),p.has(g.type)&&u("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${m}/type`),l.add(g.code),p.add(g.type);s.filter(m=>m.presentation==="primary").length!==1&&u("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let _=I(i.surfaces,`${n}/surfaces`);C(_,["desktop","mobile"],`${n}/surfaces`);let d=pn(_.desktop,"desktop",`${n}/surfaces/desktop`),c=pn(_.mobile,"mobile",`${n}/surfaces/mobile`);d.routeCode===c.routeCode&&u("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let A=h(t,"/config/frontend/routes",500),f=new Map;for(let[m,g]of A.entries()){let T=I(g,`/config/frontend/routes/${m}`);f.set(String(T.code||""),T)}let E=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(m=>String(m.code||"")).filter(m=>/^[a-z][a-z0-9-]{0,62}$/.test(m)));for(let[m,g]of[["desktop",d],["mobile",c]]){f.has(g.routeCode)&&u("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${m}/routeCode`);let T=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(g.defaultRouteCode||"")),D=f.get(g.defaultRouteCode),b=String(D?.path||"");if(T&&E.has(T[1])){let V=T[2]==="records"?`/my/${T[1]}`:`/my/${T[1]}/submit`;D={surface:"user",path:m==="mobile"?`/m${V}`:V},b=String(D.path)}let O=m==="desktop"?b==="/m"||b.startsWith("/m/"):!(b==="/m"||b.startsWith("/m/"));(!D||D.surface!=="user"||/[:*]/.test(b)||O)&&u("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${m}/defaultRouteCode`)}let N=Vn(o).filter(m=>!m.owner.startsWith("authentication:"));for(let[m,g]of[["desktop",d],["mobile",c]]){let T=N.find(D=>Ye(D.path)===Ye(g.path));T&&u("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${m}/path`,{owner:T.owner})}}function Oi(e,t){if(e===null)return;let o={data:{resources:[]},workflows:{definitions:[]},frontend:{routes:[{code:"auth-desktop-default",path:"/auth-desktop-default",surface:"user"},{code:"auth-mobile-default",path:"/m/auth-mobile-default",surface:"user"}],user:{applicationTodoCenter:!1},admin:{navigation:[]},authentication:e}},n=I(e,t),i=I(n.surfaces,`${t}/surfaces`),r={...n,surfaces:{...i,desktop:{...I(i.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...I(i.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};yn(r,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:r}},t)}function $i(e){let t=e.frontend.authentication;return t===null?null:{accountMode:t.accountMode,registration:{mode:t.registration.mode},methods:t.methods.map(o=>({...o})),surfaces:{desktop:{...t.surfaces.desktop},mobile:{...t.surfaces.mobile}}}}var hi=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function Ri(e,t,o){let n=I(e,o);C(n,["policies"],o);let i=h(n.policies,`${o}/policies`,16);i.length<1&&u("NATIVE_PUBLIC_POLICY_REQUIRED",o);let r=new Map(t.frontend.routes.map(p=>[p.code,p])),a=new Map(t.data.resources.map(p=>[p.code,p])),s=new Set,l=new Set(i.map(p=>String(p?.code||"")));i.forEach((p,_)=>{let d=`${o}/policies/${_}`,c=I(p,d);C(c,["code","routeCode","mode","resourceCode","operations","fields"],d,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let A=y(c.code,`${d}/code`);s.has(A)&&u("NATIVE_PUBLIC_POLICY_DUPLICATE",`${d}/code`);let f=y(c.routeCode,`${d}/routeCode`),E=r.get(f);(!E||E.surface!=="user"||E.capability!==void 0||E.access!==void 0||/[:*]/.test(String(E.path)))&&u("NATIVE_PUBLIC_ROUTE_INVALID",`${d}/routeCode`),v(c.mode,"anonymous",`${d}/mode`);let N=G(c.resourceCode,`${d}/resourceCode`),m=a.get(N);m||u("NATIVE_PUBLIC_RESOURCE_MISSING",`${d}/resourceCode`);let g=new Map(m.schema.fields.map(S=>[String(S.code),String(S.type)])),T=F(c.operations,`${d}/operations`,8);(T.length<1||T.some(S=>!hi.has(S)))&&u("NATIVE_PUBLIC_OPERATION_INVALID",`${d}/operations`),T.includes("draft.read")!==T.includes("draft.update")&&u("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${d}/operations`);let D=F(c.fields,`${d}/fields`,64);(D.length<1||D.some(S=>!g.has(S)))&&u("NATIVE_PUBLIC_FIELD_INVALID",`${d}/fields`);for(let S of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(c,S))continue;F(c[S],`${d}/${S}`,64).some(L=>!D.includes(L))&&u("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${d}/${S}`)}let b=Object.prototype.hasOwnProperty.call(c,"serverGeneratedFields")?h(c.serverGeneratedFields,`${d}/serverGeneratedFields`,16):[],O=new Set;b.forEach((S,k)=>{let L=`${d}/serverGeneratedFields/${k}`,W=I(S,L);C(W,["field","kind"],L);let J=z(W.field,`${L}/field`);(O.has(J)||!g.has(J)||D.includes(J)||g.get(J)!=="text.short"&&g.get(J)!=="text.long")&&u("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${L}/field`),v(W.kind,"random-token",`${L}/kind`),O.add(J)});let V=Object.prototype.hasOwnProperty.call(c,"schedule")?I(c.schedule,`${d}/schedule`):null;if(V){let S=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];C(V,S,`${d}/schedule`);for(let k of["campusPolicyCode","rulePolicyCode"])y(V[k],`${d}/schedule/${k}`);for(let k of S.filter(L=>!["campusPolicyCode","rulePolicyCode"].includes(L)))z(V[k],`${d}/schedule/${k}`);for(let k of[V.campusField,V.dateField,V.timeField])D.includes(String(k))||u("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${d}/schedule`);(!l.has(String(V.campusPolicyCode))||!l.has(String(V.rulePolicyCode)))&&u("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${d}/schedule`)}let w=Object.prototype.hasOwnProperty.call(c,"publicFilters")?h(c.publicFilters,`${d}/publicFilters`,16):[],x=new Set;w.forEach((S,k)=>{let L=`${d}/publicFilters/${k}`,W=I(S,L);C(W,["field","operator","value"],L);let J=z(W.field,`${L}/field`);x.has(J)&&u("NATIVE_PUBLIC_FILTER_DUPLICATE",`${L}/field`),D.includes(J)||u("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${L}/field`),v(W.operator,"eq",`${L}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(g.get(J)||"")||u("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${L}/field`),W.value!==null&&typeof W.value!="string"&&typeof W.value!="number"&&typeof W.value!="boolean"&&u("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${L}/value`),x.add(J)});let M=Object.prototype.hasOwnProperty.call(c,"publicSubtableFields")?I(c.publicSubtableFields,`${d}/publicSubtableFields`):null;if(M){Object.keys(M).length>64&&u("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields`);for(let[S,k]of Object.entries(M)){let L=m.schema.fields.find(Y=>String(Y.code)===S),W=String(L?.subtable?.resourceCode||""),J=a.get(W),de=new Map((J?.schema?.fields||[]).map(Y=>[String(Y.code),String(Y.type)])),j=F(k,`${d}/publicSubtableFields/${S}`,64);(!D.includes(S)||g.get(S)!=="subtable"||!J||j.length<1||j.some(Y=>!de.has(Y))||j.some(Y=>de.get(Y)==="subtable")||j.some(Y=>de.get(Y)==="signature"))&&u("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields/${S}`)}}if(T.some(S=>S.startsWith("public."))){Object.prototype.hasOwnProperty.call(c,"publicRecordFields")||u("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${d}/publicRecordFields`);let S=F(c.publicRecordFields,`${d}/publicRecordFields`,64);(S.length<1||S.some(k=>!D.includes(k))||S.some(k=>g.get(k)==="signature"||g.get(k)==="subtable"&&!M?.[k]))&&u("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${d}/publicRecordFields`)}let ee=Object.prototype.hasOwnProperty.call(c,"requiredFields")?F(c.requiredFields,`${d}/requiredFields`,64):[],B=m.surface||{},Ie=B.fields||{},ge=String(B.mutationOwner||"native")==="native"&&B.generated?.create!==!1,q=m.schema.fields.filter(S=>We(S,Ie[S.code])).map(S=>String(S.code));if(T.includes("create")&&!ge&&u("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/fields`),T.includes("create")&&!Object.prototype.hasOwnProperty.call(c,"draft")&&u("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`),T.includes("create"))for(let S of q){let k=D.includes(S)?ee.includes(S)?null:"requiredFields":"fields";k&&u("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/${k}`,{resourceCode:G,fieldCode:S})}if(Object.prototype.hasOwnProperty.call(c,"draft")){let S=I(c.draft,`${d}/draft`);C(S,["enabled","inactivityTtlSeconds","maxBytes"],`${d}/draft`),v(S.enabled,!0,`${d}/draft/enabled`),Z(S.inactivityTtlSeconds,`${d}/draft/inactivityTtlSeconds`,3600,7776e3),Z(S.maxBytes,`${d}/draft/maxBytes`,4096,262144)}else T.includes("draft.read")&&u("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`);let Te=Object.prototype.hasOwnProperty.call(c,"validations")?h(c.validations,`${d}/validations`,16):[],me=new Set;Te.forEach((S,k)=>{let L=`${d}/validations/${k}`,W=I(S,L);C(W,["code","kind","fields","result"],L);let J=y(W.code,`${L}/code`);me.has(J)&&u("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${L}/code`),v(W.kind,"duplicate",`${L}/kind`),v(W.result,"availability",`${L}/result`);let de=F(W.fields,`${L}/fields`,8);(de.length<1||de.some(j=>!D.includes(j))||de.some(j=>["file","subtable"].includes(g.get(j)||"")))&&u("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${L}/fields`),me.add(J)}),s.add(A)})}function Di(e,t){let o=I(e,t);C(o,["policies"],t),h(o.policies,`${t}/policies`,16).length<1&&u("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function Si(e){return{policies:ne(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:U(t.operations),fields:U(t.fields),...t.requiredFields?{requiredFields:U(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:U(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:U(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(o=>({field:o.field,operator:o.operator,value:o.value})).sort((o,n)=>ie(o.field,n.field))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>[o,U(Array.isArray(n)?n.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(o=>({field:o.field,kind:o.kind})).sort((o,n)=>ie(o.field,n.field))}:{},...t.schedule?{schedule:{campusPolicyCode:t.schedule.campusPolicyCode,rulePolicyCode:t.schedule.rulePolicyCode,campusField:t.schedule.campusField,ruleCampusField:t.schedule.ruleCampusField,ruleWeekdaysField:t.schedule.ruleWeekdaysField,ruleOpenAtField:t.schedule.ruleOpenAtField,ruleCloseAtField:t.schedule.ruleCloseAtField,ruleSlotMinutesField:t.schedule.ruleSlotMinutesField,ruleAdvanceHoursField:t.schedule.ruleAdvanceHoursField,ruleAdvanceDaysField:t.schedule.ruleAdvanceDaysField,campusEnabledField:t.schedule.campusEnabledField,ruleEnabledField:t.schedule.ruleEnabledField,dateField:t.schedule.dateField,timeField:t.schedule.timeField}}:{},...t.draft?{draft:{...t.draft}}:{},...t.validations?{validations:ne(t.validations.map(o=>({code:o.code,kind:o.kind,fields:U(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function Vn(e){let t=[{owner:"platform:admin-entry",path:"/"},{owner:"platform:admin-entry",path:"/admin"},{owner:"platform:file-preview",path:"/files/:resourceCode/:fileId/preview"}];e.frontend.authentication&&t.push({owner:"authentication:desktop",path:e.frontend.authentication.surfaces.desktop.path},{owner:"authentication:mobile",path:e.frontend.authentication.surfaces.mobile.path});for(let o of e.data.resources){let n=wn(o),i=`/admin/resources/${o.code}`,r=[["list",i],["detail",`${i}/:id`],["create",`${i}/new`],["update",`${i}/:id/edit`]];for(let[a,s]of r)n[a]&&t.push({owner:`resource:${o.code}:${a}`,path:s},{owner:`resource:${o.code}:${a}:mobile`,path:`/m${s}`})}if(e.frontend.user.applicationTodoCenter===!0&&t.push({owner:"application:todo-center",path:"/todos"},{owner:"application:todo-center:mobile",path:"/m/todos"}),e.workflows.definitions.length>0){t.push({owner:"workflow:work-center",path:"/work-center"},{owner:"workflow:work-center:mobile",path:"/m/work-center"},{owner:"workflow:task",path:"/tasks/:taskId"},{owner:"workflow:task:mobile",path:"/m/tasks/:taskId"},{owner:"workflow:instance",path:"/workflows/:instanceId"},{owner:"workflow:instance:mobile",path:"/m/workflows/:instanceId"});let o=!1;for(let n of e.workflows.definitions)["standalone","hidden-handoff"].includes(n.launch.mode)&&(o=!0);o&&t.push({owner:"workflow:launch",path:"/workflows/:workflowCode/start"},{owner:"workflow:launch:mobile",path:"/m/workflows/:workflowCode/start"})}return t}function qe(e){let t=new Map(Vn(e).map(o=>[Ye(o.path),o]));return ne(e.frontend.routes.map((o,n)=>{let i=`/config/frontend/routes/${n}`,r=I(o,i);C(r,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],i,!0),["admin","user"].includes(r.surface)||u("NATIVE_ROUTE_SURFACE_INVALID",`${i}/surface`);let a=se(r.path,`${i}/path`);r.surface==="admin"&&a!=="/admin"&&!a.startsWith("/admin/")&&u("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${i}/path`),r.surface==="user"&&(a==="/admin"||a.startsWith("/admin/"))&&u("NATIVE_USER_ROUTE_PATH_RESERVED",`${i}/path`);let s=Ye(a),l=t.get(s);l&&u("NATIVE_ROUTE_PATH_CONFLICT",`${i}/path`,{path:a,owner:l.owner}),t.set(s,{owner:`frontend:${String(r.code||n)}`,path:a});let p=/[:*]/.test(a),_=Dt(r,i,e.appCode),d=r.pinned===void 0?void 0:De(r.pinned,`${i}/pinned`),c=r.tabPersistence===void 0?p?"none":"session":$(r.tabPersistence,`${i}/tabPersistence`,16),A=r.keepAlive===void 0?"none":$(r.keepAlive,`${i}/keepAlive`,16);return["session","none"].includes(c)||u("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${i}/tabPersistence`),["none","memory"].includes(A)||u("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${i}/keepAlive`),p&&d===!0&&u("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${i}/pinned`),p&&c==="session"&&u("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${i}/tabPersistence`),p&&A==="memory"&&u("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${i}/keepAlive`),{code:y(r.code,`${i}/code`),path:a,label:$(r.label,`${i}/label`,255),surface:r.surface,...r.parentCode===void 0?{}:{parentCode:y(r.parentCode,`${i}/parentCode`)},..._,...d===void 0?{}:{pinned:d},tabPersistence:c,keepAlive:A}}),o=>o.code)}function wn(e){let t=e.surface===void 0?{}:I(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:I(t.generated,"/surface/generated"),i=o==="native";return{list:n.list??!0,detail:n.detail??!0,create:n.create??i,update:n.update??i,delete:n.delete??i}}function Pn(e){let t=[];for(let o of ne(e.data.resources,n=>n.code).flatMap(n=>[{resource:n,viewCode:void 0},...(n.surface?.views||[]).map(i=>({viewCode:i.code,resource:{...n,name:i.name,surface:pt(n.surface,i.code)}}))])){let{resource:n,viewCode:i}=o,r=`/admin/resources/${n.code}${i?`/views/${i}`:""}`,a=wn(n),s=[{operation:"list",kind:"resource-list",path:`${r}`,label:n.name,capability:n.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${r}/:id`,label:`${n.name}\u8BE6\u60C5`,capability:n.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${r}/new`,label:`\u65B0\u589E${n.name}`,capability:n.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${r}/:id/edit`,label:`\u7F16\u8F91${n.name}`,capability:n.capabilities.update,navigationEligible:!1}];for(let l of s)a[l.operation]&&t.push({code:`resource:${n.code}${i?`:view:${i}`:""}:${l.operation}`,kind:l.kind,path:l.path,label:l.label,navigationEligible:l.navigationEligible,capability:l.capability,resourceCode:n.code,...i?{viewCode:i}:{}})}for(let o of qe(e))o.surface==="admin"&&t.push({code:`operation:${o.code}`,kind:"operation",path:o.path,label:o.label,navigationEligible:!/[:*]/.test(o.path),routeCode:o.code});return t.sort((o,n)=>ie(o.code,n.code))}function Fn(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function yi(e){return e.frontend.admin.navigation.map((t,o)=>({code:t.code,label:t.label,...t.icon===void 0?{}:{icon:t.icon},order:t.order??o,items:t.items.map((n,i)=>({pageCode:Fn(n.page),...n.label===void 0?{}:{label:n.label},...n.icon===void 0?{}:{icon:n.icon},order:n.order??i})).sort((n,i)=>n.order-i.order||ie(n.pageCode,i.pageCode))})).sort((t,o)=>t.order-o.order||ie(t.code,o.code))}function Vi(e,t){let o=h(e,t,K.adminNavigationGroups),n=0;o.forEach((i,r)=>{let a=`${t}/${r}`,s=I(i,a);C(s,["code","label","icon","order","items"],a,!0),y(s.code,`${a}/code`),$(s.label,`${a}/label`,255),He(s.icon,`${a}/icon`),mn(s.order,`${a}/order`);let l=h(s.items,`${a}/items`,500);l.length===0&&u("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),n+=l.length,n>K.adminNavigationItems&&u("NATIVE_ARRAY_LIMIT_EXCEEDED",t),l.forEach((p,_)=>{let d=`${a}/items/${_}`,c=I(p,d);C(c,["page","label","icon","order"],d,!0),wi(c.page,`${d}/page`),c.label!==void 0&&$(c.label,`${d}/label`,255),He(c.icon,`${d}/icon`),mn(c.order,`${d}/order`)})})}function wi(e,t){let o=I(e,t),n=$(o.kind,`${t}/kind`,64);if(n==="resource"){C(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&y(o.viewCode,`${t}/viewCode`),G(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){C(o,["kind","routeCode"],t),y(o.routeCode,`${t}/routeCode`);return}u("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function Pi(e){let t=new Map(Pn(e).map(i=>[String(i.code),i])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((i,r)=>{let a=`/config/frontend/admin/navigation/${r}`;o.has(i.code)&&u("NATIVE_ADMIN_GROUP_DUPLICATE",`${a}/code`),o.add(i.code),i.label===i.code&&u("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${a}/label`),i.items.forEach((s,l)=>{let p=`${a}/items/${l}`,_=Fn(s.page),d=t.get(_);(!d||d.navigationEligible!==!0)&&u("NATIVE_ADMIN_PAGE_NOT_FOUND",`${p}/page`),n.has(_)&&u("NATIVE_ADMIN_PAGE_DUPLICATE",`${p}/page`),n.add(_);let c=s.page.resourceCode||s.page.routeCode||s.page.workflowCode||_,A=s.label||d.label;(!A||A===c||A===_)&&u("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${p}/label`)})})}function Fi(e,t){let o=h(e,t,K.adminPages),n=new Set;o.forEach((i,r)=>{let a=`${t}/${r}`,s=I(i,a);C(s,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],a,!0);let l=$(s.code,`${a}/code`,255);n.has(l)&&u("NATIVE_ADMIN_PAGE_DUPLICATE",`${a}/code`),n.add(l);let p=$(s.kind,`${a}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(p)||u("NATIVE_ADMIN_PAGE_KIND_INVALID",`${a}/kind`),se(s.path,`${a}/path`),$(s.label,`${a}/label`,255),De(s.navigationEligible,`${a}/navigationEligible`),s.capability!==void 0&&s.access!==void 0&&u("NATIVE_ROUTE_ACCESS_CONFLICT",`${a}/access`),s.capability!==void 0&&$(s.capability,`${a}/capability`,255),s.access!==void 0){let _=I(s.access,`${a}/access`);C(_,["allOf","anyOf"],`${a}/access`,!0);for(let d of["allOf","anyOf"])_[d]!==void 0&&F(_[d],`${a}/access/${d}`,50)}for(let _ of["resourceCode","viewCode","routeCode"])s[_]!==void 0&&y(s[_],`${a}/${_}`)})}function vi(e,t){let o=h(e,t,K.adminNavigationGroups),n=0;o.forEach((i,r)=>{let a=`${t}/${r}`,s=I(i,a);C(s,["code","label","icon","order","items"],a,!0),y(s.code,`${a}/code`),$(s.label,`${a}/label`,255),He(s.icon,`${a}/icon`),Z(s.order,`${a}/order`,-1e4,1e4);let l=h(s.items,`${a}/items`,500);l.length===0&&u("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),n+=l.length,n>K.adminNavigationItems&&u("NATIVE_ARRAY_LIMIT_EXCEEDED",t),l.forEach((p,_)=>{let d=`${a}/items/${_}`,c=I(p,d);C(c,["pageCode","label","icon","order"],d,!0),$(c.pageCode,`${d}/pageCode`,255),c.label!==void 0&&$(c.label,`${d}/label`,255),He(c.icon,`${d}/icon`),Z(c.order,`${d}/order`,-1e4,1e4)})})}var Li=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function ki(e,t,o){let n=I(e,t);C(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),v(n.schemaVersion,Dn,`${t}/schemaVersion`),v(n.appCode,o,`${t}/appCode`),Rt(n.devicePolicy,`${t}/devicePolicy`),xi(n.rootEntry,`${t}/rootEntry`),Ui(n.authentication,`${t}/authentication`),$t(n.digest,`${t}/digest`);let i=h(n.routes,`${t}/routes`,K.routes),r=new Set;i.forEach((a,s)=>{let l=`${t}/routes/${s}`,p=I(a,l),_=p.kind==="resource-records"||p.kind==="resource-submit";C(p,["code","kind","desktop","mobile"],l,["workflowCode",..._?["resourceCode"]:[]]);let d=$(p.code,`${l}/code`,255);r.has(d)&&u("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${l}/code`),r.add(d);let c=$(p.kind,`${l}/kind`,64);if(Li.has(c)||u("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${l}/kind`),p.workflowCode!==void 0&&y(p.workflowCode,`${l}/workflowCode`),_){let E=G(p.resourceCode,`${l}/resourceCode`);v(d,`user.${E}.${p.kind==="resource-records"?"records":"submit"}`,`${l}/code`)}else p.resourceCode!==void 0&&u("NATIVE_PROPERTY_UNKNOWN",`${l}/resourceCode`);let A=En(p.desktop,`${l}/desktop`,o),f=En(p.mobile,`${l}/mobile`,o);A.surface!=="user"&&u("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${l}/desktop/surface`),f.surface!=="user"&&u("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${l}/mobile/surface`),A.routeCode===f.routeCode&&u("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",l)}),v(n.digest,X({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function Rt(e,t){let o=I(e,t);C(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),v(o.kind,"viewport-family",`${t}/kind`);let n=Z(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),i=Z(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return i!==n+1&&u("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:i}}function xi(e,t){let o=I(e,t);C(o,["code","desktop","mobile"],t);let n=y(o.code,`${t}/code`),i=Ot(o.desktop,`${t}/desktop`),r=Ot(o.mobile,`${t}/mobile`);return(i===r||r==="/"||!r.startsWith("/m/"))&&u("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),i.startsWith("/m/")&&u("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:i,mobile:r}}function Ui(e,t){let o=I(e,t);C(o,["desktop","mobile"],t);let n=_n(o.desktop,`${t}/desktop`,!1),i=_n(o.mobile,`${t}/mobile`,!0);return(n.routeCode===i.routeCode||n.path===i.path)&&u("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:i}}function _n(e,t,o){let n=I(e,t);C(n,["routeCode","path"],t);let i=y(n.routeCode,`${t}/routeCode`),r=Ot(n.path,`${t}/path`);return(o?!r.startsWith("/m/"):r.startsWith("/m/"))&&u("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:i,path:r}}function Ot(e,t){let o=se(e,t);return/[:*?#\\\\]/.test(o)&&u("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function En(e,t,o){let n=I(e,t);C(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),y(n.routeCode,`${t}/routeCode`);let i=se(n.path,`${t}/path`),r=$(n.surface,`${t}/surface`,16);["admin","user"].includes(r)||u("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let a=F(n.pathParams,`${t}/pathParams`,8);return a.forEach((s,l)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(s)||s.length>64)&&u("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${l}`)}),H(a)!==H(vn(i))&&u("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),Dt(n,t,o),n.requiresAuthentication!==!0&&u("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function vn(e){return U([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function An(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:vn(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function In(e,t,o,n){return e==="workflow-launch"?`workflow.${o}.launch.${t}`:e==="application-todo-center"?`application.todo-center.${t}`:e==="resource-records"?`user.${n}.records.${t}`:e==="resource-submit"?`user.${n}.submit.${t}`:`${e.replace(/-/g,".")}.${t}`}function Mi(e){let t=e.appCode,o=[],n=(A,f,E,N,m,g,T)=>{o.push({code:A,kind:f,...m?{workflowCode:m}:{},...T?{resourceCode:T}:{},desktop:An(In(f,"desktop",m,T),E,"user",g),mobile:An(In(f,"mobile",m,T),N,"user",g)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let i=Ln(e);i.length>0&&(n("workflow:work-center","workflow-work-center","/work-center","/m/work-center"),n("workflow:task","workflow-task","/tasks/:taskId","/m/tasks/:taskId"),n("workflow:instance","workflow-instance","/workflows/:instanceId","/m/workflows/:instanceId"));for(let A of i){if(!["standalone","hidden-handoff"].includes(A.launch.mode))continue;let f=U([A.launch.submission?.create?.requiredCapability,A.launch.submission?.existing?.requiredCapability].filter(E=>!!E));n(`workflow:${A.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",A.code,f.length===1?{capability:f[0]}:f.length>1?{access:{anyOf:f}}:void 0)}let r=o.sort((A,f)=>ie(String(A.code),String(f.code))),a=qe(e),s=A=>{let f=A==="mobile"?"/m/":"/",E=a.filter(m=>m.surface==="user"&&!/[:*?#\\\\]/.test(m.path)&&m.path===f).sort((m,g)=>ie(m.code,g.code))[0];if(E)return{code:E.code,path:E.path};let N=a.filter(m=>m.surface==="user"&&!/[:*?#\\\\]/.test(m.path)&&(A==="mobile"?m.path.startsWith("/m/"):!m.path.startsWith("/m/"))).sort((m,g)=>ie(m.code,g.code))[0];return N?{code:N.code,path:N.path}:{code:A==="mobile"?"application-root-mobile":"application-root",path:f}},l=e.frontend.authentication?{desktop:{routeCode:e.frontend.authentication.surfaces.desktop.routeCode,path:e.frontend.authentication.surfaces.desktop.path},mobile:{routeCode:e.frontend.authentication.surfaces.mobile.routeCode,path:e.frontend.authentication.surfaces.mobile.path}}:{desktop:{routeCode:"application-login",path:"/login"},mobile:{routeCode:"application-login-mobile",path:"/m/login"}},p=Rt(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),_=s("desktop"),d=s("mobile"),c={schemaVersion:Dn,appCode:t,devicePolicy:p,rootEntry:{code:_.code,desktop:_.path,mobile:d.path},authentication:l,routes:r};return{...c,digest:X(c)}}function He(e,t){if(e===void 0)return;let o=$(e,t,32);ti.has(o)||u("NATIVE_ADMIN_ICON_INVALID",t)}function mn(e,t){e!==void 0&&Z(e,t,-1e4,1e4)}function Dt(e,t,o){return e.capability!==void 0&&e.access!==void 0&&u("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:Ae(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:Xe(e.access,`${t}/access`,o)}}function Xe(e,t,o){let n=I(e,t);C(n,["allOf","anyOf"],t,!0);let i=n.allOf===void 0?void 0:U(F(n.allOf,`${t}/allOf`,50).map((a,s)=>Ae(a,`${t}/allOf/${s}`,o))),r=n.anyOf===void 0?void 0:U(F(n.anyOf,`${t}/anyOf`,50).map((a,s)=>Ae(a,`${t}/anyOf/${s}`,o)));return(i?.length||0)+(r?.length||0)===0&&u("NATIVE_ROUTE_ACCESS_EMPTY",t),{...i===void 0?{}:{allOf:i},...r===void 0?{}:{anyOf:r}}}function Ln(e){let t=new Map(Sn(e).map(i=>[String(i.code),i])),o=e.workflows.definitions.map((i,r)=>{let a=`/config/workflows/definitions/${r}`,s=I(i,a);C(s,["version","definition","launch"],a,["detailRouteCode"]);let l=I(s.definition,`${a}/definition`),p=s.detailRouteCode===void 0?void 0:xn(s.detailRouteCode,`${a}/detailRouteCode`);return{code:y(l.code,`${a}/definition/code`),title:$(l.title,`${a}/definition/title`,255),version:Re(s.version,`${a}/version`),launch:ji(e,l,s.launch,`${a}/launch`,t),...p?{detailRouteCode:p}:{},definition:l}});return U(o.map(i=>i.code)).map(i=>{let r=o.filter(p=>p.code===i),a=e.workflows.activations.find(p=>p.workflowCode===i)?.definitionVersion,s=r.find(p=>p.version===a)||[...r].sort((p,_)=>_.version-p.version)[0],l=new Set;for(let p of r){let _=I(p.definition.nodes,"/config/workflows/definitions/nodes");for(let d of Object.values(_)){let c=I(d,"/config/workflows/definitions/nodes/*");if(c.kind==="approval")for(let A of F(c.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))l.add(A)}}return{code:i,title:s.title,acceptedCommandDeactivationPolicy:s.definition.acceptedCommandDeactivationPolicy,subject:s.definition.subject,launch:s.launch,...["standalone","hidden-handoff"].includes(s.launch.mode)&&!s.launch.submission?{processOperationCode:`openxiangda.workflow.${i}.submit`}:{},...s.detailRouteCode?{detailRouteCode:s.detailRouteCode}:{},definitionVersions:hn(r.map(p=>p.version)),bindingVersions:hn(e.workflows.bindings.map((p,_)=>{let d=`/config/workflows/bindings/${_}`,c=I(p,d),A=I(c.binding,`${d}/binding`);return{code:y(A.workflowCode,`${d}/binding/workflowCode`),version:Re(c.version,`${d}/version`)}}).filter(p=>p.code===i).map(p=>p.version)),providerCodes:U(e.workflows.providers.map((p,_)=>y(I(p,`/config/workflows/providers/${_}`).code,`/config/workflows/providers/${_}/code`))),allowedOperations:[...l].sort(ie),editableParameterCodes:U(e.workflows.editableParameters.map((p,_)=>{let d=`/config/workflows/editableParameters/${_}`,c=I(p,d);return{code:y(c.code,`${d}/code`),workflowCode:y(c.workflowCode,`${d}/workflowCode`)}}).filter(p=>p.workflowCode===i).map(p=>p.code))}})}function kn(e,t){let o=I(e,t);C(o,["mode"],t,["submission"]);let n=$(o.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(n)||u("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:n,...o.submission===void 0?{}:{submission:I(o.submission,`${t}/submission`)}}}function ji(e,t,o,n,i){let r=kn(o,n);if(!r.submission)return{mode:r.mode};["standalone","hidden-handoff"].includes(r.mode)||u("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let a=I(r.submission,`${n}/submission`);C(a,["kind"],`${n}/submission`,["create","existing","context"]),v(a.kind,"named-operation",`${n}/submission/kind`);let s=n.endsWith("/launch")?n.slice(0,-7):n,l=I(t.subject,`${s}/definition/subject`),p=G(l.resourceCode,`${s}/definition/subject/resourceCode`),_=e.data.resources.findIndex(O=>O.code===p),d=e.data.resources[_];(_<0||!d)&&u("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${s}/definition/subject/resourceCode`);let c=new Set(I(d.schema,`/config/data/resources/${_}/schema`).fields.map(O=>String(O.code))),A=new Map(e.backend.operations.map(O=>[String(O.code),O])),f=(O,V)=>{let w=`${n}/submission/${V}`,x=I(O,w);C(x,["operationCode","inputs","output"],w);let M=y(x.operationCode,`${w}/operationCode`),ee=A.get(M),B=i.get(M),Ie=B?.platformAccess?.workflow?.codes;(!ee||!B||B.method!=="POST"||!Array.isArray(Ie)||!Ie.includes(t.code))&&u("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",w);let ge=I(ee.requestSchema,`${w}/operation/requestSchema`),q=I(ge.properties,`${w}/operation/requestSchema/properties`),Te=new Set(ge.required===void 0?[]:F(ge.required,`${w}/operation/requestSchema/required`,64)),me=I(x.inputs,`${w}/inputs`),S=Object.entries(me);(!S.length||S.length>64)&&u("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${w}/inputs`);let k=new Set,L=new Map,W={};for(let[j,Y]of S){(!un.test(j)||!Object.prototype.hasOwnProperty.call(q,j))&&u("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${w}/inputs/${j}`);let Ce=`${w}/inputs/${j}`,Ze=I(Y,Ce),Ne=$(Ze.source,`${Ce}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(Ne)||u("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",Ce),C(Ze,["source"],Ce,Ne==="field"?["fieldCode"]:!1),L.set(Ne,(L.get(Ne)||0)+1),Ne==="field"){let xe=z(Ze.fieldCode,`${Ce}/fieldCode`);(k.has(xe)||!c.has(xe))&&u("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${Ce}/fieldCode`),k.add(xe),W[j]={source:Ne,fieldCode:xe}}else W[j]={source:Ne}}([...Te].some(j=>!(j in me))||(L.get("idempotency-key")||0)!==1||!S.some(([j,Y])=>I(Y,`${w}/inputs/${j}`).source==="idempotency-key"&&Te.has(j))||V==="create"&&((L.get("subject-id")||0)>0||(L.get("subject-revision")||0)>0)||V==="existing"&&((L.get("subject-id")||0)!==1||(L.get("subject-revision")||0)!==1))&&u("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${w}/inputs`);let J=I(x.output,`${w}/output`);C(J,["subjectId"],`${w}/output`,["subjectRevision","processCommand"]);let de=I(I(ee.responseSchema,`${w}/operation/responseSchema`).properties,`${w}/operation/responseSchema/properties`);for(let j of["subjectId","subjectRevision","processCommand"]){if(J[j]===void 0)continue;let Y=$(J[j],`${w}/output/${j}`,128);(!un.test(Y)||!Object.prototype.hasOwnProperty.call(de,Y))&&u("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${w}/output/${j}`)}return{operationCode:M,method:"POST",path:B.path,requiredCapability:B.requiredCapability,requestSchemaDigest:B.requestSchemaDigest,responseSchemaDigest:B.responseSchemaDigest,inputs:W,output:{...J},fieldCodes:k}},E=a.create===void 0?void 0:f(a.create,"create"),N=a.existing===void 0?void 0:f(a.existing,"existing");!E&&!N&&u("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let m=new Set([...E?.fieldCodes||[],...N?.fieldCodes||[]]),g=a.context===void 0?[]:h(a.context,`${n}/submission/context`,16),T=new Set,D=g.map((O,V)=>{let w=`${n}/submission/context/${V}`,x=I(O,w);C(x,["queryParameter","fieldCode"],w);let M=$(x.queryParameter,`${w}/queryParameter`,64),ee=z(x.fieldCode,`${w}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(M)||T.has(M)||!m.has(ee))&&u("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",w),T.add(M),{queryParameter:M,fieldCode:ee}}),b=O=>{let{fieldCodes:V,...w}=O;return w};return{mode:r.mode,submission:{kind:"named-operation",...E?{create:b(E)}:{},...N?{existing:b(N)}:{},context:D}}}function xn(e,t){let o=I(e,t);C(o,["desktop","mobile"],t);let n=y(o.desktop,`${t}/desktop`),i=y(o.mobile,`${t}/mobile`);return n===i&&u("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:i}}function Wi(e,t){let o=new Set(t.map(_=>_.code)),n=new Map;e.data.resources.forEach((_,d)=>{let c=`/config/data/resources/${d}`,A=I(_,c);for(let[N,m]of Object.entries(A.fieldPolicies||{})){if(!Se(N))continue;let g=`${c}/fieldPolicies/${N}/read`,T=I(m,`${c}/fieldPolicies/${N}`);for(let D of F(T.read||[],g,2e3))o.has(D)||u("NATIVE_CAPABILITY_REFERENCE_MISSING",g)}if(((A.surface===void 0?{}:I(A.surface,`${c}/surface`)).mutationOwner||"native")==="native")return;let E=I(A.capabilities,`${c}/capabilities`);for(let N of["create","update","delete"])n.set(String(E[N]),N)});let i=new Set;for(let[_,d]of e.authz.roles.entries()){let c=`/config/authz/roles/${_}`,A=I(d,c);C(A,["code","name","description","capabilities"],c,!0);let f=y(A.code,`${c}/code`);i.has(f)&&u("NATIVE_ROLE_DUPLICATE",`${c}/code`),i.add(f),$(A.name,`${c}/name`,255);let E=F(A.capabilities,`${c}/capabilities`,2e3);for(let[N,m]of E.entries())n.has(m)&&u("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${c}/capabilities/${N}`,{operation:n.get(m)}),o.has(m)||u("NATIVE_CAPABILITY_REFERENCE_MISSING",`${c}/capabilities`)}let r=e.authz.authenticatedUserRoleCode===void 0?"":y(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");r&&!i.has(r)&&u("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let a=new Set,s=0;for(let[_,d]of e.perspectives.entries()){let c=`/config/perspectives/${_}`,A=I(d,c);C(A,["code","name","description","roleCodes","capabilityCodes","default"],c,!0);let f=y(A.code,`${c}/code`);a.has(f)&&u("NATIVE_PERSPECTIVE_DUPLICATE",`${c}/code`),a.add(f),$(A.name,`${c}/name`,255);let E=F(A.roleCodes,`${c}/roleCodes`,20);E.length<1&&u("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${c}/roleCodes`),E.forEach((g,T)=>{i.has(g)||u("NATIVE_PERSPECTIVE_ROLE_MISSING",`${c}/roleCodes/${T}`)});let N=U(e.authz.roles.filter(g=>E.includes(g.code)).flatMap(g=>g.capabilities)),m=F(A.capabilityCodes,`${c}/capabilityCodes`,2e3);H(N)!==H(m)&&u("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${c}/capabilityCodes`),A.default===!0?s+=1:A.default!==void 0&&u("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${c}/default`)}s>1&&u("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[_,d]of e.backend.operations.entries()){let c=I(d,`/config/backend/operations/${_}`);o.has(c.capability)||u("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${_}/capability`)}let l=new Set,p=new Set;for(let[_,d]of e.frontend.routes.entries()){let c=`/config/frontend/routes/${_}`,A=I(d,c),f=y(A.code,`${c}/code`);l.has(f)&&u("NATIVE_ROUTE_DUPLICATE",`${c}/code`),l.add(f);let E=se(A.path,`${c}/path`);p.has(E)&&u("NATIVE_ROUTE_PATH_DUPLICATE",`${c}/path`),p.add(E);let N=Dt(A,c,e.appCode);N.capability&&!o.has(N.capability)&&u("NATIVE_CAPABILITY_REFERENCE_MISSING",`${c}/capability`);let m=A.access===void 0?void 0:I(A.access,`${c}/access`);for(let g of["allOf","anyOf"]){let T=m?.[g]===void 0?[]:h(m[g],`${c}/access/${g}`,50);for(let[D,b]of T.entries()){let O=Ae(b,`${c}/access/${g}/${D}`,e.appCode);o.has(O)||u("NATIVE_CAPABILITY_REFERENCE_MISSING",`${c}/access/${g}/${D}`)}}}if(e.frontend.admin.access!==void 0){let _=Xe(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let d of["allOf","anyOf"])for(let[c,A]of(_[d]||[]).entries())o.has(A)||u("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${d}/${c}`)}for(let[_,d]of e.frontend.routes.entries()){let c=I(d,`/config/frontend/routes/${_}`);c.parentCode&&!l.has(c.parentCode)&&u("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${_}/parentCode`)}}function Bi(e){let t=new Set(e.authz.roles.map(p=>String(p.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":y(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(p=>[String(p.code),{valueType:p.valueType==="uuid"?"uuid":"string",...p.valueSource?.resourceCode?{valueSourceResourceCode:String(p.valueSource.resourceCode)}:{}}])),i=new Set(n.keys()),r=new Map(e.data.resources.map((p,_)=>{let d=ke(p,`/config/data/resources/${_}`,e.appCode);return[d.code,new Map(d.schema.fields.map(c=>[String(c.code),c]))]}));for(let[p,_]of e.authz.scopeDimensions.entries()){let d=`/config/authz/scopeDimensions/${p}`,c=I(_,d);if(C(c,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],d,!0),c.valueSource===void 0)continue;let A=I(c.valueSource,`${d}/valueSource`);C(A,["kind","resourceCode","labelField","enabledField"],`${d}/valueSource`,!0),A.kind!=="native_resource"&&u("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${d}/valueSource/kind`),c.valueType!=="uuid"&&u("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${d}/valueType`);let f=G(A.resourceCode,`${d}/valueSource/resourceCode`),E=r.get(f);E||u("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${d}/valueSource/resourceCode`);let N=z(A.labelField,`${d}/valueSource/labelField`);if(["text.short","text.long"].includes(String(E.get(N)?.type||""))||u("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${d}/valueSource/labelField`),A.enabledField!==void 0){let m=z(A.enabledField,`${d}/valueSource/enabledField`);E.get(m)?.type!=="boolean"&&u("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${d}/valueSource/enabledField`)}}let a=new Set,s=new Set;for(let[p,_]of e.authz.scopeSources.entries()){let d=`/config/authz/scopeSources/${p}`,c=I(_,d);C(c,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],d,!0);let A=y(c.code,`${d}/code`);a.has(A)&&u("NATIVE_SCOPE_SOURCE_DUPLICATE",`${d}/code`),a.add(A),$(c.name,`${d}/name`,255);let f=G(c.resourceCode,`${d}/resourceCode`),E=r.get(f);E||u("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${d}/resourceCode`);let N=I(c.subject,`${d}/subject`),m=$(N.type,`${d}/subject/type`,32);C(N,m==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${d}/subject`),["user","role_membership"].includes(m)||u("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${d}/subject/type`);let g=Ve(N.userIdField,E);At(g)||u("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${d}/subject/userIdField`),m==="role_membership"&&!t.has(String(N.roleCode))&&u("NATIVE_ROLE_REFERENCE_MISSING",`${d}/subject/roleCode`);let T=new Set;for(let[D,b]of h(c.grants,`${d}/grants`,100).entries()){let O=`${d}/grants/${D}`,V=I(b,O);C(V,["dimensionCode","valueField","parentValueField"],O,!0);let w=y(V.dimensionCode,`${O}/dimensionCode`);(!i.has(w)||T.has(w))&&u("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${O}/dimensionCode`),T.add(w),c.failureMode==="last_known_good"&&s.add(w);for(let x of["valueField","parentValueField"]){if(V[x]===void 0)continue;let M=Ve(V[x],E);en(M,n.get(w),r)||u("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${O}/${x}`)}}T.size===0&&u("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${d}/grants`),["strict","last_known_good"].includes(c.failureMode)||u("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${d}/failureMode`);for(let D of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(c[D]===void 0)continue;let b=z(c[D],`${d}/${D}`);E.has(b)||u("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${d}/${D}`)}}Gi(e,t,r,o);let l=new Set;for(let[p,_]of e.authz.dataPolicies.entries()){let d=`/config/authz/dataPolicies/${p}`,c=I(_,d);C(c,["code","name","resourceCode","unrestrictedRoleCodes","operations","matchMode","rules","readExpression","writeBoundary"],d,!0);let A=y(c.code,`${d}/code`);l.has(A)&&u("NATIVE_DATA_POLICY_DUPLICATE",`${d}/code`),l.add(A);let f=c.readExpression!==void 0,E=F(c.operations||[],`${d}/operations`,4);c.operations!==void 0&&(E.length===0||E.some(b=>!["read","create","update","delete"].includes(b)))&&u("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${d}/operations`),["AND","OR"].includes(c.matchMode)||u("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${d}/matchMode`),f&&c.operations!==void 0&&u("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${d}/operations`);let N=e.data.resources.find(b=>b.dataPolicyCode===A),m=c.resourceCode||N?.code,g=m?r.get(G(m,`${d}/resourceCode`)):void 0;f&&!g&&u("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${d}/resourceCode`);let T=F(c.unrestrictedRoleCodes||[],`${d}/unrestrictedRoleCodes`,100);c.unrestrictedRoleCodes!==void 0&&T.length===0&&u("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${d}/unrestrictedRoleCodes`);for(let b of T)t.has(b)||u("NATIVE_ROLE_REFERENCE_MISSING",`${d}/unrestrictedRoleCodes`);let D;try{let b=h(c.rules,`${d}/rules`,100).map((O,V)=>({rule:I(O,`${d}/rules/${V}`),pointer:`${d}/rules/${V}`}));b.length===0?(!f||c.matchMode!=="AND"||c.writeBoundary!=="capability_only")&&u("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",d):c.writeBoundary!==void 0&&u("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${d}/writeBoundary`),D=[...b],f&&(D.push(...ze(c.readExpression,`${d}/readExpression`)),cn(c.readExpression,`${d}/readExpression`))}catch(b){throw b instanceof Fe&&u(b.code,b.pointer),b}for(let{rule:b,pointer:O}of D){C(b,["subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],O,!0);let V=z(b.field,`${O}/field`),w=g?.get(V);f&&!w&&u("NATIVE_DATA_POLICY_FIELD_MISSING",`${O}/field`);for(let q of F(b.roleCodes||[],`${O}/roleCodes`,100))t.has(q)||u("NATIVE_ROLE_REFERENCE_MISSING",`${O}/roleCodes`);let x=String(b.operator||""),M=b.operand==="db_now",ee=["is_null","is_not_null"].includes(x),B=["eq","not_eq","in","not_in"].includes(x),Ie=!M&&(b.operator!==void 0||b.value!==void 0);if([b.subject==="current_user"?"current_user":"",typeof b.dimensionCode=="string"?"dimension":"",typeof b.relationCode=="string"?"relationship":"",Ie?"constant":"",M?"db_now":""].filter(Boolean).length!==1&&u("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",O),b.subject!==void 0&&b.subject!=="current_user"&&u("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${O}/subject`),Ie){if(!B&&!ee&&u("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${O}/operator`),["in","not_in"].includes(x)){let q=h(b.value,`${O}/value`,100).map((Te,me)=>$(Te,`${O}/value/${me}`,2048));(q.length===0||new Set(q).size!==q.length)&&u("NATIVE_DATA_POLICY_VALUE_INVALID",`${O}/value`)}else["eq","not_eq"].includes(x)?$(b.value,`${O}/value`,2048):(b.value!==void 0||b.operand!==void 0)&&u("NATIVE_DATA_POLICY_VALUE_INVALID",`${O}/value`);for(let q of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])b[q]!==void 0&&u("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${O}/${q}`)}if(M){(!["lt","lte","gt","gte"].includes(x)||b.value!==void 0||w?.type!=="datetime")&&u("NATIVE_DATA_POLICY_DB_NOW_INVALID",O);for(let q of["operation","valuePath","emptyMatchesAll","resourceCode","value"])b[q]!==void 0&&u("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${O}/${q}`)}b.dimensionCode&&!i.has(b.dimensionCode)&&u("NATIVE_SCOPE_DIMENSION_MISSING",`${O}/dimensionCode`),s.has(String(b.dimensionCode||""))&&b.operation!=="read"&&u("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${O}/operation`)}}for(let[p,_]of e.data.resources.entries()){let d=I(_,`/config/data/resources/${p}`);d.dataPolicyCode&&!l.has(d.dataPolicyCode)&&u("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${p}/dataPolicyCode`)}}function Ji(e){try{kt(e.data.resources,"/config/data/resources")}catch(t){throw t instanceof ue&&u(t.code,t.pointer),t}}function Gi(e,t,o,n){let i=new Set;for(let[r,a]of e.authz.roleMembershipSources.entries()){let s=`/config/authz/roleMembershipSources/${r}`,l=I(a,s);C(l,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let p=y(l.code,`${s}/code`);p.length>100&&u("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),i.has(p)&&u("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),i.add(p),$(l.name,`${s}/name`,255);let _=Nn(l.resourceCode,`${s}/resourceCode`,o);gn(l.userIdField,`${s}/userIdField`,_),t.has(String(l.roleCode||""))||u("NATIVE_ROLE_REFERENCE_MISSING",`${s}/roleCode`),n&&l.roleCode===n&&u("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${s}/roleCode`),Tn(l,s,_)}for(let[r,a]of e.authz.relationshipGrantSources.entries()){let s=`/config/authz/relationshipGrantSources/${r}`,l=I(a,s);C(l,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let p=y(l.code,`${s}/code`);p.length>100&&u("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),i.has(p)&&u("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),i.add(p),$(l.name,`${s}/name`,255);let _=Nn(l.resourceCode,`${s}/resourceCode`,o),d=I(l.subject,`${s}/subject`),c=$(d.type,`${s}/subject/type`,32);C(d,c==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${s}/subject`),["user","role_membership"].includes(c)||u("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${s}/subject/type`),gn(d.userIdField,`${s}/subject/userIdField`,_),c==="role_membership"&&!t.has(String(d.roleCode||""))&&u("NATIVE_ROLE_REFERENCE_MISSING",`${s}/subject/roleCode`),y(l.relationCode,`${s}/relationCode`);let A=G(l.targetResourceCode,`${s}/targetResourceCode`);o.has(A)||u("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${s}/targetResourceCode`);let f=Ve(l.resourceIdField,_),E=f?.field.type==="resource-ref.single"&&f.valuePath==="value"&&f.field.source?.resourceCode===A;(l.resourceIdField==="id"?A!==String(l.resourceCode):!E)&&u("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${s}/resourceIdField`);let N=F(l.operations,`${s}/operations`,20);(N.length===0||N.some(m=>m.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(m)))&&u("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${s}/operations`),Tn(l,s,_)}}function Nn(e,t,o){let n=G(e,t),i=o.get(n);return i||u("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),i}function gn(e,t,o){let n=Ve(e,o);At(n)||u("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function Tn(e,t,o){if(e.failureMode!=="strict"&&u("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=z(e.enabledField,`${t}/enabledField`);o.get(n)?.type!=="boolean"&&u("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let n of["effectiveFromField","effectiveToField"]){if(e[n]===void 0)continue;let i=z(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(i)?.type))||u("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function zi(e){let t=new Set,o=new Set;e.forEach((n,i)=>{let r=`/config/backend/secrets/${i}`,a=I(n,r);C(a,["name","env","description","required","exposure"],r,!0);let s=$(a.name,`${r}/name`,128),l=$(a.env,`${r}/env`,128);Yo.test(s)||u("NATIVE_SECRET_NAME_INVALID",`${r}/name`),(!Ho.test(l)||l.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(l))&&u("NATIVE_SECRET_ENV_INVALID",`${r}/env`),t.has(s)&&u("NATIVE_SECRET_NAME_DUPLICATE",`${r}/name`),o.has(l)&&u("NATIVE_SECRET_ENV_DUPLICATE",`${r}/env`),t.add(s),o.add(l),v(a.exposure,"active_only",`${r}/exposure`),a.required!==void 0&&De(a.required,`${r}/required`),a.description!==void 0&&St(a.description,`${r}/description`,2e3)})}function Yi(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(c=>[String(c.code),c])),i=new Map(e.frontend.routes.map((c,A)=>{let f=I(c,`/config/frontend/routes/${A}`);return[y(f.code,`/config/frontend/routes/${A}/code`),f]}));for(let[c,A]of e.workflows.definitions.entries()){let f=`/config/workflows/definitions/${c}`,E=I(A,f);if(C(E,["version","definition","launch"],f,["detailRouteCode"]),kn(E.launch,`${f}/launch`),E.detailRouteCode!==void 0){let T=xn(E.detailRouteCode,`${f}/detailRouteCode`);for(let[D,b,O]of[["desktop",T.desktop,"admin"],["mobile",T.mobile,"user"]]){let V=`${f}/detailRouteCode/${D}`,w=i.get(b);w||u("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",V),w.surface!==O&&u("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",V);let x=se(w.path,V),M=[...x.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(ee=>ee[1]);(x.includes("*")||M.length!==1||M[0]!=="instanceId")&&u("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",V)}}let N=I(E.definition,`${f}/definition`),m=`${N.code}:${Re(E.version,`${f}/version`)}`;t.has(m)&&u("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",f),t.add(m),Ki(N,`${f}/definition`),Hi(N.subject,n,`${f}/definition/subject`);let g=sn(N,{appCode:e.appCode,capabilities:e.authz.capabilities.map(T=>T.code),fields:new Map((n.get(N.subject.resourceCode)?.schema.fields||[]).map(T=>[T.code,T]))});g.length&&u("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${f}/definition/instanceCommands`,{errors:g}),N.title===N.code&&u("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${f}/definition/title`),o.set(m,N)}let r=new Set,a=new Map;for(let[c,A]of e.workflows.bindings.entries()){let f=I(A,`/config/workflows/bindings/${c}`),E=I(f.binding,`/config/workflows/bindings/${c}/binding`),N=`${E.workflowCode}:${Re(f.version,`/config/workflows/bindings/${c}/version`)}`;r.has(N)&&u("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${c}`),r.add(N),qi(E,`/config/workflows/bindings/${c}/binding`),a.set(N,E)}let s=new Set,l=new Map;for(let[c,A]of e.workflows.activations.entries()){let f=`/config/workflows/activations/${c}`,E=I(A,f);C(E,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],f,["environmentKey"]);let N=y(E.workflowCode,`${f}/workflowCode`);s.has(N)&&u("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",f),s.add(N);let m=`${N}:${Re(E.definitionVersion,`${f}/definitionVersion`)}`,g=`${N}:${Re(E.bindingVersion,`${f}/bindingVersion`)}`;t.has(m)||u("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${f}/definitionVersion`),r.has(g)||u("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${f}/bindingVersion`);let T=o.get(m),D=a.get(g);(!["finish-pinned","cancel-on-deactivate"].includes(E.acceptedCommandDeactivationPolicy)||E.acceptedCommandDeactivationPolicy!==T.acceptedCommandDeactivationPolicy)&&u("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${f}/acceptedCommandDeactivationPolicy`),Xi(T,D,`/config/workflows/activations/${c}`),l.set(N,D)}let p=new Set;e.workflows.providers.forEach((c,A)=>{let f=`/config/workflows/providers/${A}`,E=I(c,f);C(E,["code","endpointPath","timeoutMs"],f,!0);let N=y(E.code,`${f}/code`);p.has(N)&&u("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${f}/code`),p.add(N),se(E.endpointPath,`${f}/endpointPath`),E.timeoutMs!==void 0&&Z(E.timeoutMs,`${f}/timeoutMs`,100,1e4)});for(let[c,A]of l.entries())for(let[f,E]of Object.entries(I(A.bindings,"/config/workflows/bindings/*/binding/bindings"))){let N=I(E,`/config/workflows/${c}/bindings/${f}`);N.provider==="application_provider"&&!p.has(N.providerCode)&&u("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${c}/bindings/${f}/providerCode`)}let _=new Set(e.authz.roles.map(c=>c.code)),d=new Set;e.workflows.editableParameters.forEach((c,A)=>{let f=`/config/workflows/editableParameters/${A}`,E=I(c,f);C(E,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],f,!0);let N=y(E.code,`${f}/code`);d.has(N)&&u("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${f}/code`),d.add(N);let m=Qe(E.workflowCode,`${f}/workflowCode`),g=yt(E.bindingKey,`${f}/bindingKey`),T=l.get(m);(!T||!I(T.bindings,`${f}/bindingKey`)[g])&&u("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${f}/bindingKey`),$(E.label,`${f}/label`,255),["role_code","user_ids","provider_code"].includes(E.valueType)||u("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${f}/valueType`);for(let D of F(E.allowedRoleCodes||[],`${f}/allowedRoleCodes`,100))_.has(D)||u("NATIVE_ROLE_REFERENCE_MISSING",`${f}/allowedRoleCodes`);for(let D of F(E.allowedProviderCodes||[],`${f}/allowedProviderCodes`,100))p.has(D)||u("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${f}/allowedProviderCodes`);E.required!==void 0&&De(E.required,`${f}/required`),E.maxItems!==void 0&&Z(E.maxItems,`${f}/maxItems`,1,200)})}function Hi(e,t,o){let n=I(e,o);C(n,["resourceCode","factProjection"],o,["summaryFields"]);let i=G(n.resourceCode,`${o}/resourceCode`),r=t.get(i);r||u("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let a=new Set(h(I(r.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((p,_)=>z(I(p,`${o}/resourceCode/${_}`).code,`${o}/resourceCode/${_}`))),s=I(n.factProjection,`${o}/factProjection`),l=Object.entries(s);(l.length<1||l.length>64)&&u("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[p,_]of l){Xo.test(p)||u("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${p}`);let d=z(_,`${o}/factProjection/${p}`);a.has(d)||u("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${p}`)}if(n.summaryFields!==void 0){let p=F(n.summaryFields,`${o}/summaryFields`,Qo).map((f,E)=>z(f,`${o}/summaryFields/${E}`)),_=t.get(i),d=_.surface&&typeof _.surface=="object"&&!Array.isArray(_.surface)?_.surface:{},c=d.fields&&typeof d.fields=="object"&&!Array.isArray(d.fields)?d.fields:{},A=new Map(h(I(_.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((f,E)=>{let N=I(f,`${o}/resourceCode/${E}`);return[String(N.code),N]}));for(let[f,E]of p.entries()){let N=A.get(E),m=c[E],g=String(N?.type||""),T=N?.maxLength;(!N||N.system===!0||m&&typeof m=="object"&&!Array.isArray(m)&&m.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(E)||!ei.has(g)||g==="text.long"&&typeof T=="number"&&Number.isFinite(T)&&T>Zo)&&u("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${f}`)}}}function Ki(e,t){C(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands"]),v(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),Qe(e.code,`${t}/code`),$(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||u("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=I(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&u("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let i=$(e.startAt,`${t}/startAt`,128);o[i]||u("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let r=new Map;for(let[p,_]of Object.entries(o)){let d=`${t}/nodes/${p}`,c=I(_,d);v(c.id,p,`${d}/id`),["approval","condition","end"].includes(c.kind)||u("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${d}/kind`);let A=[];if(c.kind==="approval"){$(c.title,`${d}/title`,255),yt(c.binding,`${d}/binding`),["single","any","all","sequence"].includes(c.mode)||u("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${d}/mode`),A.push($(c.onApprove,`${d}/onApprove`,128),$(c.onReject,`${d}/onReject`,128));for(let f of F(c.returnTargets||[],`${d}/returnTargets`,200))o[f]||u("NATIVE_WORKFLOW_TARGET_MISSING",`${d}/returnTargets`);for(let f of F(c.allowedOperations||[],`${d}/allowedOperations`,20))ni.has(f)||u("NATIVE_WORKFLOW_OPERATION_INVALID",`${d}/allowedOperations`)}else if(c.kind==="condition"){let f=h(c.branches,`${d}/branches`,100);f.length===0&&u("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${d}/branches`),f.forEach((E,N)=>{let m=I(E,`${d}/branches/${N}`);ve(m.when,`${d}/branches/${N}/when`,0),A.push($(m.target,`${d}/branches/${N}/target`,128))}),A.push($(c.otherwise,`${d}/otherwise`,128))}else $(c.title,`${d}/title`,255),$(c.outcome,`${d}/outcome`,128);for(let f of A)o[f]||u("NATIVE_WORKFLOW_TARGET_MISSING",d);r.set(p,A)}let a=new Set,s=new Set,l=p=>{if(s.has(p)&&u("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${p}`),!a.has(p)){a.add(p),s.add(p);for(let _ of r.get(p)||[])l(_);s.delete(p)}};l(i),a.size!==n.length&&u("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function ve(e,t,o){o>20&&u("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=I(e,t),i=$(n.op,`${t}/op`,16);if(i!=="literal"){if(i==="path"){let r=$(n.path,`${t}/path`,255);/^[A-Za-z][A-Za-z0-9_.]{0,254}$/.test(r)||u("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(i)){ve(n.left,`${t}/left`,o+1),ve(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(i)){let r=h(n.values,`${t}/values`,100);r.length===0&&u("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),r.forEach((a,s)=>ve(a,`${t}/values/${s}`,o+1));return}if(["not","exists"].includes(i)){ve(n.value,`${t}/value`,o+1);return}u("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function qi(e,t){v(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),Qe(e.workflowCode,`${t}/workflowCode`);let o=I(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&u("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,i]of Object.entries(o)){yt(n,`${t}/bindings/${n}`);let r=I(i,`${t}/bindings/${n}`),a=$(r.provider,`${t}/bindings/${n}/provider`,64);["fixed_users","initiator","input_users","form_field_users","department_supervisor","app_role","app_role_in_scope","business_relation","previous_node_actor","initiator_select","application_provider"].includes(a)||u("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${n}/provider`),a==="fixed_users"&&h(r.users,`${t}/bindings/${n}/users`,200).length===0&&u("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),["input_users","form_field_users"].includes(a)&&$(r.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(a)&&y(r.roleCode,`${t}/bindings/${n}/roleCode`),a==="department_supervisor"&&$(r.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),a==="application_provider"&&y(r.providerCode,`${t}/bindings/${n}/providerCode`)}}function Xi(e,t,o){v(t.workflowCode,e.code,`${o}/workflowCode`);let n=I(t.bindings,`${o}/bindings`);for(let[i,r]of Object.entries(I(e.nodes,`${o}/nodes`))){let a=I(r,`${o}/nodes/${i}`);a.kind==="approval"&&!n[a.binding]&&u("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${i}/binding`)}}function Qi(e,t,o){let n=I(t.routeManifest,"/contracts/routeManifest"),i=I(e.routeManifest,"/contracts/routeManifest"),r=new Map;for(let _ of h(o.data?.resources,"/config/data/resources",100)){let d=I(_,"/config/data/resources");r.set(String(d.code||""),d)}let a=new Set(h(i.routes,"/contracts/routeManifest/routes",1e3).map(_=>String(I(_,"/contracts/routeManifest/routes").code||""))),s=[];for(let _ of h(n.routes,"/contracts/routeManifest/routes",1e3)){let d=I(_,"/contracts/routeManifest/routes"),c=String(d.kind||"");if(c!=="resource-records"&&c!=="resource-submit")continue;let A=String(d.resourceCode||""),f=r.get(A);f||u("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let N=`user.${A}.${c==="resource-records"?"records":"submit"}`;v(String(d.code||""),N,"/contracts/routeManifest/routes/code");let m=c==="resource-records"?"read":"create",g=String(I(f.capabilities,"/config/data/resources/capabilities")[m]||"");for(let T of["desktop","mobile"]){let D=I(d[T],`/contracts/routeManifest/routes/${T}`),b=T==="mobile"?"/m/my/":"/my/",O=c==="resource-records"?`${b}${A}`:`${b}${A}/submit`;v(String(D.path||""),O,`/contracts/routeManifest/routes/${T}/path`),v(String(D.capability||""),g,`/contracts/routeManifest/routes/${T}/capability`),v(String(D.routeCode||""),`${N}.${T}`,`/contracts/routeManifest/routes/${T}/routeCode`)}(a.has(N)||s.some(T=>String(T.code)===N))&&u("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),s.push(d)}if(!s.length)return;i.routes=h([...i.routes,...s],"/contracts/routeManifest/routes",1e3).sort((_,d)=>ie(String(I(_,"x").code||""),String(I(d,"x").code||"")));let l=String(I(n.rootEntry,"x").code||"");if(s.find(_=>String(_.code)===l&&_.kind==="resource-records")){let _=I(n.rootEntry,"x");i.rootEntry={code:l,desktop:String(_.desktop||""),mobile:String(_.mobile||"")}}i.digest=X({schemaVersion:i.schemaVersion,appCode:i.appCode,devicePolicy:i.devicePolicy,rootEntry:i.rootEntry,authentication:i.authentication,routes:i.routes})}function ke(e,t,o){let n=I(e,t);C(n,["schemaVersion","appCode","code","name","schema","surface","invariants","capabilities","dataPolicyCode","fieldPolicies"],t,!0),v(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),v(n.appCode,o,`${t}/appCode`);let i=G(n.code,`${t}/code`),r=$(n.name,`${t}/name`,255),a=I(n.schema,`${t}/schema`);C(a,["fields"],`${t}/schema`);let s,l;try{s=it(a.fields,`${t}/schema/fields`),l=xt(n.invariants,s,`${t}/invariants`),ft(n.surface,s,`${t}/surface`)}catch(c){throw c instanceof ue&&u(c.code,c.pointer),c}let p=new Set(s.map(c=>c.code)),_=I(n.capabilities,`${t}/capabilities`);C(_,["read","create","update","delete"],`${t}/capabilities`);let d=I(n.fieldPolicies,`${t}/fieldPolicies`);for(let[c,A]of Object.entries(d)){!p.has(c)&&!Se(c)&&u("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${c}`);let f=`${t}/fieldPolicies/${c}`,E=I(A,f);Se(c)&&(C(E,["read"],f,!0),(!Array.isArray(E.read)||E.read.length>20||E.read.some(N=>typeof N!="string"||!N.trim())||new Set(E.read).size!==E.read.length)&&u("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${f}/read`)),C(E,["read","create","update","mask"],f,!0),E.mask!==void 0&&!["omit","null"].includes(E.mask)&&u("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${f}/mask`)}return{...n,code:i,name:r,schema:{fields:s},...n.invariants===void 0?{}:{invariants:l},capabilities:_,fieldPolicies:d}}function Un(e){return[{code:`app:${e}:directory:read`,kind:"platform",name:"\u8BFB\u53D6\u53D7\u9650\u7EC4\u7EC7\u76EE\u5F55",source:"platform"},...[["app:role:read","\u67E5\u770B\u89D2\u8272\u4E0E\u6388\u6743"],["app:role:define","\u5B9A\u4E49\u624B\u5DE5\u89D2\u8272"],["app:role:assign","\u5206\u914D\u89D2\u8272\u6210\u5458"],["app:role:grant-capability","\u6388\u4E88\u89D2\u8272\u80FD\u529B"],["app:scope-grant:manage","\u7BA1\u7406\u6570\u636E\u8303\u56F4"],["app:super-admin:manage","\u7BA1\u7406\u5E94\u7528\u6700\u9AD8\u7BA1\u7406\u5458"]].map(([t,o])=>({code:t,kind:"platform",name:o,source:"platform"}))]}function Cn(e,t,o,n){let i=e.toString("utf8"),r;try{r=JSON.parse(i)}catch{u(o,t)}let a=I(r,t);return H(a)!==i&&u(n,t),a}function bn(e,t){let o=0,n=(i,r,a)=>{if(o+=1,o>ri&&u("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",r),a>si&&u("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",r),typeof i=="string"){Buffer.byteLength(i)>gt&&u("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",r);return}if(Array.isArray(i)){i.forEach((s,l)=>n(s,`${r}/${l}`,a+1));return}if(!(!i||typeof i!="object"))for(let[s,l]of Object.entries(i))["__proto__","prototype","constructor"].includes(s)&&u("NATIVE_ARTIFACT_DANGEROUS_KEY",`${r}/${s}`),Zi(s)&&u("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${r}/${s}`),n(l,`${r}/${s}`,a+1)};n(e,t,0)}function Zi(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function he(e){return{value:e,digest:X(e)}}function On(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&u("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let i=Buffer.isBuffer(e)?e:Buffer.from(e);return i.byteLength===0&&u("NATIVE_ARTIFACT_EMPTY",o),i.byteLength>t&&u(n,o),i}function $n(e,t,o,n){let i=Ke.createHash("sha256").update(e).digest("hex");Ke.timingSafeEqual(Buffer.from(i),Buffer.from(t))||u(n,o)}function I(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&u("NATIVE_OBJECT_REQUIRED",t),e}function h(e,t,o){return Array.isArray(e)||u("NATIVE_ARRAY_REQUIRED",t),e.length>o&&u("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function F(e,t,o){let n=h(e,t,o).map((i,r)=>$(i,`${t}/${r}`,255));return new Set(n).size!==n.length&&u("NATIVE_ARRAY_DUPLICATE",t),n}function $(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&u("NATIVE_STRING_INVALID",t),e}function St(e,t,o){return(typeof e!="string"||e.length>o)&&u("NATIVE_STRING_INVALID",t),e}function y(e,t){let o=$(e,t,128);return Bo.test(o)||u("NATIVE_CODE_INVALID",t),o}function G(e,t){let o=$(e,t,64);return Go.test(o)||u("NATIVE_RESOURCE_CODE_INVALID",t),o}function z(e,t){let o=$(e,t,63);return zo.test(o)||u("NATIVE_FIELD_CODE_INVALID",t),o}function Qe(e,t){let o=$(e,t,128);return Ko.test(o)||u("NATIVE_WORKFLOW_CODE_INVALID",t),o}function yt(e,t){let o=$(e,t,128);return qo.test(o)||u("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function Ae(e,t,o){let n=$(e,t,255);return Wo.test(n)||u("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!Un(o).some(i=>i.code===n)&&u("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function se(e,t){let o=$(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&u("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function Re(e,t){return(!Number.isInteger(e)||Number(e)<1)&&u("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function Z(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&u("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function De(e,t){return typeof e!="boolean"&&u("NATIVE_BOOLEAN_REQUIRED",t),e}function $t(e,t){let o=$(e,t,64).toLowerCase();return Mo.test(o)||u("NATIVE_DIGEST_INVALID",t),o}function v(e,t,o){e!==t&&u("NATIVE_VALUE_MISMATCH",o)}function C(e,t,o,n=!1){let i=new Set([...t,...Array.isArray(n)?n:[]]);for(let r of Object.keys(e))i.has(r)||u("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`);if(n!==!0)for(let r of t)Object.prototype.hasOwnProperty.call(e,r)||u("NATIVE_PROPERTY_REQUIRED",`${o}/${r}`)}function ne(e,t){return[...e].sort((o,n)=>ie(t(o),t(n)))}function U(e){return[...new Set(e)].sort(ie)}function hn(e){return[...new Set(e)].sort((t,o)=>t-o)}function ie(e,t){return e===t?0:e<t?-1:1}function Mn(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>Mn(t))),e}function ht(e,t,o){if(Nt(e,t))return o;if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length);for(let i=0;i<n;i+=1)if(!Nt(e[i],t[i]))return ht(e[i],t[i],`${o}/${i}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=U([...Object.keys(e),...Object.keys(t)]);for(let i of n){let r=e[i],a=t[i];if(!Nt(r,a))return ht(r,a,`${o}/${i}`)}}return o}function Nt(e,t){return e===void 0||t===void 0?e===t:H(e)===H(t)}function u(e,t,o={}){throw new bt(e,t,o)}var cr="7f24caff61e91c02bf2731b154aa24d0033458ae21206175ebfc772ea135bb18";export{Ut as DATA_AUDIT_METADATA_FIELDS,Tt as DATA_EVENT_TYPES_V2,eo as DATA_SYSTEM_SORT_FIELD_CODES,cr as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,K as NATIVE_CONTRACT_CAPACITY_V2,Gs as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,Ws as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,Bs as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,Js as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,zs as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,to as NATIVE_DATA_QUERY_OPERATORS_V2,bt as NativeConfigurationCompilerError,ue as NativeDataFieldContractV2Error,Fe as NativeDataPolicyExpressionV2Error,It as NativeEventActionContractError,Et as NativeScopeSourceFieldPathV2Error,Bn as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,pe as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,ot as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,ns as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,Ct as WORKFLOW_EVENT_TYPES_V2,rr as compileNativeApplicationConfiguration,nn as compileNativeEventAction,ui as compileNativeEventCapturePlansV2,li as compileRequiredPlatformCapabilitiesV3,Mt as hasDataAuditReadPolicy,Se as isDataAuditMetadataField,jt as isDataSystemSortField,rs as isNativeDataQueryOperatorV2,je as isNativeMultiValueFieldV2,Ps as materializeNativeDataQueryPathTypesV2,ze as nativeDataPolicyExpressionLeavesV2,cn as nativeDataPolicyExpressionToCnfV2,Fs as nativeDataQueryPathPlanV2,cs as nativeFieldAggregatePlanV2,Cs as nativeFieldColumnDefinitionV2,bs as nativeFieldDefaultSqlV2,Os as nativeFieldHasDefaultV2,Ds as nativeFieldIndexStatementsV2,We as nativeFieldRequiresCreateInputV2,Rs as nativeFieldSequenceGrantStatementsV2,hs as nativeFieldSequenceOwnershipStatementsV2,$s as nativeFieldSequenceStatementsV2,Gt as nativeFieldSupportsFilterV2,as as nativeFieldSupportsOperatorV2,ct as nativeFieldSupportsSearchV2,dt as nativeFieldSupportsSortV2,Jt as nativeOperatorsForFieldV2,Co as nativePhysicalFieldV2,Ts as nativePhysicalFieldsV2,_e as nativePhysicalObjectNameV2,Vs as nativeScopeSourceFieldValueV2,en as nativeScopeSourceGrantPathSupportedV2,At as nativeScopeSourceSubjectPathSupportedV2,Ss as nativeSubtableConstraintStatementsV2,it as parseNativeDataFieldsV2,xt as parseNativeDataResourceInvariantsV2,pt as projectNativeDataResourceViewV2,te as quoteNativeIdentifierV2,Ve as resolveNativeScopeSourceFieldPathV2,kt as validateNativeDataResourceReferencesV2,ft as validateNativeDataResourceSurfaceV2,sn as validateWorkflowInstanceCommandPolicies,Us as workflowInstanceCommandDeadlineError,xs as workflowInstanceTerminateCapabilityAllowed,on as workflowPolicyTimestamp};