openxiangda-contracts 2.16.2 → 2.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/data-view-validation.d.ts +1 -0
- package/dist/data-view-validation.d.ts.map +1 -1
- package/dist/data-view-validation.js +38 -1
- package/dist/data-view-validation.js.map +1 -1
- package/dist/native-compiler/compiler.d.ts +1 -0
- package/dist/native-compiler/compiler.d.ts.map +1 -1
- package/dist/native-compiler/compiler.js +336 -2
- package/dist/native-compiler/compiler.js.map +1 -1
- package/dist/native-compiler/data-surface.d.ts +2 -1
- package/dist/native-compiler/data-surface.d.ts.map +1 -1
- package/dist/native-compiler/data-surface.js +4 -1
- package/dist/native-compiler/data-surface.js.map +1 -1
- package/dist/native-compiler/draft-state.d.ts +3 -0
- package/dist/native-compiler/draft-state.d.ts.map +1 -0
- package/dist/native-compiler/draft-state.js +101 -0
- package/dist/native-compiler/draft-state.js.map +1 -0
- package/dist/native-compiler/index.cjs +5 -5
- package/dist/native-compiler/index.d.ts +1 -0
- package/dist/native-compiler/index.d.ts.map +1 -1
- package/dist/native-compiler/index.js +5 -5
- package/dist/native.d.ts +134 -0
- package/dist/native.d.ts.map +1 -1
- package/dist/native.js.map +1 -1
- package/dist/schemas.d.ts +1090 -30
- package/dist/schemas.d.ts.map +1 -1
- package/dist/schemas.js +227 -0
- package/dist/schemas.js.map +1 -1
- package/dist/surface.d.ts +26 -0
- package/dist/surface.d.ts.map +1 -1
- package/dist/surface.js.map +1 -1
- package/dist/types.d.ts +9 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/validation.d.ts.map +1 -1
- package/dist/validation.js +2 -1
- package/dist/validation.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var Xn=Object.create;var We=Object.defineProperty;var Qn=Object.getOwnPropertyDescriptor;var Zn=Object.getOwnPropertyNames;var eo=Object.getPrototypeOf,to=Object.prototype.hasOwnProperty;var no=(e,t)=>{for(var o in t)We(e,o,{get:t[o],enumerable:!0})},Jt=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Zn(t))!to.call(e,i)&&i!==o&&We(e,i,{get:()=>t[i],enumerable:!(n=Qn(t,i))||n.enumerable});return e};var oo=(e,t,o)=>(o=e!=null?Xn(eo(e)):{},Jt(t||!e||!e.__esModule?We(o,"default",{value:e,enumerable:!0}):o,e)),io=e=>Jt(We({},"__esModule",{value:!0}),e);var ys={};no(ys,{DATA_AUDIT_METADATA_FIELDS:()=>mt,DATA_EVENT_TYPES_V2:()=>ot,DATA_SYSTEM_SORT_FIELD_CODES:()=>Zt,NATIVE_CONFIGURATION_VALIDATOR_DIGEST:()=>Ss,NATIVE_CONTRACT_CAPACITY_V2:()=>H,NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES:()=>or,NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH:()=>er,NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS:()=>tr,NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES:()=>nr,NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES:()=>ir,NATIVE_DATA_QUERY_OPERATORS_V2:()=>nn,NativeConfigurationCompilerError:()=>st,NativeDataFieldContractV2Error:()=>le,NativeDataPolicyExpressionV2Error:()=>De,NativeEventActionContractError:()=>nt,NativeScopeSourceFieldPathV2Error:()=>et,OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2:()=>Xt,OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2:()=>ue,OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2:()=>Ge,OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2:()=>ao,WORKFLOW_EVENT_TYPES_V2:()=>it,compileNativeApplicationConfiguration:()=>Mi,compileNativeEventAction:()=>yt,compileNativeEventCapturePlansV2:()=>xn,compileRequiredPlatformCapabilitiesV3:()=>kn,hasDataAuditReadPolicy:()=>Nt,isDataAuditMetadataField:()=>Oe,isDataSystemSortField:()=>gt,isNativeDataQueryOperatorV2:()=>No,isNativeMultiValueFieldV2:()=>we,materializeNativeDataQueryPathTypesV2:()=>li,nativeDataPolicyExpressionLeavesV2:()=>ke,nativeDataPolicyExpressionToCnfV2:()=>Ft,nativeDataQueryPathPlanV2:()=>ui,nativeFieldAggregatePlanV2:()=>Ro,nativeFieldColumnDefinitionV2:()=>Mo,nativeFieldDefaultSqlV2:()=>jo,nativeFieldHasDefaultV2:()=>Bo,nativeFieldIndexStatementsV2:()=>Yo,nativeFieldRequiresCreateInputV2:()=>Pe,nativeFieldSequenceGrantStatementsV2:()=>zo,nativeFieldSequenceOwnershipStatementsV2:()=>Go,nativeFieldSequenceStatementsV2:()=>Jo,nativeFieldSupportsFilterV2:()=>$t,nativeFieldSupportsOperatorV2:()=>Oo,nativeFieldSupportsSearchV2:()=>He,nativeFieldSupportsSortV2:()=>Ke,nativeOperatorsForFieldV2:()=>Ot,nativePhysicalFieldV2:()=>ln,nativePhysicalFieldsV2:()=>Uo,nativePhysicalObjectNameV2:()=>pe,nativeScopeSourceFieldValueV2:()=>ei,nativeScopeSourceGrantPathSupportedV2:()=>St,nativeScopeSourceSubjectPathSupportedV2:()=>tt,nativeSubtableConstraintStatementsV2:()=>Ho,parseNativeDataFieldsV2:()=>ze,parseNativeDataResourceInvariantsV2:()=>It,projectNativeDataResourceViewV2:()=>Xe,quoteNativeIdentifierV2:()=>Z,resolveNativeScopeSourceFieldPathV2:()=>Re,validateNativeDataResourceReferencesV2:()=>At,validateNativeDataResourceSurfaceV2:()=>qe,validateWorkflowInstanceCommandPolicies:()=>wt,workflowInstanceCommandDeadlineError:()=>_i,workflowInstanceTerminateCapabilityAllowed:()=>pi,workflowPolicyTimestamp:()=>Vt});module.exports=io(ys);var Gt=require("node:crypto");function so(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function pt(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)=>pt(n,`${t}[${i}]`)).join(",")}]`;if(so(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)}:${pt(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 K(e){return pt(e,"$")}function X(e){return(0,Gt.createHash)("sha256").update(K(e)).digest("hex")}var qt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Et=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Xt=["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"],ro=new Set(Xt),Qt=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),zt=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),Yt=new Set(["resource-ref.single","resource-ref.multiple"]),Ge=[{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}],ao=new Map(Ge.map(e=>[e.code,e])),le=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function we(e){return Qt.has(e)}function Pe(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!we(e.type)||t.requiredHint===!0)}function ze(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);qt.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);ro.has(p)||R("NATIVE_DATA_FIELD_TYPE_INVALID",`${a}/type`);let _=p,d=Ht(s.nullable,`${a}/nullable`),c=Ht(s.indexed,`${a}/indexed`);d===!0&&Qt.has(_)&&R("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${a}/nullable`);let A=uo(s.options,_,a),f=fo(s.source,_,a),E=_o(s,_,a),N=co(s.rangeBoundary,_,a),m=Eo(s.file,_,a),g=Ao(s.serial,_,a),T=Io(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 co(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 At(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);(!Et.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:ze(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&&lo(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 It(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 _=Je(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=_e(d.leftField,`${s}/expression/leftField`),A=_e(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 lo(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 uo(e,t,o){let n=`${o}/options`;if(e===void 0){zt.has(t)&&R("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!zt.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=Je(A.description,`${c}/description`,2e3),m=Je(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 fo(e,t,o){let n=`${o}/source`;if(e===void 0){Yt.has(t)&&R("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}Yt.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);Et.test(r)||R("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=_e(i.labelField,`${n}/labelField`),s=_t(i.searchFields,`${n}/searchFields`,10),l=_t(i.descriptionFields,`${n}/descriptionFields`,10),p=_t(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=po(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 po(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=_e(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:_e(_.field,`${i}/binding/field`)}}})}function _o(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=Be(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=Be(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:Be(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=Kt(e.min,`${o}/min`),r=Kt(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 Eo(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 Ao(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=Je(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 Io(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);Et.test(r)||R("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=_e(i.foreignKey,`${n}/foreignKey`),s=_e(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 _t(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)=>_e(i,`${t}/${r}`));return new Set(n).size!==n.length&&R("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function _e(e,t){let o=ae(e,t,63);return qt.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 Je(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&R("NATIVE_STRING_INVALID",t),e}function Ht(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 Be(e,t,o,n)}function Kt(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&R("NATIVE_NUMBER_REQUIRED",t),e}function Be(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 le(e,t)}var mt=["created_by","updated_by","created_at","updated_at"];function Oe(e){return mt.includes(e)}function Nt(e){return mt.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var Zt=Ge.map(e=>e.code);function gt(e){return Zt.includes(e)}var nn=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],mo=new Set(nn);function No(e){return mo.has(String(e))}var Tt=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],Fe=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],go=["eq","neq","in","isEmpty"],Ye=["eq","neq","in","isEmpty","isNotEmpty"],$e=["has","hasAny","hasAll","isEmpty","isNotEmpty"],en=["overlaps","contains","containedBy","isEmpty"],Ct=["jsonContains","isEmpty","isNotEmpty"],bt=["isEmpty","isNotEmpty"],To={"text.short":Tt,"text.long":Tt,"text.rich":Tt,"number.integer":Fe,"number.decimal":Fe,boolean:go,date:Fe,time:Fe,datetime:Fe,"date-range":en,"datetime-range":en,"option.single":Ye,"option.multiple":$e,"cascade.single":$e,"cascade.multiple":$e,"user.single":Ye,"user.multiple":$e,"department.single":Ye,"department.multiple":$e,"resource-ref.single":Ye,"resource-ref.multiple":$e,file:bt,image:bt,signature:bt,address:Ct,location:Ct,uuid:["eq","neq","in","isEmpty"],json:Ct,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},Co=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),bo=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function Ot(e){return To[e]}function Oo(e,t){return Ot(e).includes(t)}function He(e){return Co.has(e)}function Ke(e){return!bo.has(e)}function $t(e){return Ot(e).length>0}var tn=new Set(["number.integer","number.decimal"]),on=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),$o=new Set([...on,"boolean","uuid"]),ho=new Set(["option.single","user.single","department.single","resource-ref.single"]);function Ro(e,t){return t==="sum"||t==="avg"?tn.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?on.has(e)?{valueExpression:"column",numericResult:tn.has(e)}:null:ho.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:$o.has(e)?{valueExpression:"column",numericResult:!0}:null}var Do=500,ue={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"]},So={"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 qe(e,t,o){if(e===void 0)return;let n=Q(e,o);ce(n,ue.surface,o);let i=n.mutationOwner===void 0?"native":fe(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,ue.generated,`${o}/generated`);for(let l of ue.generated)Rt(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}`),Vo(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 rn(d,c,l)});p&&!_&&P("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${l}`)}if(wo(n.list,a,`${o}/list`),sn(n.form,a,`${o}/form`),sn(n.detail,a,`${o}/detail`),n.mobile!==void 0){let l=Q(n.mobile,`${o}/mobile`);ce(l,ue.mobile,`${o}/mobile`),Rt(l.enabled,`${o}/mobile/enabled`)}yo(n,t,o)}function Xe(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 yo(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=fe(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),fe(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=he(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),fe(f.title,`${A}/title`,255);for(let E of he(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=Xe(e,l);if(qe(p,t,a),s.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let _ of t)Pe(_,e.fields[_.code])&&rn(_,e.fields[_.code],"create")&&!s.form.fieldOrder.includes(_.code)&&P("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${a}/form/fieldOrder`)})}function rn(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 Vo(e,t,o){let n=Q(e,o);ce(n,ue.field,o),fe(n.label,`${o}/label`,500),n.type!==t.type&&P("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let i=fe(n.widget,`${o}/widget`,64);So[t.type].includes(i)||P("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),vo(n.section,`${o}/section`,255);for(let r of["requiredHint","system","hidden","list","searchable","sortable"])Rt(n[r],`${o}/${r}`);n.searchable===!0&&!He(t.type)&&P("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!Ke(t.type)&&P("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let r of["readCapabilities","createCapabilities","updateCapabilities"])he(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];he(r,`${o}/accept`,50,!1)}for(let r of["maxLength","precision","scale","min","max","rangeBoundary","options","source","timePrecision","serial","subtable"])Po(n,t,r,o);Fo(n,t,o)}function wo(e,t,o){if(e===void 0)return;let n=Q(e,o);if(ce(n,ue.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 he(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",He],["filterFields",$t]]){if(n[i]===void 0)continue;let a=he(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,ue.defaultSort,`${o}/defaultSort`);let r=fe(i.field,`${o}/defaultSort/field`,63),a=t.get(r);!gt(r)&&(!a||!Ke(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 sn(e,t,o){if(e===void 0)return;let n=Q(e,o);if(ce(n,ue.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>Do)&&P("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i);let r=n.fieldOrder.map((a,s)=>fe(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 Po(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}`),K(e[o])!==K(t[o])&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function Fo(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:ht(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"?ht(i[r]):i[r],s=r==="accept"?ht(n[r]):n[r];K(a)!==K(s)&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`)}}function ht(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 he(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)=>fe(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 fe(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&P("NATIVE_STRING_INVALID",t),e}function vo(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&P("NATIVE_STRING_INVALID",t)}function Rt(e,t){e!==void 0&&typeof e!="boolean"&&P("NATIVE_BOOLEAN_REQUIRED",t)}function P(e,t){throw new le(e,t)}var cn=require("crypto");var Dt=new Set(["option.single","user.single","department.single","resource-ref.single"]),Lo=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),dn=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),ko=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),xo=new Set([...Dt,...dn,"signature","address","location","json"]);function Uo(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=>ln(n,o.has(n.code))).sort((n,i)=>n.code.localeCompare(i.code))}function ln(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:qo(e),index:Ko(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 Mo(e,t){if(t.type==="subtable")return null;let o=Z(t.code),n=un(e,t),i=[n?` DEFAULT ${n}`:"",Xo(o,t),Wo(o,t)].join("");return`${o} ${t.storage}${i}`}function jo(e,t){return un(e,t)}function Wo(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 Bo(e){return e.type==="serial-number"||we(e.type)&&e.type!=="subtable"}function Jo(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=Ze(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 Go(e,t){let o=Qe(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${Ze(e,n.code)} OWNED BY ${o}.${Z(n.code)}`)}function zo(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${Ze(e,o.code)} TO "openxiangda_data_api"`)}function Yo(e,t){let o=Qe(e),n=[];for(let i of t){if(i.type==="subtable")continue;let r=Z(i.code),a=Z(pe("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=Z(pe("idx",e,i.code,"snapshot-value")),l=Z(pe("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=Dt.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=Z(pe("uidx",e,i.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${s} ON ${o} (${r})`)}}return n}function Ho(e,t,o,n){let i=Qe(e),r=Qe(t),a=Z(pe("uidx",e,"environment_id","subtable-parent")),s=Z(pe("idx",t,o,n,"subtable-child")),l=Z(pe("fk",t,o,e)),p=Z(o),_=Z(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
|
|
1
|
+
"use strict";var io=Object.create;var We=Object.defineProperty;var ro=Object.getOwnPropertyDescriptor;var ao=Object.getOwnPropertyNames;var co=Object.getPrototypeOf,lo=Object.prototype.hasOwnProperty;var uo=(e,t)=>{for(var n in t)We(e,n,{get:t[n],enumerable:!0})},Kt=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ao(t))!lo.call(e,s)&&s!==n&&We(e,s,{get:()=>t[s],enumerable:!(o=ro(t,s))||o.enumerable});return e};var fo=(e,t,n)=>(n=e!=null?io(co(e)):{},Kt(t||!e||!e.__esModule?We(n,"default",{value:e,enumerable:!0}):n,e)),_o=e=>Kt(We({},"__esModule",{value:!0}),e);var Bi={};uo(Bi,{DATA_AUDIT_METADATA_FIELDS:()=>gt,DATA_EVENT_TYPES_V2:()=>rt,DATA_SYSTEM_SORT_FIELD_CODES:()=>sn,NATIVE_CONFIGURATION_VALIDATOR_DIGEST:()=>ji,NATIVE_CONTRACT_CAPACITY_V2:()=>q,NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES:()=>mr,NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH:()=>pr,NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS:()=>Ar,NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES:()=>Ir,NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES:()=>Nr,NATIVE_DATA_QUERY_OPERATORS_V2:()=>cn,NativeConfigurationCompilerError:()=>ct,NativeDataFieldContractV2Error:()=>ae,NativeDataPolicyExpressionV2Error:()=>Ve,NativeEventActionContractError:()=>it,NativeScopeSourceFieldPathV2Error:()=>ot,OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2:()=>nn,OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2:()=>Ae,OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2:()=>Qe,OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2:()=>Ye,OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2:()=>Ao,WORKFLOW_EVENT_TYPES_V2:()=>at,compileNativeApplicationConfiguration:()=>Ks,compileNativeEventAction:()=>Lt,compileNativeEventCapturePlansV2:()=>zn,compileRequiredPlatformCapabilitiesV3:()=>Gn,hasDataAuditReadPolicy:()=>bt,isDataAuditMetadataField:()=>Re,isDataSystemSortField:()=>Ct,isNativeDataQueryOperatorV2:()=>ho,isNativeMultiValueFieldV2:()=>Le,materializeNativeDataQueryPathTypesV2:()=>Ts,nativeDataPolicyExpressionLeavesV2:()=>Me,nativeDataPolicyExpressionToCnfV2:()=>xt,nativeDataQueryPathPlanV2:()=>gs,nativeFieldAggregatePlanV2:()=>Lo,nativeFieldColumnDefinitionV2:()=>Ho,nativeFieldDefaultSqlV2:()=>Xo,nativeFieldHasDefaultV2:()=>Zo,nativeFieldIndexStatementsV2:()=>os,nativeFieldRequiresCreateInputV2:()=>ve,nativeFieldSequenceGrantStatementsV2:()=>ns,nativeFieldSequenceOwnershipStatementsV2:()=>ts,nativeFieldSequenceStatementsV2:()=>es,nativeFieldSupportsFilterV2:()=>St,nativeFieldSupportsOperatorV2:()=>wo,nativeFieldSupportsSearchV2:()=>He,nativeFieldSupportsSortV2:()=>Se,nativeOperatorsForFieldV2:()=>ht,nativePhysicalFieldV2:()=>In,nativePhysicalFieldsV2:()=>Ko,nativePhysicalObjectNameV2:()=>me,nativeScopeSourceFieldValueV2:()=>ls,nativeScopeSourceGrantPathSupportedV2:()=>Pt,nativeScopeSourceSubjectPathSupportedV2:()=>st,nativeSubtableConstraintStatementsV2:()=>ss,parseNativeDataFieldsV2:()=>qe,parseNativeDataResourceInvariantsV2:()=>Tt,projectNativeDataResourceViewV2:()=>et,quoteNativeIdentifierV2:()=>ne,resolveNativeScopeSourceFieldPathV2:()=>ye,validateNativeDataDraftStateV2:()=>yt,validateNativeDataResourceReferencesV2:()=>Nt,validateNativeDataResourceSurfaceV2:()=>Ze,validateWorkflowInstanceCommandPolicies:()=>kt,workflowInstanceCommandDeadlineError:()=>Os,workflowInstanceTerminateCapabilityAllowed:()=>Cs,workflowPolicyTimestamp:()=>vt});module.exports=_o(Bi);var Ht=require("node:crypto");function Eo(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function At(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((o,s)=>At(o,`${t}[${s}]`)).join(",")}]`;if(Eo(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)}:${At(e[s],`${t}.${s}`)}`).join(",")}}`;let n=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${n})`)}function Q(e){return At(e,"$")}function ee(e){return(0,Ht.createHash)("sha256").update(Q(e)).digest("hex")}var tn=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,mt=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,nn=["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"],po=new Set(nn),on=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),Xt=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),Qt=new Set(["resource-ref.single","resource-ref.multiple"]),Ye=[{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}],Ao=new Map(Ye.map(e=>[e.code,e])),ae=class extends Error{constructor(n,o){super(n);this.code=n;this.pointer=o;this.name="NativeDataFieldContractV2Error"}code;pointer};function Le(e){return on.has(e)}function ve(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!Le(e.type)||t.requiredHint===!0)}function qe(e,t,n=500){Array.isArray(e)||S("NATIVE_ARRAY_REQUIRED",t),e.length===0&&S("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>n&&S("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let o=new Set;return e.map((s,r)=>{let a=`${t}/${r}`,i=ie(s,a);ue(i,["code","type","nullable","indexed","options","source","maxLength","precision","scale","min","max","rangeBoundary","timePrecision","file","serial","subtable"],a);let c=fe(i.code,`${a}/code`,63);tn.test(c)||S("NATIVE_FIELD_CODE_INVALID",`${a}/code`),o.has(c)&&S("NATIVE_DATA_FIELD_DUPLICATE",`${a}/code`),o.add(c);let u=fe(i.type,`${a}/type`,32);po.has(u)||S("NATIVE_DATA_FIELD_TYPE_INVALID",`${a}/type`);let E=u,d=Zt(i.nullable,`${a}/nullable`),f=Zt(i.indexed,`${a}/indexed`);d===!0&&on.has(E)&&S("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${a}/nullable`);let p=No(i.options,E,a),_=To(i.source,E,a),A=bo(i,E,a),N=Io(i.rangeBoundary,E,a),m=Co(i.file,E,a),T=Oo(i.serial,E,a),C=$o(i.subtable,E,a);return{code:c,type:E,...d===void 0?{}:{nullable:d},...f===void 0?{}:{indexed:f},...p?{options:p}:{},..._?{source:_}:{},...A,...N?{rangeBoundary:N}:{},...m?{file:m}:{},...T?{serial:T}:{},...C?{subtable:C}:{}}})}function Io(e,t,n){let o=`${n}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&S("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",o);return}return e!=="closed"&&e!=="half-open"&&S("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",o),e}function Nt(e,t){Array.isArray(e)||S("NATIVE_ARRAY_REQUIRED",t);let n=new Map;e.forEach((o,s)=>{let r=`${t}/${s}`,a=ie(o,r),i=fe(a.code,`${r}/code`,64);(!mt.test(i)||n.has(i))&&S("NATIVE_RESOURCE_CODE_INVALID",`${r}/code`);let c=ie(a.schema,`${r}/schema`);n.set(i,{pointer:r,fields:qe(c.fields,`${r}/schema/fields`)})});for(let[o,s]of n){let r=new Map(s.fields.map(i=>[i.code,i]));s.fields.filter(i=>i.type==="subtable").reduce((i,c)=>i+(c.subtable?.maxRows??20),0)>49&&S("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${s.pointer}/schema/fields`),s.fields.forEach((i,c)=>{let u=`${s.pointer}/schema/fields/${c}`;if(i.source&&mo(i.source,r,n,`${u}/source`),i.subtable){let E=n.get(i.subtable.resourceCode);(!E||i.subtable.resourceCode===o)&&S("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${u}/subtable/resourceCode`);let d=E.fields.find(p=>p.code===i.subtable?.foreignKey);(!d||d.type!=="uuid"||d.nullable!==!1)&&S("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${u}/subtable/foreignKey`);let f=E.fields.find(p=>p.code===i.subtable?.orderField);(!f||f.type!=="number.integer"||f.nullable!==!1)&&S("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${u}/subtable/orderField`)}})}}function Tt(e,t,n){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&S("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",n);let o=new Map(t.map(r=>[r.code,r])),s=new Set;return e.map((r,a)=>{let i=`${n}/${a}`,c=ie(r,i);ue(c,["code","message","expression"],i);let u=fe(c.code,`${i}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(u)||s.has(u))&&S("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${i}/code`),s.add(u);let E=ze(c.message,`${i}/message`,500);E!==void 0&&E.length===0&&S("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${i}/message`);let d=ie(c.expression,`${i}/expression`);ue(d,["leftField","operator","rightField"],`${i}/expression`);let f=Te(d.leftField,`${i}/expression/leftField`),p=Te(d.rightField,`${i}/expression/rightField`),_=o.get(f),A=o.get(p);(!_||!A)&&S("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${i}/expression`),_.type===A.type||["number.integer","number.decimal"].includes(_.type)&&["number.integer","number.decimal"].includes(A.type)||S("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${i}/expression`);let m=String(d.operator);return["eq","neq","gt","gte","lt","lte"].includes(m)||S("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(_.type)&&S("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${i}/expression`),{code:u,...E===void 0?{}:{message:E},expression:{leftField:f,operator:m,rightField:p}}})}function mo(e,t,n,o){let s=n.get(e.resourceCode);s||S("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${o}/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))&&S("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${o}/labelField`);for(let i of["searchFields","descriptionFields","snapshotFields"])for(let c of e[i]||[])r.has(c)||S("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${o}/${i}`);for(let[i,c]of(e.filters||[]).entries())r.has(c.field)||S("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${o}/filters/${i}/field`),"binding"in c&&!t.has(c.binding.field)&&S("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${o}/filters/${i}/binding/field`)}function No(e,t,n){let o=`${n}/options`;if(e===void 0){Xt.has(t)&&S("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",o);return}(!Xt.has(t)||!Array.isArray(e))&&S("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",o),(e.length<1||e.length>100)&&S("NATIVE_DATA_FIELD_OPTIONS_INVALID",o);let s=0,r=(a,i,c)=>{c>5&&S("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",i);let u=new Set;return a.map((E,d)=>{s+=1,s>1e3&&S("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",o);let f=`${i}/${d}`,p=ie(E,f);ue(p,["label","value","description","color","children"],f);let _=fe(p.label,`${f}/label`,500),A=fe(p.value,`${f}/value`,500);u.has(A)&&S("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${f}/value`),u.add(A);let N=ze(p.description,`${f}/description`,2e3),m=ze(p.color,`${f}/color`,64),T;return p.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(p.children))&&S("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${f}/children`),(p.children.length<1||p.children.length>100)&&S("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${f}/children`),T=r(p.children,`${f}/children`,c+1)),{label:_,value:A,...N===void 0?{}:{description:N},...m===void 0?{}:{color:m},...T?{children:T}:{}}})};return r(e,o,1)}function To(e,t,n){let o=`${n}/source`;if(e===void 0){Qt.has(t)&&S("NATIVE_DATA_FIELD_SOURCE_REQUIRED",o);return}Qt.has(t)||S("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",o);let s=ie(e,o);ue(s,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode"],o),s.kind!=="resource"&&S("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${o}/kind`);let r=fe(s.resourceCode,`${o}/resourceCode`,64);mt.test(r)||S("NATIVE_RESOURCE_CODE_INVALID",`${o}/resourceCode`);let a=Te(s.labelField,`${o}/labelField`),i=It(s.searchFields,`${o}/searchFields`,10),c=It(s.descriptionFields,`${o}/descriptionFields`,10),u=It(s.snapshotFields,`${o}/snapshotFields`,50),E=$e(s.pageSize,`${o}/pageSize`,1,100),d;s.loadMode!==void 0&&(["search","all"].includes(String(s.loadMode))||S("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${o}/loadMode`),d=s.loadMode);let f=go(s.filters,`${o}/filters`);return{kind:"resource",resourceCode:r,labelField:a,...i?{searchFields:i}:{},...c?{descriptionFields:c}:{},...u?{snapshotFields:u}:{},...f?{filters:f}:{},...E===void 0?{}:{pageSize:E},...d?{loadMode:d}:{}}}function go(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&S("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((n,o)=>{let s=`${t}/${o}`,r=ie(n,s),a=Object.prototype.hasOwnProperty.call(r,"value"),i=Object.prototype.hasOwnProperty.call(r,"binding");ue(r,a?["field","operator","value"]:["field","operator","binding"],s),a===i&&S("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",s);let c=Te(r.field,`${s}/field`);["eq","in"].includes(String(r.operator))||S("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${s}/operator`);let u=r.operator;if(a)return{field:c,operator:u,value:r.value};let E=ie(r.binding,`${s}/binding`);return ue(E,["kind","field"],`${s}/binding`),E.kind!=="field"&&S("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${s}/binding/kind`),{field:c,operator:u,binding:{kind:"field",field:Te(E.field,`${s}/binding/field`)}}})}function bo(e,t,n){let o={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||S("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${n}/maxLength`),o.maxLength=Ge(e.maxLength,`${n}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&S("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",n),o.precision=Ge(e.precision,`${n}/precision`,1,1e3),o.scale=e.scale===void 0?0:Ge(e.scale,`${n}/scale`,0,o.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||S("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",n);let s=en(e.min,`${n}/min`),r=en(e.max,`${n}/max`);t==="number.integer"&&[s,r].some(a=>a!==void 0&&!Number.isSafeInteger(a))&&S("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",n),s!==void 0&&r!==void 0&&s>r&&S("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",n),s!==void 0&&(o.min=s),r!==void 0&&(o.max=r)}return e.timePrecision!==void 0&&((t!=="time"||!["minute","second"].includes(e.timePrecision))&&S("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${n}/timePrecision`),o.timePrecision=e.timePrecision),o}function Co(e,t,n){if(e===void 0)return;let o=`${n}/file`;["file","image","signature"].includes(t)||S("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",o);let s=ie(e,o);ue(s,["maxCount","maxSizeMb","accept"],o);let r=$e(s.maxCount,`${o}/maxCount`,1,100);t==="signature"&&r!==void 0&&r!==1&&S("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${o}/maxCount`);let a=$e(s.maxSizeMb,`${o}/maxSizeMb`,1,1024),i;return s.accept!==void 0&&((!Array.isArray(s.accept)||s.accept.length>50)&&S("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${o}/accept`),i=s.accept.map((c,u)=>fe(c,`${o}/accept/${u}`,255)),new Set(i).size!==i.length&&S("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${o}/accept`)),{...r===void 0?{}:{maxCount:r},...a===void 0?{}:{maxSizeMb:a},...i===void 0?{}:{accept:i}}}function Oo(e,t,n){let o=`${n}/serial`;if(e===void 0){t==="serial-number"&&S("NATIVE_DATA_FIELD_SERIAL_REQUIRED",o);return}t!=="serial-number"&&S("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",o);let s=ie(e,o);ue(s,["prefix","digits","start"],o);let r=ze(s.prefix,`${o}/prefix`,64),a=$e(s.digits,`${o}/digits`,1,32),i=$e(s.start,`${o}/start`,0,Number.MAX_SAFE_INTEGER);return{...r===void 0?{}:{prefix:r},...a===void 0?{}:{digits:a},...i===void 0?{}:{start:i}}}function $o(e,t,n){let o=`${n}/subtable`;if(e===void 0){t==="subtable"&&S("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",o);return}t!=="subtable"&&S("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",o);let s=ie(e,o);ue(s,["resourceCode","foreignKey","orderField","maxRows"],o);let r=fe(s.resourceCode,`${o}/resourceCode`,64);mt.test(r)||S("NATIVE_RESOURCE_CODE_INVALID",`${o}/resourceCode`);let a=Te(s.foreignKey,`${o}/foreignKey`),i=Te(s.orderField,`${o}/orderField`);i===a&&S("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${o}/orderField`);let c=$e(s.maxRows,`${o}/maxRows`,1,49);return{resourceCode:r,foreignKey:a,orderField:i,...c===void 0?{}:{maxRows:c}}}function It(e,t,n){if(e===void 0)return;(!Array.isArray(e)||e.length>n)&&S("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let o=e.map((s,r)=>Te(s,`${t}/${r}`));return new Set(o).size!==o.length&&S("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),o}function Te(e,t){let n=fe(e,t,63);return tn.test(n)||S("NATIVE_FIELD_CODE_INVALID",t),n}function ie(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&S("NATIVE_OBJECT_REQUIRED",t),e}function ue(e,t,n){let o=new Set(t);for(let s of Object.keys(e))o.has(s)||S("NATIVE_PROPERTY_UNKNOWN",`${n}/${s}`)}function fe(e,t,n){return(typeof e!="string"||e.length===0||e.length>n)&&S("NATIVE_STRING_INVALID",t),e}function ze(e,t,n){if(e!==void 0)return(typeof e!="string"||e.length>n)&&S("NATIVE_STRING_INVALID",t),e}function Zt(e,t){if(e!==void 0)return typeof e!="boolean"&&S("NATIVE_BOOLEAN_REQUIRED",t),e}function $e(e,t,n,o){if(e!==void 0)return Ge(e,t,n,o)}function en(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&S("NATIVE_NUMBER_REQUIRED",t),e}function Ge(e,t,n,o){return(!Number.isSafeInteger(e)||Number(e)<n||Number(e)>o)&&S("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function S(e,t){throw new ae(e,t)}var gt=["created_by","updated_by","created_at","updated_at"];function Re(e){return gt.includes(e)}function bt(e){return gt.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var sn=Ye.map(e=>e.code);function Ct(e){return sn.includes(e)}var cn=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],Ro=new Set(cn);function ho(e){return Ro.has(String(e))}var Ot=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],ke=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],So=["eq","neq","in","isEmpty"],Ke=["eq","neq","in","isEmpty","isNotEmpty"],he=["has","hasAny","hasAll","isEmpty","isNotEmpty"],rn=["overlaps","contains","containedBy","isEmpty"],$t=["jsonContains","isEmpty","isNotEmpty"],Rt=["isEmpty","isNotEmpty"],Do={"text.short":Ot,"text.long":Ot,"text.rich":Ot,"number.integer":ke,"number.decimal":ke,boolean:So,date:ke,time:ke,datetime:ke,"date-range":rn,"datetime-range":rn,"option.single":Ke,"option.multiple":he,"cascade.single":he,"cascade.multiple":he,"user.single":Ke,"user.multiple":he,"department.single":Ke,"department.multiple":he,"resource-ref.single":Ke,"resource-ref.multiple":he,file:Rt,image:Rt,signature:Rt,address:$t,location:$t,uuid:["eq","neq","in","isEmpty"],json:$t,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},yo=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),Vo=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function ht(e){return Do[e]}function wo(e,t){return ht(e).includes(t)}function He(e){return yo.has(e)}function Se(e){return!Vo.has(e)}function St(e){return ht(e).length>0}var an=new Set(["number.integer","number.decimal"]),dn=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),Fo=new Set([...dn,"boolean","uuid"]),Po=new Set(["option.single","user.single","department.single","resource-ref.single"]);function Lo(e,t){return t==="sum"||t==="avg"?an.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?dn.has(e)?{valueExpression:"column",numericResult:an.has(e)}:null:Po.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:Fo.has(e)?{valueExpression:"column",numericResult:!0}:null}var Qe=["version","maxBytes","fields"];function yt(e,t){if(e===void 0)return;let n=Dt(e,t);ln(n,Qe,t);let o=Xe(n.version,`${t}/version`,1,1e6),s=Xe(n.maxBytes,`${t}/maxBytes`,2,196608);(!o||!s)&&oe("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let r=Dt(n.fields,`${t}/fields`),a=Object.entries(r);(!a.length||a.length>50)&&oe("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[i,c]of a){let u=`${t}/fields/${i}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(i)||oe("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",u);let E=Dt(c,u),d=un(E.type,`${u}/type`,32),f=d==="string"?["type","required","maxLength","enum"]:d==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(d)||oe("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${u}/type`),ln(E,f,u),ko(E.required,`${u}/required`),d==="string"){let p=Xe(E.maxLength,`${u}/maxLength`,1,196608);p||oe("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",u),E.enum!==void 0&&vo(E.enum,`${u}/enum`,100,!1).some(A=>A.length>p)&&oe("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${u}/enum`)}else if(d==="json.object"){let p=Xe(E.maxBytes,`${u}/maxBytes`,2,65536);(!p||p>s)&&oe("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",u)}}}function vo(e,t,n,o){(!Array.isArray(e)||!o&&e.length===0||e.length>n)&&oe("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let s=e.map((r,a)=>un(r,`${t}/${a}`,255));return new Set(s).size!==s.length&&oe("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),s}function Dt(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&oe("NATIVE_OBJECT_REQUIRED",t),e}function ln(e,t,n){let o=new Set(t);for(let s of Object.keys(e))o.has(s)||oe("NATIVE_PROPERTY_UNKNOWN",`${n}/${s}`)}function un(e,t,n){return(typeof e!="string"||e.length===0||e.length>n)&&oe("NATIVE_STRING_INVALID",t),e}function ko(e,t){e!==void 0&&typeof e!="boolean"&&oe("NATIVE_BOOLEAN_REQUIRED",t)}function Xe(e,t,n,o){return(!Number.isSafeInteger(e)||Number(e)<n||Number(e)>o)&&oe("NATIVE_INTEGER_INVALID",t),Number(e)}function oe(e,t){throw new ae(e,t)}var Uo=500,Ae={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","draftState"],draftState:Qe,mobile:["enabled"]},xo={"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 Ze(e,t,n){if(e===void 0)return;let o=te(e,n);_e(o,Ae.surface,n);let s=o.mutationOwner===void 0?"native":Ie(o.mutationOwner,`${n}/mutationOwner`,16);["native","action","readonly","workflow"].includes(s)||L("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${n}/mutationOwner`);let r=o.generated===void 0?{}:te(o.generated,`${n}/generated`);_e(r,Ae.generated,`${n}/generated`);for(let c of Ae.generated)wt(r[c],`${n}/generated/${c}`);if(s!=="native")for(let c of["create","update","delete"])r[c]===!0&&L("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${n}/generated/${c}`);let a=new Map(t.map(c=>[c.code,c])),i=te(o.fields,`${n}/fields`);for(let c of Object.keys(i))a.has(c)||L("NATIVE_DATA_SURFACE_FIELD_MISSING",`${n}/fields/${c}`);for(let c of t)Object.prototype.hasOwnProperty.call(i,c.code)||L("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${n}/fields/${c.code}`),jo(i[c.code],c,`${n}/fields/${c.code}`);for(let c of["create","update"]){let u=r[c]??s==="native",E=t.some(d=>{let f=te(i[d.code],`${n}/fields/${d.code}`);return _n(d,f,c)});u&&!E&&L("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${n}/generated/${c}`)}if(Bo(o.list,a,`${n}/list`),fn(o.form,a,`${n}/form`),fn(o.detail,a,`${n}/detail`),o.mobile!==void 0){let c=te(o.mobile,`${n}/mobile`);_e(c,Ae.mobile,`${n}/mobile`),wt(c.enabled,`${n}/mobile/enabled`)}Mo(o,t,n)}function et(e,t){let n=e.views?.find(s=>s.code===t);n||L("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let o=new Map((n.sections||[]).flatMap(s=>s.fields.map(r=>[r,s.title])));return{mutationOwner:e.mutationOwner||"native",generated:n.generated,list:n.list,form:n.form,detail:n.detail,mobile:n.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([s,r])=>{let a={...r};delete a.section;let i=o.get(s);return[s,{...a,...i?{section:i}:{},list:n.list.fieldOrder.includes(s)}]}))}}function Mo(e,t,n){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&L("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${n}/views`);let o=new Set;e.views.forEach((s,r)=>{let a=`${n}/views/${r}`,i=te(s,a);_e(i,["code","name","generated","list","form","detail","mobile","sections"],a);let c=Ie(i.code,`${a}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(c)||o.has(c))&&L("NATIVE_DATA_VIEW_CODE_INVALID",`${a}/code`),o.add(c),Ie(i.name,`${a}/name`,255),te(i.generated,`${a}/generated`),te(i.mobile,`${a}/mobile`);for(let E of["list","detail","create","update","delete"])typeof i.generated[E]!="boolean"&&L("NATIVE_DATA_VIEW_OPERATION_INVALID",`${a}/generated/${E}`);typeof i.mobile.enabled!="boolean"&&L("NATIVE_DATA_VIEW_MOBILE_INVALID",`${a}/mobile/enabled`);for(let E of["list","form","detail"]){let d=te(i[E],`${a}/${E}`),f=De(d.fieldOrder,`${a}/${E}/fieldOrder`,500,!0);for(let p of f){let _=e.fields[p];(!_||(_.hidden??_.system)===!0)&&L("NATIVE_DATA_VIEW_FIELD_INVALID",`${a}/${E}/fieldOrder`)}}if(i.sections!==void 0){(!Array.isArray(i.sections)||i.sections.length>100)&&L("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${a}/sections`);let E=new Set;i.sections.forEach((d,f)=>{let p=`${a}/sections/${f}`,_=te(d,p);_e(_,["title","fields"],p),Ie(_.title,`${p}/title`,255);for(let A of De(_.fields,`${p}/fields`,100,!0)){let N=e.fields[A];(!N||(N.hidden??N.system)===!0||E.has(A))&&L("NATIVE_DATA_VIEW_FIELD_INVALID",`${p}/fields`),E.add(A)}})}let u=et(e,c);if(Ze(u,t,a),i.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let E of t)ve(E,e.fields[E.code])&&_n(E,e.fields[E.code],"create")&&!i.form.fieldOrder.includes(E.code)&&L("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${a}/form/fieldOrder`)})}function _n(e,t,n){if(e.type==="serial-number"||t.system===!0)return!1;let o=t[`${n}Capabilities`];return Array.isArray(o)&&o.length>0}function jo(e,t,n){let o=te(e,n);_e(o,Ae.field,n),Ie(o.label,`${n}/label`,500),o.type!==t.type&&L("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${n}/type`);let s=Ie(o.widget,`${n}/widget`,64);xo[t.type].includes(s)||L("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${n}/widget`),Go(o.section,`${n}/section`,255);for(let r of["requiredHint","system","hidden","list","searchable","sortable"])wt(o[r],`${n}/${r}`);o.searchable===!0&&!He(t.type)&&L("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${n}/searchable`),o.sortable===!0&&!Se(t.type)&&L("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${n}/sortable`);for(let r of["readCapabilities","createCapabilities","updateCapabilities"])De(o[r],`${n}/${r}`,100,!0);if(o.maxCount!==void 0&&(!Number.isSafeInteger(o.maxCount)||Number(o.maxCount)<1||Number(o.maxCount)>100)&&L("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${n}/maxCount`),o.maxSizeMb!==void 0&&(!Number.isSafeInteger(o.maxSizeMb)||Number(o.maxSizeMb)<1||Number(o.maxSizeMb)>1024)&&L("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${n}/maxSizeMb`),o.accept!==void 0){let r=Array.isArray(o.accept)?o.accept:[o.accept];De(r,`${n}/accept`,50,!1)}for(let r of["maxLength","precision","scale","min","max","rangeBoundary","options","source","timePrecision","serial","subtable"])Jo(o,t,r,n);Wo(o,t,n)}function Bo(e,t,n){if(e===void 0)return;let o=te(e,n);if(_e(o,Ae.list,n),o.actions!==void 0){let s=te(o.actions,`${n}/actions`);_e(s,["import","export"],`${n}/actions`);for(let r of["import","export"])s[r]!==void 0&&typeof s[r]!="boolean"&&L("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${n}/actions/${r}`)}if(o.fieldOrder!==void 0)for(let s of De(o.fieldOrder,`${n}/fieldOrder`,500,!0))t.has(s)||L("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${n}/fieldOrder`);o.defaultPageSize!==void 0&&(!Number.isSafeInteger(o.defaultPageSize)||Number(o.defaultPageSize)<1||Number(o.defaultPageSize)>200)&&L("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${n}/defaultPageSize`);for(let[s,r]of[["searchableFields",He],["filterFields",St]]){if(o[s]===void 0)continue;let a=De(o[s],`${n}/${s}`,100,!0);for(let i of a){let c=t.get(i);(!c||!r(c.type))&&L("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${n}/${s}`)}}if(o.defaultSort!==void 0){let s=te(o.defaultSort,`${n}/defaultSort`);_e(s,Ae.defaultSort,`${n}/defaultSort`);let r=Ie(s.field,`${n}/defaultSort/field`,63),a=t.get(r);!Ct(r)&&(!a||!Se(a.type))&&L("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${n}/defaultSort/field`),s.order!==void 0&&!["asc","desc"].includes(s.order)&&L("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${n}/defaultSort/order`)}}function fn(e,t,n){if(e===void 0)return;let o=te(e,n);if(_e(o,Ae.layout,n),o.layout!==void 0&&!["flat","sections"].includes(o.layout)&&L("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${n}/layout`),o.fieldOrder!==void 0){let s=`${n}/fieldOrder`;(!Array.isArray(o.fieldOrder)||o.fieldOrder.length>t.size||o.fieldOrder.length>Uo)&&L("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",s);let r=o.fieldOrder.map((a,i)=>Ie(a,`${s}/${i}`,63));new Set(r).size!==r.length&&L("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",s),r.forEach((a,i)=>{t.has(a)||L("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${s}/${i}`)})}yt(o.draftState,`${n}/draftState`)}function Jo(e,t,n,o){e[n]===void 0&&t[n]===void 0||((e[n]===void 0||t[n]===void 0)&&L("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${n}`),Q(e[n])!==Q(t[n])&&L("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${n}`))}function Wo(e,t,n){let o=t.file||{},s={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:Vt(e.accept)}};for(let r of["maxCount","maxSizeMb","accept"]){if(s[r]===void 0&&o[r]===void 0)continue;(s[r]===void 0||o[r]===void 0)&&L("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${r}`);let a=r==="accept"?Vt(s[r]):s[r],i=r==="accept"?Vt(o[r]):o[r];Q(a)!==Q(i)&&L("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${r}`)}}function Vt(e){return(Array.isArray(e)?[...e]:[e]).sort((t,n)=>{let o=String(t),s=String(n);return o===s?0:o<s?-1:1})}function De(e,t,n,o){(!Array.isArray(e)||!o&&e.length===0||e.length>n)&&L("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let s=e.map((r,a)=>Ie(r,`${t}/${a}`,255));return new Set(s).size!==s.length&&L("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),s}function te(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&L("NATIVE_OBJECT_REQUIRED",t),e}function _e(e,t,n){let o=new Set(t);for(let s of Object.keys(e))o.has(s)||L("NATIVE_PROPERTY_UNKNOWN",`${n}/${s}`)}function Ie(e,t,n){return(typeof e!="string"||e.length===0||e.length>n)&&L("NATIVE_STRING_INVALID",t),e}function Go(e,t,n){e!==void 0&&(typeof e!="string"||e.length>n)&&L("NATIVE_STRING_INVALID",t)}function wt(e,t){e!==void 0&&typeof e!="boolean"&&L("NATIVE_BOOLEAN_REQUIRED",t)}function L(e,t){throw new ae(e,t)}var pn=require("crypto");var Ft=new Set(["option.single","user.single","department.single","resource-ref.single"]),zo=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),An=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),Yo=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),qo=new Set([...Ft,...An,"signature","address","location","json"]);function Ko(e,t){let n=new Set([...Array.isArray(t?.list?.searchableFields)?t.list.searchableFields:[],...Object.entries(t?.fields||{}).filter(([,o])=>o?.searchable===!0).map(([o])=>o)]);return e.map(o=>In(o,n.has(o.code))).sort((o,s)=>o.code.localeCompare(s.code))}function In(e,t=!1){let n=e.type==="date-range"||e.type==="datetime-range";if(n&&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:rs(e),index:is(e,t),...n?{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 Ho(e,t){if(t.type==="subtable")return null;let n=ne(t.code),o=mn(e,t),s=[o?` DEFAULT ${o}`:"",as(n,t),Qo(n,t)].join("");return`${n} ${t.storage}${s}`}function Xo(e,t){return mn(e,t)}function Qo(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 n=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 ${n?"":"NOT "}upper_inc(${e})))`}function Zo(e){return e.type==="serial-number"||Le(e.type)&&e.type!=="subtable"}function es(e,t){return t.filter(n=>n.type==="serial-number").map(n=>{let o=nt(e,n.code),s=n.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${o} AS bigint MINVALUE ${s} START WITH ${s} CACHE 1`})}function ts(e,t){let n=tt(e);return t.filter(o=>o.type==="serial-number").map(o=>`ALTER SEQUENCE ${nt(e,o.code)} OWNED BY ${n}.${ne(o.code)}`)}function ns(e,t){return t.filter(n=>n.type==="serial-number").map(n=>`GRANT USAGE, SELECT ON SEQUENCE ${nt(e,n.code)} TO "openxiangda_data_api"`)}function os(e,t){let n=tt(e),o=[];for(let s of t){if(s.type==="subtable")continue;let r=ne(s.code),a=ne(me("idx",e,s.code,s.index));switch(s.index){case"btree":o.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${n} (${r})`);break;case"btree-snapshot-expressions":{let i=ne(me("idx",e,s.code,"snapshot-value")),c=ne(me("idx",e,s.code,"snapshot-label"));o.push(`CREATE INDEX IF NOT EXISTS ${i} ON ${n} ((${r} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${c} ON ${n} ((${r} ->> 'label'))`);break}case"gin-jsonb-path":o.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${n} USING GIN (${r} jsonb_path_ops)`);break;case"gist-range":o.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${n} USING GIST (${r})`);break;case"gin-trigram":{let i=Ft.has(s.type)?`((${r} ->> 'label')) gin_trgm_ops`:`${r} gin_trgm_ops`;o.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${n} USING GIN (${i})`);break}case"none":break}if(s.type==="serial-number"){let i=ne(me("uidx",e,s.code,"serial"));o.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${i} ON ${n} (${r})`)}}return o}function ss(e,t,n,o){let s=tt(e),r=tt(t),a=ne(me("uidx",e,"environment_id","subtable-parent")),i=ne(me("idx",t,n,o,"subtable-child")),c=ne(me("fk",t,n,e)),u=ne(n),E=ne(o);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", ${u}, ${E}, "id")`,`DO $native_subtable$ BEGIN
|
|
2
2
|
ALTER TABLE ${r}
|
|
3
|
-
ADD CONSTRAINT ${
|
|
4
|
-
FOREIGN KEY ("tenant_id", "app_code", "environment_key", ${
|
|
5
|
-
REFERENCES ${
|
|
3
|
+
ADD CONSTRAINT ${c}
|
|
4
|
+
FOREIGN KEY ("tenant_id", "app_code", "environment_key", ${u})
|
|
5
|
+
REFERENCES ${s} ("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 pe(e,...t){return`${e}_${(0,cn.createHash)("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function Z(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function Ko(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":Dt.has(e.type)?"btree-snapshot-expressions":Lo.has(e.type)?"gin-jsonb-path":"btree":"none"}function qo(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 xo.has(e.type),"jsonb"}}function un(e,t){if(we(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=an(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${an(Ze(e,t.code))})::text, ${n}, '0'))`}function Xo(e,t){return dn.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:ko.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function Qe(e){return`"app_data".${Z(e)}`}function Ze(e,t){let o=pe("seq",e,t);return`"app_data".${Z(o)}`}function an(e){return`'${e.replace(/'/g,"''")}'`}var fn=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),Qo=new Set([...fn,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),pn=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Zo=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 Re(e,t){let o=_n(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 tt(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function St(e,t,o){if(!e||!t||!ti(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 ei(e,t){let o=_n(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 ti(e){let{field:t,valuePath:o}=e;if(!o)return!Qo.has(t.type);if(o==="value")return fn.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return pn.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function _n(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=>!pn.test(o)||Zo.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var ni=new Set(["option.single","user.single","department.single","resource-ref.single"]),oi=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),ii=new Set(["value","label","description","color"]),si=new Set(["avatarUrl","employeeNo","title","mobile","email"]),ri=new Set(["fullPath","parent.value","parent.label"]),ai=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),ci=new Set(["longitude","latitude","accuracy"]),di=new Set(["address","name","province","city","district","source"]);function li(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=fi(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 ui(e,t){if(ni.has(e.type)&&ii.has(t)||e.type==="user.single"&&si.has(t)||e.type==="department.single"&&ri.has(t))return ve(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&ai.has(t))return ve(t);if(e.type==="location"){if(ci.has(t))return{parts:[t],type:"number.decimal"};if(di.has(t))return ve(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function fi(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}`,oi.has(i.type)?i.type:"json"]]:[]})):{}}function ve(e){return{parts:e.split("."),type:"text.short"}}var nt=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function yt(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(E,N)=>{throw new nt(`${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 wt(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 pi(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 Vt(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 _i(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)?Vt(a[r]):null,l=n instanceof Date?n.getTime():Vt(n);return s===null||l===null||!Number.isFinite(l)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":l<s?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var ct=oo(require("crypto"),1);var En="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 er=5,tr=20,nr=50,or=50,ir=100,De=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function ke(e,t){let o=[],n=(i,r,a)=>{a>5&&Le("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",r);let s=In(i,r),l=["allOf","anyOf"].filter(d=>d in s);if(l.length===0){o.push({rule:s,pointer:r}),o.length>50&&Le("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)&&Le("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",r),_.forEach((d,c)=>n(d,`${r}/${p}/${c}`,a+1))};return n(e,t,1),o}function Ft(e,t){ke(e,t);let o=(n,i)=>{let r=In(n,i);if(Array.isArray(r.allOf))return Pt(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=Pt(a.flatMap(_=>p.map(d=>[..._,...d])),i)}),a}return[[r]]};return Pt(o(e,t),t)}function Pt(e,t){let o=e.reduce((n,i)=>n+i.length,0);return(e.length>50||o>100)&&Le("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function In(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&Le("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function Le(e,t){throw new De(e,t)}var Ei="openxiangda.config-bundle/v3",vn="openxiangda.contract-bundle/v3",mn="openxiangda.native-configuration-projection/v1",Ue=En,Ai=/^[a-f0-9]{64}$/,Ii=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,mi=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,Ni=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,gi=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,Ti=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Ci=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Nn=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,bi=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,Oi=/^[A-Z][A-Z0-9_]*$/,$i=/^[a-z][a-z0-9-]{2,63}$/,hi=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Ri=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,Di=16,Si=2*1024,yi=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"]),Vi=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),wi=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Pi=4*1024*1024,Fi=8*1024*1024,vi=40,Li=1e5,Lt=1024*1024,ki="openxiangda.event-handler-manifest/v2",Ln="openxiangda.application-route-manifest/v3",gn=64,xi=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),H=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}),ot=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],it=["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"],Ui=new Set(it),st=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 Mi(e){let t=$(e.appCode,"/appCode",128);Ii.test(t)||u("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=xt(e.expectedConfigDigest,"/expectedConfigDigest"),n=xt(e.expectedContractDigest,"/expectedContractDigest"),i=wn(e.configBytes,Pi,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),r=wn(e.contractBytes,Fi,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");Pn(i,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),Pn(r,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let a=yn(i,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),s=yn(r,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");Vn(a,"/config"),Vn(s,"/contracts");let l=a,p=s;Wi(l,t),Bi(p,t,o);let _=Ji(l,o,p.generatorVersion);Rs(_,p,l),K(_)!==K(p)&&u("NATIVE_CONTRACT_CLOSURE_MISMATCH",Ut(_,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:xn({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:Se(d.authz),data:Se(d.data),events:Se(d.events),workflows:Se(d.workflows),runtime:Se(d.runtime),contracts:Se(d.contracts)},A={configDigest:o,contractDigest:n,generatorVersion:p.generatorVersion},f=kn(l),E={schemaVersion:mn,compilerContractVersion:Ue,appCode:t,source:A,projections:c,requiredPlatformCapabilities:f,aggregateDigest:X({schemaVersion:mn,compilerContractVersion:Ue,appCode:t,source:A,requiredPlatformCapabilities:f,projectionDigests:Object.fromEntries(Object.entries(c).map(([N,m])=>[N,m.digest]))})};return qn(E)}function kn(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(Nt)?[{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 xn(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 ke(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)ot.includes(B)&&m.add(B);for(let B of ji(x,`/capturePlan/subscriptions/${O}/filter`))E.add(B);let te=I(V.payload||{},`/capturePlan/subscriptions/${O}/payload`);for(let B of h(te.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>gn&&u("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",s,{resourceCode:p,maximum:gn});for(let O of T)!d.has(O)&&!(f.has(O)&&xi.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 ji(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 Wi(e,t){C(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),v(e.schemaVersion,Ei,"/config/schemaVersion"),v(e.compilerContractVersion,Ue,"/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),Ts(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"),Ve(l.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),Mt(s.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(s,"authentication")&&Mn(s.authentication,s.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(s,"publicAccess")&&ns(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&<(p.access,"/config/frontend/admin/access",e.appCode),rs(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 Bi(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,vn,"/contracts/schemaVersion"),v(e.compilerContractVersion,Ue,"/contracts/compilerContractVersion"),$(e.generatorVersion,"/contracts/generatorVersion",128),v(e.appCode,t,"/contracts/appCode"),v(e.configDigest,o,"/contracts/configDigest"),h(e.perspectives,"/contracts/perspectives",H.perspectives),h(e.resources,"/contracts/resources",H.resources),h(e.capabilities,"/contracts/capabilities",H.capabilities),h(e.operations,"/contracts/operations",H.operations),h(e.eventConsumers,"/contracts/eventConsumers",H.eventConsumers),h(e.eventProducers,"/contracts/eventProducers",H.eventProducers),h(e.eventSchemas,"/contracts/eventSchemas",H.eventSchemas),I(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),F(e.eventTypes,"/contracts/eventTypes",H.eventTypes),h(e.workflows,"/contracts/workflows",H.workflows),h(e.routes,"/contracts/routes",H.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&Zi(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&os(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&<(e.adminAccess,"/contracts/adminAccess",t),fs(e.routeManifest,"/contracts/routeManifest",t),ds(e.adminPages,"/contracts/adminPages"),ls(e.adminNavigation,"/contracts/adminNavigation")}function Ji(e,t,o){let n=Yi(e);Is(e,n),Ns(e),ms(e),Cs(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([...ot,...it,...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=yt(E,e.data.resources,f),g=zi(E.delivery,N,`${f}/delivery`),T=Gi(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=>ot.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?it.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))]);cs(e);let d=Bn(e);return{schemaVersion:vn,compilerContractVersion:Ue,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:Hi(e),capabilities:ne(n,c=>c.code),operations:Un(e),eventConsumers:s,eventProducers:p,eventSchemas:i,eventHandlerManifest:{schemaVersion:ki,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:zn(e),routes:dt(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:es(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:is(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:Es(e),adminPages:d,adminNavigation:ss(e)}}function Gi(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 zi(e,t,o){let n=I(e,o);C(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),ee(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),ee(n.maxAttempts,`${o}/maxAttempts`,1,12);let i=ee(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);ee(n.maxBackoffMs,`${o}/maxBackoffMs`,i,18e5),ee(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=>!Ui.has(a))&&u("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function Yi(e){let t=new Map;for(let o of Kn(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:Wt(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=Me(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(Oe(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 Hi(e){let t=Ki(e);return ne(e.data.resources.map((o,n)=>{let i=Me(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 Ki(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=Me(r,s,e.appCode);return[l.code,l]})),n=new Map(dt(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 Un(e){let t=new Map(e.data.resources.map((i,r)=>{let a=`/config/data/resources/${r}`,s=Me(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)=>ut(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`);Xi(s.ai,a,p,l,o);let _=qi(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:Wt(s.description,`${a}/description`,2e3)},..._?{platformAccess:_}:{}}}),i=>i.code)}function qi(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 Xi(e,t,o,n,i){if(e===void 0)return;let r=`${t}/ai`,a=I(e,r);gi.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`,Lt),$(a.description,`${r}/description`,Lt);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&&ee(a.timeoutMs,`${r}/timeoutMs`,100,3e4)}function rt(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function Qi(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=Ve(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 Tn(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 Mn(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)=>Qi(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=Tn(_.desktop,"desktop",`${n}/surfaces/desktop`),c=Tn(_.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=jn(o).filter(m=>!m.owner.startsWith("authentication:"));for(let[m,g]of[["desktop",d],["mobile",c]]){let T=N.find(D=>rt(D.path)===rt(g.path));T&&u("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${m}/path`,{owner:T.owner})}}function Zi(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"}}};Mn(r,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:r}},t)}function es(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 ts=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function ns(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=>!ts.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 te=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=>Pe(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)?te.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`),ee(S.inactivityTtlSeconds,`${d}/draft/inactivityTtlSeconds`,3600,7776e3),ee(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 os(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 is(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 jn(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 dt(e){let t=new Map(jn(e).map(o=>[rt(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=rt(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),_=jt(r,i,e.appCode),d=r.pinned===void 0?void 0:Ve(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 Bn(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:Xe(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 dt(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 Jn(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function ss(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:Jn(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 rs(e,t){let o=h(e,t,H.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),at(s.icon,`${a}/icon`),hn(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>H.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),as(c.page,`${d}/page`),c.label!==void 0&&$(c.label,`${d}/label`,255),at(c.icon,`${d}/icon`),hn(c.order,`${d}/order`)})})}function as(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 cs(e){let t=new Map(Bn(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}`,_=Jn(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 ds(e,t){let o=h(e,t,H.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),Ve(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 ls(e,t){let o=h(e,t,H.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),at(s.icon,`${a}/icon`),ee(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>H.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),at(c.icon,`${d}/icon`),ee(c.order,`${d}/order`,-1e4,1e4)})})}var us=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function fs(e,t,o){let n=I(e,t);C(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),v(n.schemaVersion,Ln,`${t}/schemaVersion`),v(n.appCode,o,`${t}/appCode`),Mt(n.devicePolicy,`${t}/devicePolicy`),ps(n.rootEntry,`${t}/rootEntry`),_s(n.authentication,`${t}/authentication`),xt(n.digest,`${t}/digest`);let i=h(n.routes,`${t}/routes`,H.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(us.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=bn(p.desktop,`${l}/desktop`,o),f=bn(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 Mt(e,t){let o=I(e,t);C(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),v(o.kind,"viewport-family",`${t}/kind`);let n=ee(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),i=ee(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 ps(e,t){let o=I(e,t);C(o,["code","desktop","mobile"],t);let n=y(o.code,`${t}/code`),i=kt(o.desktop,`${t}/desktop`),r=kt(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 _s(e,t){let o=I(e,t);C(o,["desktop","mobile"],t);let n=Cn(o.desktop,`${t}/desktop`,!1),i=Cn(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 Cn(e,t,o){let n=I(e,t);C(n,["routeCode","path"],t);let i=y(n.routeCode,`${t}/routeCode`),r=kt(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 kt(e,t){let o=se(e,t);return/[:*?#\\\\]/.test(o)&&u("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function bn(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}`)}),K(a)!==K(Gn(i))&&u("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),jt(n,t,o),n.requiresAuthentication!==!0&&u("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function Gn(e){return U([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function On(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:Gn(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function $n(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 Es(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:On($n(f,"desktop",m,T),E,"user",g),mobile:On($n(f,"mobile",m,T),N,"user",g)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let i=zn(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=dt(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=Mt(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),_=s("desktop"),d=s("mobile"),c={schemaVersion:Ln,appCode:t,devicePolicy:p,rootEntry:{code:_.code,desktop:_.path,mobile:d.path},authentication:l,routes:r};return{...c,digest:X(c)}}function at(e,t){if(e===void 0)return;let o=$(e,t,32);Vi.has(o)||u("NATIVE_ADMIN_ICON_INVALID",t)}function hn(e,t){e!==void 0&&ee(e,t,-1e4,1e4)}function jt(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:lt(e.access,`${t}/access`,o)}}function lt(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 zn(e){let t=new Map(Un(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:Hn(s.detailRouteCode,`${a}/detailRouteCode`);return{code:y(l.code,`${a}/definition/code`),title:$(l.title,`${a}/definition/title`,255),version:ye(s.version,`${a}/version`),launch:As(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:Fn(r.map(p=>p.version)),bindingVersions:Fn(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:ye(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 Yn(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 As(e,t,o,n,i){let r=Yn(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`),te=A.get(M),B=i.get(M),Ie=B?.platformAccess?.workflow?.codes;(!te||!B||B.method!=="POST"||!Array.isArray(Ie)||!Ie.includes(t.code))&&u("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",w);let ge=I(te.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){(!Nn.test(j)||!Object.prototype.hasOwnProperty.call(q,j))&&u("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${w}/inputs/${j}`);let Ce=`${w}/inputs/${j}`,ft=I(Y,Ce),Ne=$(ft.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(ft,["source"],Ce,Ne==="field"?["fieldCode"]:!1),L.set(Ne,(L.get(Ne)||0)+1),Ne==="field"){let je=z(ft.fieldCode,`${Ce}/fieldCode`);(k.has(je)||!c.has(je))&&u("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${Ce}/fieldCode`),k.add(je),W[j]={source:Ne,fieldCode:je}}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(te.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);(!Nn.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),te=z(x.fieldCode,`${w}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(M)||T.has(M)||!m.has(te))&&u("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",w),T.add(M),{queryParameter:M,fieldCode:te}}),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 Hn(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 Is(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(!Oe(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);K(N)!==K(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=jt(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 _=lt(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 ms(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=Me(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=Re(N.userIdField,E);tt(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=Re(V[x],E);St(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=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(...ke(c.readExpression,`${d}/readExpression`)),Ft(c.readExpression,`${d}/readExpression`))}catch(b){throw b instanceof De&&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",te=["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&&!te&&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 Ns(e){try{At(e.data.resources,"/config/data/resources")}catch(t){throw t instanceof le&&u(t.code,t.pointer),t}}function gs(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 _=Rn(l.resourceCode,`${s}/resourceCode`,o);Dn(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`),Sn(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 _=Rn(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`),Dn(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=Re(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`),Sn(l,s,_)}}function Rn(e,t,o){let n=G(e,t),i=o.get(n);return i||u("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),i}function Dn(e,t,o){let n=Re(e,o);tt(n)||u("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function Sn(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 Ts(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);bi.test(s)||u("NATIVE_SECRET_NAME_INVALID",`${r}/name`),(!Oi.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&&Ve(a.required,`${r}/required`),a.description!==void 0&&Wt(a.description,`${r}/description`,2e3)})}function Cs(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"]),Yn(E.launch,`${f}/launch`),E.detailRouteCode!==void 0){let T=Hn(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(te=>te[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}:${ye(E.version,`${f}/version`)}`;t.has(m)&&u("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",f),t.add(m),Os(N,`${f}/definition`),bs(N.subject,n,`${f}/definition/subject`);let g=wt(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}:${ye(f.version,`/config/workflows/bindings/${c}/version`)}`;r.has(N)&&u("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${c}`),r.add(N),$s(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}:${ye(E.definitionVersion,`${f}/definitionVersion`)}`,g=`${N}:${ye(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`),hs(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&&ee(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=ut(E.workflowCode,`${f}/workflowCode`),g=Bt(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&&Ve(E.required,`${f}/required`),E.maxItems!==void 0&&ee(E.maxItems,`${f}/maxItems`,1,200)})}function bs(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){Ri.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`,Di).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)||!yi.has(g)||g==="text.long"&&typeof T=="number"&&Number.isFinite(T)&&T>Si)&&u("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${f}`)}}}function Os(e,t){C(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands"]),v(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),ut(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),Bt(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))wi.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}`);xe(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 xe(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)){xe(n.left,`${t}/left`,o+1),xe(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)=>xe(a,`${t}/values/${s}`,o+1));return}if(["not","exists"].includes(i)){xe(n.value,`${t}/value`,o+1);return}u("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function $s(e,t){v(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),ut(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)){Bt(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 hs(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 Rs(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 Me(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=ze(a.fields,`${t}/schema/fields`),l=It(n.invariants,s,`${t}/invariants`),qe(n.surface,s,`${t}/surface`)}catch(c){throw c instanceof le&&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)&&!Oe(c)&&u("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${c}`);let f=`${t}/fieldPolicies/${c}`,E=I(A,f);Oe(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 Kn(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 yn(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 K(a)!==i&&u(n,t),a}function Vn(e,t){let o=0,n=(i,r,a)=>{if(o+=1,o>Li&&u("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",r),a>vi&&u("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",r),typeof i=="string"){Buffer.byteLength(i)>Lt&&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}`),Ds(s)&&u("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${r}/${s}`),n(l,`${r}/${s}`,a+1)};n(e,t,0)}function Ds(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function Se(e){return{value:e,digest:X(e)}}function wn(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 Pn(e,t,o,n){let i=ct.createHash("sha256").update(e).digest("hex");ct.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 Wt(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 Ni.test(o)||u("NATIVE_CODE_INVALID",t),o}function G(e,t){let o=$(e,t,64);return Ti.test(o)||u("NATIVE_RESOURCE_CODE_INVALID",t),o}function z(e,t){let o=$(e,t,63);return Ci.test(o)||u("NATIVE_FIELD_CODE_INVALID",t),o}function ut(e,t){let o=$(e,t,128);return $i.test(o)||u("NATIVE_WORKFLOW_CODE_INVALID",t),o}function Bt(e,t){let o=$(e,t,128);return hi.test(o)||u("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function Ae(e,t,o){let n=$(e,t,255);return mi.test(n)||u("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!Kn(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 ye(e,t){return(!Number.isInteger(e)||Number(e)<1)&&u("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function ee(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&u("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function Ve(e,t){return typeof e!="boolean"&&u("NATIVE_BOOLEAN_REQUIRED",t),e}function xt(e,t){let o=$(e,t,64).toLowerCase();return Ai.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 Fn(e){return[...new Set(e)].sort((t,o)=>t-o)}function ie(e,t){return e===t?0:e<t?-1:1}function qn(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>qn(t))),e}function Ut(e,t,o){if(vt(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(!vt(e[i],t[i]))return Ut(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(!vt(r,a))return Ut(r,a,`${o}/${i}`)}}return o}function vt(e,t){return e===void 0||t===void 0?e===t:K(e)===K(t)}function u(e,t,o={}){throw new st(e,t,o)}var Ss="7f24caff61e91c02bf2731b154aa24d0033458ae21206175ebfc772ea135bb18";0&&(module.exports={DATA_AUDIT_METADATA_FIELDS,DATA_EVENT_TYPES_V2,DATA_SYSTEM_SORT_FIELD_CODES,NATIVE_CONFIGURATION_VALIDATOR_DIGEST,NATIVE_CONTRACT_CAPACITY_V2,NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,NATIVE_DATA_QUERY_OPERATORS_V2,NativeConfigurationCompilerError,NativeDataFieldContractV2Error,NativeDataPolicyExpressionV2Error,NativeEventActionContractError,NativeScopeSourceFieldPathV2Error,OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,WORKFLOW_EVENT_TYPES_V2,compileNativeApplicationConfiguration,compileNativeEventAction,compileNativeEventCapturePlansV2,compileRequiredPlatformCapabilitiesV3,hasDataAuditReadPolicy,isDataAuditMetadataField,isDataSystemSortField,isNativeDataQueryOperatorV2,isNativeMultiValueFieldV2,materializeNativeDataQueryPathTypesV2,nativeDataPolicyExpressionLeavesV2,nativeDataPolicyExpressionToCnfV2,nativeDataQueryPathPlanV2,nativeFieldAggregatePlanV2,nativeFieldColumnDefinitionV2,nativeFieldDefaultSqlV2,nativeFieldHasDefaultV2,nativeFieldIndexStatementsV2,nativeFieldRequiresCreateInputV2,nativeFieldSequenceGrantStatementsV2,nativeFieldSequenceOwnershipStatementsV2,nativeFieldSequenceStatementsV2,nativeFieldSupportsFilterV2,nativeFieldSupportsOperatorV2,nativeFieldSupportsSearchV2,nativeFieldSupportsSortV2,nativeOperatorsForFieldV2,nativePhysicalFieldV2,nativePhysicalFieldsV2,nativePhysicalObjectNameV2,nativeScopeSourceFieldValueV2,nativeScopeSourceGrantPathSupportedV2,nativeScopeSourceSubjectPathSupportedV2,nativeSubtableConstraintStatementsV2,parseNativeDataFieldsV2,parseNativeDataResourceInvariantsV2,projectNativeDataResourceViewV2,quoteNativeIdentifierV2,resolveNativeScopeSourceFieldPathV2,validateNativeDataResourceReferencesV2,validateNativeDataResourceSurfaceV2,validateWorkflowInstanceCommandPolicies,workflowInstanceCommandDeadlineError,workflowInstanceTerminateCapabilityAllowed,workflowPolicyTimestamp});
|
|
8
|
+
END $native_subtable$`]}function me(e,...t){return`${e}_${(0,pn.createHash)("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function ne(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function is(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":Ft.has(e.type)?"btree-snapshot-expressions":zo.has(e.type)?"gin-jsonb-path":"btree":"none"}function rs(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 qo.has(e.type),"jsonb"}}function mn(e,t){if(Le(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let n=En(t.serial?.prefix||""),o=t.serial?.digits??6;return`(${n} || lpad(nextval(${En(nt(e,t.code))})::text, ${o}, '0'))`}function as(e,t){return An.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:Yo.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function tt(e){return`"app_data".${ne(e)}`}function nt(e,t){let n=me("seq",e,t);return`"app_data".${ne(n)}`}function En(e){return`'${e.replace(/'/g,"''")}'`}var Nn=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),cs=new Set([...Nn,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),Tn=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,ds=new Set(["__proto__","prototype","constructor"]),ot=class extends Error{constructor(n){super("OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID");this.path=n;this.name="NativeScopeSourceFieldPathV2Error"}path;code="OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID"};function ye(e,t){let n=gn(e);if(!n)return null;let o=t.get(n[0]);if(!o)return null;let s=n.slice(1).join(".")||void 0;return{field:o,...s?{valuePath:s}:{}}}function st(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function Pt(e,t,n){if(!e||!t||!us(e))return!1;let{field:o,valuePath:s}=e;if(!s)return t.valueType==="uuid"?o.type==="uuid":["text.short","text.long","serial-number"].includes(o.type);if(s==="value")return!(t.valueSourceResourceCode&&o.type.startsWith("resource-ref.")&&o.source?.resourceCode!==t.valueSourceResourceCode);let r=s.slice(9),i=n.get(o.source?.resourceCode||"")?.get(r)?.type;return t.valueType==="uuid"?i==="uuid":["text.short","text.long","serial-number"].includes(i||"")}function ls(e,t){let n=gn(t);if(!n)throw new ot(String(t||""));let o=e;for(let s of n){if(!o||typeof o!="object"||!Object.prototype.hasOwnProperty.call(o,s))return;o=o[s]}return o}function us(e){let{field:t,valuePath:n}=e;if(!n)return!cs.has(t.type);if(n==="value")return Nn.has(t.type);if(!n.startsWith("snapshot."))return!1;let o=n.slice(9);return Tn.test(o)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(o)}function gn(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(n=>!Tn.test(n)||ds.has(n))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var fs=new Set(["option.single","user.single","department.single","resource-ref.single"]),_s=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),Es=new Set(["value","label","description","color"]),ps=new Set(["avatarUrl","employeeNo","title","mobile","email"]),As=new Set(["fullPath","parent.value","parent.label"]),Is=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),ms=new Set(["longitude","latitude","accuracy"]),Ns=new Set(["address","name","province","city","district","source"]);function Ts(e){let t=new Map(e.map(n=>[n.code,new Map(n.schema.fields.map(o=>[o.code,o]))]));return e.map(n=>({...n,schema:{...n.schema,fields:n.schema.fields.map(o=>{let s=bs(o,t);if(!Object.keys(s).length)return o;let r={...o};return Object.defineProperty(r,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(s)}),r})}}))}function gs(e,t){if(fs.has(e.type)&&Es.has(t)||e.type==="user.single"&&ps.has(t)||e.type==="department.single"&&As.has(t))return Ue(t);if(e.type==="resource-ref.single"){let n=e.queryPathTypes?.[t];return n?{parts:t.split("."),type:n}:null}if(e.type==="address"&&Is.has(t))return Ue(t);if(e.type==="location"){if(ms.has(t))return{parts:[t],type:"number.decimal"};if(Ns.has(t))return Ue(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function bs(e,t){if(e.type!=="resource-ref.single"||!e.source)return{};let n=t.get(e.source.resourceCode);return n?Object.fromEntries((e.source.snapshotFields||[]).flatMap(o=>{let s=n.get(o);return s?[[`snapshot.${o}`,_s.has(s.type)?s.type:"json"]]:[]})):{}}function Ue(e){return{parts:e.split("."),type:"text.short"}}var it=class extends Error{constructor(n,o){super(o);this.pointer=n}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function Lt(e,t,n="/events/subscriptions"){if(e.execution===void 0)return;let o=(A,N)=>{throw new it(`${n}${A}`,N)},s=(A,N,m)=>((!A||typeof A!="object"||Array.isArray(A)||Object.keys(A).some(T=>!m.includes(T)))&&o(N,"Invalid action object or unsupported property"),A),r=s(e.execution,"/execution",["kind","version","operations"]);(r.kind!=="native-data"||r.version!==1)&&o("/execution","Expected native-data version 1"),e.platformAccess&&o("/platformAccess","Native actions do not use application runtime capabilities"),(!Array.isArray(e.eventTypes)||!e.eventTypes.length||e.eventTypes.some(A=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(A)))&&o("/eventTypes","Native data actions require declared data events");let a=e.filter?.resourceCodes;(!Array.isArray(a)||!a.length||a.length>20)&&o("/filter/resourceCodes","Native actions require explicit source resources");let i=new Map(t.map(A=>[A.code,A])),c=a.map(A=>{let N=i.get(A);return N||o("/filter/resourceCodes","Unknown source resource"),new Set((N.schema?.fields||[]).map(m=>m.code))}),u=new Set(e.payload?.fields||[]),E=e.payload?.includeChanges===!0,d=(A,N)=>{let m=s(A,N,["source","path","value"]);if(m.source==="literal"){(!Object.hasOwn(m,"value")||Object.hasOwn(m,"path"))&&o(N,"Literal binding requires only value");let b;try{b=JSON.stringify(m.value)}catch{o(N,"Literal must be JSON")}return(b===void 0||Buffer.byteLength(b)>65536)&&o(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"))&&o(N,"Expected a literal or event binding");let T=m.path.split(".");(T.length>8||T.some(b=>!/^[A-Za-z0-9_-]+$/.test(b)||["__proto__","prototype","constructor"].includes(b)))&&o(N,"Invalid event path");let C=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(m.path),$=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(m.path);if(C||$){let b=(C||$)[1];c.some(g=>!g.has(b))&&o(N,"Source field must exist on every filtered resource"),u.add(b),$&&(E=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(m.path)||o(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)&&o("/execution/operations","Expected 1 to 16 operations");let f={},p=r.operations.map((A,N)=>{let m=`/execution/operations/${N}`,T=s(A,m,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(T.operation)||o(m,"Unsupported Native operation");let C=i.get(T.resourceCode);C||o(m,"Unknown action target resource");let $=new Map((C.schema?.fields||[]).map(g=>[g.code,g])),b=T.data===void 0?{}:s(T.data,`${m}/data`,[...$.keys()]);return Object.keys(b).length>32&&o(m,"Maximum 32 mapped fields per operation"),T.operation==="create"&&(T.id!==void 0||T.expectedRevision!==void 0)&&o(m,"Create does not accept id or expectedRevision"),T.operation==="delete"&&T.data!==void 0&&o(m,"Delete does not accept data"),Object.keys(b).some(g=>$.get(g)?.type==="serial-number")&&o(m,"Generated fields cannot be assigned"),f[T.resourceCode]=ee(C),{operation:T.operation,resourceCode:T.resourceCode,...T.operation==="create"?{}:{id:d(T.id,`${m}/id`),expectedRevision:d(T.expectedRevision,`${m}/expectedRevision`)},...T.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(b).map(([g,D])=>[g,d(D,`${m}/data/${g}`)]))}}});(u.size>32||[...u].some(A=>c.some(N=>!N.has(A))))&&o("/payload/fields","Payload must contain at most 32 declared source fields");let _={kind:"native-data",version:1,operations:p,resourceDigests:f};return Buffer.byteLength(JSON.stringify(_))>65536&&o("/execution","Action plan exceeds 64 KiB"),{execution:{..._,digest:ee(_)},payload:{includeChanges:E,fields:[...u].sort()}}}function ge(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function kt(e,t){if(e?.instanceCommands===void 0)return[];let n=ge(e.instanceCommands);if(!n||!Object.keys(n).length||Object.keys(n).some(s=>!["withdraw","terminate"].includes(s)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let o=[];for(let[s,r]of Object.entries(n)){let a=ge(r),i=s==="withdraw"?["beforeFact"]:["beforeFact","capability"];if(!a||Object.keys(a).some(c=>!i.includes(c))){o.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${s}`);continue}if(s==="terminate"){let c=a.capability;(typeof c!="string"||c.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(c)||t&&(!c.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(c)))&&o.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(s==="withdraw"||a.beforeFact!==void 0){let c=a.beforeFact,u=ge(e.inputSchema),E=ge(ge(u?.properties)?.[c]),d=ge(ge(e.subject)?.factProjection)?.[c],f=t?.fields.get(d);(typeof c!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(c)||!Array.isArray(u?.required)||!u.required.includes(c)||E?.type!=="string"||E?.format!=="date-time"||typeof d!="string"||t&&(f?.type!=="datetime"||f.nullable===!0))&&o.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${s}`)}}return o}function Cs(e,t){let n=e?.terminate?.capability;return typeof n=="string"&&/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(n)&&t.includes(n)}function vt(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[,n,o,s,r,a,i]=t,c=t[8],u=new Date(Date.UTC(Number(n),Number(o),0)).getUTCDate();if(Number(o)<1||Number(o)>12||Number(s)<1||Number(s)>u||Number(r)>23||Number(a)>59||Number(i)>59||c!=="Z"&&(Number(c.slice(1,3))>23||Number(c.slice(4))>59))return null;let E=Date.parse(e);return Number.isFinite(E)?E:null}function Os(e,t,n,o){let s=e?.[t];if(!s||t==="terminate"&&s.beforeFact===void 0)return null;let r=s.beforeFact,a=ge(n),i=r&&a&&Object.hasOwn(a,r)?vt(a[r]):null,c=o instanceof Date?o.getTime():vt(o);return i===null||c===null||!Number.isFinite(c)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":c<i?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var ut=fo(require("crypto"),1);var bn="native-4",Cn={"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 pr=5,Ar=20,Ir=50,mr=50,Nr=100,Ve=class extends Error{constructor(n,o){super(n);this.code=n;this.pointer=o;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function Me(e,t){let n=[],o=(s,r,a)=>{a>5&&xe("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",r);let i=On(s,r),c=["allOf","anyOf"].filter(d=>d in i);if(c.length===0){n.push({rule:i,pointer:r}),n.length>50&&xe("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",r);return}let u=c[0],E=i[u];(c.length!==1||Object.keys(i).length!==1||!Array.isArray(E)||E.length<1||E.length>20)&&xe("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",r),E.forEach((d,f)=>o(d,`${r}/${u}/${f}`,a+1))};return o(e,t,1),n}function xt(e,t){Me(e,t);let n=(o,s)=>{let r=On(o,s);if(Array.isArray(r.allOf))return Ut(r.allOf.flatMap((a,i)=>n(a,`${s}/allOf/${i}`)),s);if(Array.isArray(r.anyOf)){let a=[[]];return r.anyOf.forEach((i,c)=>{let u=n(i,`${s}/anyOf/${c}`);a=Ut(a.flatMap(E=>u.map(d=>[...E,...d])),s)}),a}return[[r]]};return Ut(n(e,t),t)}function Ut(e,t){let n=e.reduce((o,s)=>o+s.length,0);return(e.length>50||n>100)&&xe("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function On(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&xe("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function xe(e,t){throw new Ve(e,t)}var $s="openxiangda.config-bundle/v3",Bn="openxiangda.contract-bundle/v3",$n="openxiangda.native-configuration-projection/v1",Be=bn,Rs=/^[a-f0-9]{64}$/,hs=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Ss=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,Ds=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,ys=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,Vs=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,ws=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Rn=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,Fs=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,Ps=/^[A-Z][A-Z0-9_]*$/,Ls=/^[a-z][a-z0-9-]{2,63}$/,vs=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,ks=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,Us=16,xs=2*1024,Ms=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"]),js=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),Bs=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Js=4*1024*1024,Ws=8*1024*1024,Gs=40,zs=1e5,jt=1024*1024,Ys="openxiangda.event-handler-manifest/v2",Jn="openxiangda.application-route-manifest/v3",hn=64,Wn=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),q=Object.freeze({perspectives:100,resources:100,subjectReadSurfaces:50,capabilities:2e3,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:100,routes:500,adminPages:500,adminNavigationGroups:100,adminNavigationItems:500}),rt=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],at=["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"],qs=new Set(at),ct=class extends Error{code;pointer;identifiers;constructor(t,n,o={}){super(t),this.name="NativeConfigurationCompilerError",this.code=t,this.pointer=n,this.identifiers=Object.fromEntries(Object.entries(o).slice(0,8).map(([s,r])=>[s,String(r).slice(0,128)]))}};function Ks(e){let t=h(e.appCode,"/appCode",128);hs.test(t)||l("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let n=Jt(e.expectedConfigDigest,"/expectedConfigDigest"),o=Jt(e.expectedContractDigest,"/expectedContractDigest"),s=xn(e.configBytes,Js,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),r=xn(e.contractBytes,Ws,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");Mn(s,n,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),Mn(r,o,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let a=kn(s,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),i=kn(r,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");Un(a,"/config"),Un(i,"/contracts");let c=a,u=i;Xs(c,t),Qs(u,t,n);let E=Zs(c,n,u.generatorVersion);xi(E,u,c),Q(E)!==Q(u)&&l("NATIVE_CONTRACT_CLOSURE_MISMATCH",Wt(E,u,"/contracts"));let d={authz:{appCode:t,...c.authz,perspectives:c.perspectives,capabilityCatalog:E.capabilities},data:{appCode:t,resources:c.data.resources,resourceContracts:E.resources,...E.subjectReadSurfaces?{subjectReadSurfaces:E.subjectReadSurfaces}:{}},events:{appCode:t,...c.events,consumers:E.eventConsumers,producers:E.eventProducers,handlerManifest:E.eventHandlerManifest,eventTypes:E.eventTypes,capturePlans:zn({resources:c.data.resources,dataPolicies:c.authz.dataPolicies,subscriptions:E.eventConsumers,capturePolicies:c.events.capturePolicies})},workflows:{appCode:t,...c.workflows,contracts:E.workflows},runtime:{appCode:t,requirements:c.runtime,backend:c.backend,frontend:c.frontend},contracts:E},f={authz:we(d.authz),data:we(d.data),events:we(d.events),workflows:we(d.workflows),runtime:we(d.runtime),contracts:we(d.contracts)},p={configDigest:n,contractDigest:o,generatorVersion:u.generatorVersion},_=Gn(c),A={schemaVersion:$n,compilerContractVersion:Be,appCode:t,source:p,projections:f,requiredPlatformCapabilities:_,aggregateDigest:ee({schemaVersion:$n,compilerContractVersion:Be,appCode:t,source:p,requiredPlatformCapabilities:_,projectionDigests:Object.fromEntries(Object.entries(f).map(([N,m])=>[N,m.digest]))})};return so(A)}function Gn(e){let t=e.authz.roles,n=e.data.resources,o=e.backend.operations,s=t.some(_=>_.capabilities.some(A=>A.endsWith(":directory:read")))||n.some(_=>_.schema.fields.some(A=>["user.single","user.multiple","department.single","department.multiple"].includes(A.type)))||o.some(_=>_.platformAccess?.directory),r=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),a=o.some(_=>_.platformAccess?.managedFiles||_.platformAccess?.managedFileCopies)||e.events.subscriptions.some(_=>_.platformAccess?.managedFileCopies),i=o.some(_=>_.platformAccess?.notification)||e.events.subscriptions.some(_=>_.platformAccess?.notification),c=e.workflows.definitions.filter(_=>_.launch.mode==="standalone"||_.launch.mode==="hidden-handoff"),u=o.some(_=>_.platformAccess?.workflow)||c.length>0,E={resources:n},d={perspectives:e.perspectives,authz:e.authz},f={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:o.map(_=>({code:_.code,method:_.method,path:_.path,capability:_.capability,platformAccess:_.platformAccess||null,..._.browser?{browser:_.browser}:{},ai:_.ai||null}))}};return[{code:"application-native-2",declaration:f},{code:"authz.native-batch-explain",declaration:d},{code:"authz.native-management",declaration:d},{code:"deployment.durable-runs",declaration:f.backend},{code:"deployment.platform-executor",declaration:f.backend},{code:"environment.on-demand-production",declaration:{environments:["preproduction","production"]}},{code:"environment.runtime-lifecycle",declaration:{environments:["preproduction","production"]}},...n.length?[{code:"data-api-v2",declaration:E},{code:"data.native-golden-crud",declaration:E}]:[],...n.some(bt)?[{code:"data.audit-read-access",declaration:E}]:[],...s?[{code:"directory-v2",declaration:{roles:t.map(_=>({code:_.code,capabilities:_.capabilities.filter(A=>A.endsWith(":directory:read"))})),resources:n.map(_=>({code:_.code,fields:_.schema.fields.filter(A=>["user.single","user.multiple","department.single","department.multiple"].includes(A.type))})),operations:o.filter(_=>_.platformAccess?.directory).map(_=>({code:_.code,directory:_.platformAccess.directory}))}}]:[],...a?[{code:"data.managed-files",declaration:{operations:o.filter(_=>_.platformAccess?.managedFiles||_.platformAccess?.managedFileCopies).map(_=>({code:_.code,..._.platformAccess?.managedFiles?{managedFiles:_.platformAccess.managedFiles}:{},..._.platformAccess?.managedFileCopies?{managedFileCopies:_.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(_=>_.platformAccess?.managedFileCopies).map(_=>({code:_.code,managedFileCopies:_.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(_=>_.execution)?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(_=>_.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(_=>_.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(_=>_.definition.instanceCommands!==void 0)}]:[],...u?[{code:"business-process.durable-command",declaration:{operations:o.filter(_=>_.platformAccess?.workflow).map(_=>({code:_.code,workflow:_.platformAccess.workflow})),definitions:c,activations:e.workflows.activations.filter(_=>c.some(A=>A.definition.code===_.workflowCode))}}]:[],...i?[{code:"notification-hub-v2",declaration:{operations:o.filter(_=>_.platformAccess?.notification).map(_=>({code:_.code,notification:_.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(_=>_.platformAccess?.notification).map(_=>({code:_.code,notification:_.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:_,declaration:A})=>({code:_,contractVersion:Cn[_],usageDigest:`sha256:${ee(A)}`})).sort((_,A)=>_.code===A.code?0:_.code<A.code?-1:1)}function zn(e){let t=new Map,n=new Set(e.resources.map(r=>String(r.code)));for(let[r,a]of R(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let i=`/capturePlan/capturePolicies/${r}`,c=I(a,i);O(c,["resourceCode","mode"],i);let u=z(c.resourceCode,`${i}/resourceCode`);n.has(u)||l("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",i,{resourceCode:u}),t.has(u)&&l("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",i,{resourceCode:u}),c.mode!=="all"&&c.mode!=="subscribed"&&l("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${i}/mode`),t.set(u,c.mode)}let o=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}`,c=I(r,i),u=z(c.code,`${i}/code`),E=c.schema?I(c.schema,`${i}/schema`):c,d=new Set(R(E.fields||[],`${i}/schema/fields`,500).map((g,D)=>W(I(g,`${i}/schema/fields/${D}`).code,`${i}/schema/fields/${D}/code`))),f=c.dataPolicyCode?w(c.dataPolicyCode,`${i}/dataPolicyCode`):null,p=f?o.get(f):void 0;f&&!p&&l("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",i,{resourceCode:u,dataPolicyCode:f});let _=new Set;for(let g of p?.rules||[])_.add(String(g.field));if(p?.readExpression)for(let g of Me(p.readExpression,`${i}/readExpression`))_.add(String(g.rule.field));let A=new Set,N=new Set,m=new Set;for(let[g,D]of s.entries()){let V=R(D.eventTypes,`/capturePlan/subscriptions/${g}/eventTypes`,20).map(String);if(!V.some(M=>M.startsWith("openxiangda.data.")))continue;let x=I(D.filter||{},`/capturePlan/subscriptions/${g}/filter`),k=Array.isArray(x.resourceCodes)?x.resourceCodes.map(String):[];if(k.length&&!k.includes(u))continue;for(let M of V)rt.includes(M)&&m.add(M);for(let M of Hs(x,`/capturePlan/subscriptions/${g}/filter`))A.add(M);let Y=I(D.payload||{},`/capturePlan/subscriptions/${g}/payload`);for(let M of R(Y.fields||[],`/capturePlan/subscriptions/${g}/payload/fields`,32))N.add(W(M,`/capturePlan/subscriptions/${g}/payload/fields`))}let T=new Set([...A,...N]),C=new Set([...T,..._]);C.size>hn&&l("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",i,{resourceCode:u,maximum:hn});for(let g of C)!d.has(g)&&!(_.has(g)&&Wn.has(g))&&l("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",i,{resourceCode:u,field:g});let $=I(c.fieldPolicies||{},`${i}/fieldPolicies`);for(let g of T)$[g]?.mask==="omit"&&l("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",i,{resourceCode:u,field:g});let b={resourceCode:u,...t.get(u)==="subscribed"?{capturedEventTypes:[...m].sort()}:{},filterFields:[...A].sort(),projectionFields:[...N].sort(),authorizationFields:[..._].sort(),captureFields:[...C].sort()};return{...b,digest:ee(b)}}).sort((r,a)=>r.resourceCode.localeCompare(a.resourceCode))}function Hs(e,t){let n=new Set;for(let[a,i]of R(e.changes||[],`${t}/changes`,16).entries()){let c=I(i,`${t}/changes/${a}`);n.add(W(c.field,`${t}/changes/${a}/field`))}let o=I(e.changedFields||{},`${t}/changedFields`);for(let a of["anyOf","allOf","noneOf"])for(let[i,c]of R(o[a]||[],`${t}/changedFields/${a}`,32).entries())n.add(W(c,`${t}/changedFields/${a}/${i}`));let s=0,r=(a,i,c)=>{c>3&&l("NATIVE_EVENT_FILTER_DEPTH_LIMIT",i);let u=I(a,i);if(u.change){let d=I(u.change,`${i}/change`);n.add(W(d.field,`${i}/change/field`)),s+=1;return}if(u.not){r(u.not,`${i}/not`,c+1);return}let E=u.all?"all":u.any?"any":null;E||l("NATIVE_EVENT_FILTER_CONDITION_INVALID",i);for(let[d,f]of R(u[E],`${i}/${E}`,16).entries())r(f,`${i}/${E}/${d}`,c+1)};return e.where&&r(e.where,`${t}/where`,1),s+=Array.isArray(e.changes)?e.changes.length:0,s>16&&l("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...n].sort()}function Xs(e,t){O(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),v(e.schemaVersion,$s,"/config/schemaVersion"),v(e.compilerContractVersion,Be,"/config/compilerContractVersion"),v(e.appCode,t,"/config/appCode"),R(e.perspectives,"/config/perspectives",100);let n=I(e.authz,"/config/authz");O(n,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),R(n.capabilities,"/config/authz/capabilities",2e3),R(n.roles,"/config/authz/roles",100),R(n.scopeDimensions,"/config/authz/scopeDimensions",100),R(n.scopeSources,"/config/authz/scopeSources",100),R(n.roleMembershipSources,"/config/authz/roleMembershipSources",100),R(n.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),R(n.dataPolicies,"/config/authz/dataPolicies",100),R(n.authorizationTransitions,"/config/authz/authorizationTransitions",100);let o=I(e.backend,"/config/backend");O(o,["secrets","operations"],"/config/backend"),R(o.secrets,"/config/backend/secrets",100),R(o.operations,"/config/backend/operations",500),Fi(o.secrets);let s=I(e.data,"/config/data");O(s,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces"]),R(s.resources,"/config/data/resources",100),s.subjectReadSurfaces!==void 0&&R(s.subjectReadSurfaces,"/config/data/subjectReadSurfaces",q.subjectReadSurfaces),s.resourceDetailRoutes!==void 0&&R(s.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let r=I(e.events,"/config/events");O(r,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),R(r.schemas,"/config/events/schemas",100),R(r.subscriptions,"/config/events/subscriptions",100),R(r.timers,"/config/events/timers",100),R(r.dateTriggers,"/config/events/dateTriggers",100);let a=I(e.workflows,"/config/workflows");O(a,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),R(a.definitions,"/config/workflows/definitions",100),R(a.bindings,"/config/workflows/bindings",100),R(a.activations,"/config/workflows/activations",100),R(a.providers,"/config/workflows/providers",100),R(a.editableParameters,"/config/workflows/editableParameters",100);let i=I(e.frontend,"/config/frontend");O(i,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),R(i.routes,"/config/frontend/routes",500);let c=I(i.user,"/config/frontend/user");O(c,["applicationTodoCenter"],"/config/frontend/user"),Pe(c.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),Gt(i.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(i,"authentication")&&qn(i.authentication,i.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(i,"publicAccess")&&Ei(i.publicAccess,e,"/config/frontend/publicAccess");let u=I(i.admin,"/config/frontend/admin");O(u,["navigation"],"/config/frontend/admin",["access"]),u.access!==void 0&&_t(u.access,"/config/frontend/admin/access",e.appCode),mi(u.navigation,"/config/frontend/admin/navigation");let E=I(e.runtime,"/config/runtime");O(E,["protocolCapabilities","health"],"/config/runtime"),F(E.protocolCapabilities,"/config/runtime/protocolCapabilities",100),O(I(E.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),v(E.health.livePath,"/__platform/health","/config/runtime/health/livePath"),v(E.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),v(E.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function Qs(e,t,n){O(e,["schemaVersion","compilerContractVersion","generatorVersion","appCode","configDigest","perspectives","resources","capabilities","operations","eventConsumers","eventProducers","eventSchemas","eventHandlerManifest","eventTypes","workflows","routes","routeManifest","adminPages","adminNavigation"],"/contracts",["authentication","publicAccess","adminAccess","subjectReadSurfaces"]),v(e.schemaVersion,Bn,"/contracts/schemaVersion"),v(e.compilerContractVersion,Be,"/contracts/compilerContractVersion"),h(e.generatorVersion,"/contracts/generatorVersion",128),v(e.appCode,t,"/contracts/appCode"),v(e.configDigest,n,"/contracts/configDigest"),R(e.perspectives,"/contracts/perspectives",q.perspectives),R(e.resources,"/contracts/resources",q.resources),e.subjectReadSurfaces!==void 0&&R(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",q.subjectReadSurfaces),R(e.capabilities,"/contracts/capabilities",q.capabilities),R(e.operations,"/contracts/operations",q.operations),R(e.eventConsumers,"/contracts/eventConsumers",q.eventConsumers),R(e.eventProducers,"/contracts/eventProducers",q.eventProducers),R(e.eventSchemas,"/contracts/eventSchemas",q.eventSchemas),I(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),F(e.eventTypes,"/contracts/eventTypes",q.eventTypes),R(e.workflows,"/contracts/workflows",q.workflows),R(e.routes,"/contracts/routes",q.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&ui(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&pi(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&_t(e.adminAccess,"/contracts/adminAccess",t),Oi(e.routeManifest,"/contracts/routeManifest",t),gi(e.adminPages,"/contracts/adminPages"),bi(e.adminNavigation,"/contracts/adminNavigation")}function Zs(e,t,n){let o=ni(e);Di(e,o),Vi(e),yi(e),Pi(e);let s=e.events.schemas.map((p,_)=>{let A=`/config/events/schemas/${_}`,N=I(p,A),m=h(N.eventType,`${A}/eventType`,255);return m.startsWith("openxiangda.")&&l("NATIVE_EVENT_SCHEMA_RESERVED",`${A}/eventType`,{eventType:m}),v(N.schemaDigest,ee(I(N.jsonSchema,`${A}/jsonSchema`)),`${A}/schemaDigest`),N}),r=new Set([...rt,...at,...s.map(p=>String(p.eventType))]),a=new Map(e.data.resources.map(p=>[String(p.code),new Map(p.schema.fields.map(_=>[String(_.code),String(_.type)]))])),i=X(e.events.subscriptions.map((p,_)=>{let A=`/config/events/subscriptions/${_}`,N=I(p,A),m=F(N.eventTypes,`${A}/eventTypes`,20);m.forEach((b,g)=>{r.has(b)||l("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${A}/eventTypes/${g}`,{eventType:b})});let T=Lt(N,e.data.resources,A),C=ti(N.delivery,m,`${A}/delivery`),$=ei(N.platformAccess,`${A}/platformAccess`,a);return{code:w(N.code,`${A}/code`),endpointPath:ce(N.endpointPath,`${A}/endpointPath`),eventTypes:m,filter:I(N.filter,`${A}/filter`),payload:T?.payload||I(N.payload,`${A}/payload`),...T?{execution:T.execution}:{},...$?{platformAccess:$}:{},delivery:C}}),p=>p.code),c=new Map(s.map(p=>[String(p.eventType),String(p.dataSchemaVersion)])),u=X([...e.data.resources.flatMap(p=>rt.map(_=>({code:`data:${p.code}:${_}`,source:"data",eventType:_,dataSchemaVersion:"2.0.0",resourceCode:p.code}))),...s.map(p=>({code:`app:${p.eventType}`,source:"app",eventType:p.eventType,dataSchemaVersion:p.dataSchemaVersion})),...e.events.timers.map(p=>({code:p.code,source:"timer",eventType:p.eventType,dataSchemaVersion:c.get(String(p.eventType))||"2.0.0"})),...e.events.dateTriggers.map(p=>({code:p.code,source:"date",eventType:p.eventType,dataSchemaVersion:c.get(String(p.eventType))||"2.0.0",resourceCode:p.resourceCode,field:p.field})),...e.workflows.activations.length?at.map(p=>({code:`workflow:${p}`,source:"workflow",eventType:p,dataSchemaVersion:"2.0.0"})):[]],p=>`${p.source}:${p.code}:${p.eventType}`),E=j([...i.flatMap(p=>p.eventTypes),...u.map(p=>String(p.eventType))]);Ti(e);let d=Xn(e),f=si(e,o);return{schemaVersion:Bn,compilerContractVersion:Be,generatorVersion:n,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:oi(e),...f.length?{subjectReadSurfaces:f}:{},capabilities:X(o,p=>p.code),operations:Yn(e),eventConsumers:i,eventProducers:u,eventSchemas:s,eventHandlerManifest:{schemaVersion:Ys,appCode:e.appCode,handlers:i.filter(p=>!p.execution).map(p=>({code:p.code,endpointPath:p.endpointPath,eventTypes:p.eventTypes,dataSchemaVersions:j(p.eventTypes.map(_=>_.startsWith("openxiangda.")?"2.0.0":c.get(_)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2}))},eventTypes:E,workflows:eo(e),routes:ft(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:fi(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:Ai(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:hi(e),adminPages:d,adminNavigation:Ii(e)}}function ei(e,t,n){if(e===void 0)return;let o=I(e,t);O(o,["notification","managedFileCopies"],t,!0);let s={};if(o.notification!==void 0){let r=I(o.notification,`${t}/notification`);O(r,["mode"],`${t}/notification`),v(r.mode,"business-standard",`${t}/notification/mode`),s.notification={mode:"business-standard"}}if(o.managedFileCopies!==void 0){let r=R(o.managedFileCopies,`${t}/managedFileCopies`,16);r.length||l("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let a=new Set;s.managedFileCopies=X(r.map((i,c)=>{let u=`${t}/managedFileCopies/${c}`,E=I(i,u);O(E,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],u),v(E.mode,"copy",`${u}/mode`);let d=z(E.sourceResourceCode,`${u}/sourceResourceCode`),f=z(E.targetResourceCode,`${u}/targetResourceCode`),p=n.get(d),_=n.get(f);(!p||!_)&&l("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",u);let A=F(E.sourceFieldCodes,`${u}/sourceFieldCodes`,16),N=F(E.targetFieldCodes,`${u}/targetFieldCodes`,16);(!A.length||A.length!==N.length)&&l("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",u),A.forEach((T,C)=>{let $=p.get(T),b=_.get(N[C]);(!["file","image"].includes(String($))||$!==b)&&l("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${u}/sourceFieldCodes/${C}`)});let m=`${d}:${A.join(",")}=>${f}:${N.join(",")}`;return a.has(m)&&l("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",u),a.add(m),{mode:"copy",sourceResourceCode:d,sourceFieldCodes:j(A),targetResourceCode:f,targetFieldCodes:j(N)}}),i=>`${i.sourceResourceCode}:${i.sourceFieldCodes.join(",")}=>${i.targetResourceCode}:${i.targetFieldCodes.join(",")}`)}return Object.keys(s).length||l("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),s}function ti(e,t,n){let o=I(e,n);O(o,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],n),Z(o.timeoutMs,`${n}/timeoutMs`,1e3,3e4),Z(o.maxAttempts,`${n}/maxAttempts`,1,12);let s=Z(o.initialBackoffMs,`${n}/initialBackoffMs`,1e3,3e5);Z(o.maxBackoffMs,`${n}/maxBackoffMs`,s,18e5),Z(o.concurrency,`${n}/concurrency`,1,50);let r=h(o.ordering,`${n}/ordering`,32);return["none","record","workflow-instance"].includes(r)||l("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${n}/ordering`),r==="workflow-instance"&&t.some(a=>!qs.has(a))&&l("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${n}/ordering`),o}function ni(e){let t=new Map;for(let n of oo(e.appCode))t.set(n.code,n);for(let[n,o]of e.authz.capabilities.entries()){let s=`/config/authz/capabilities/${n}`,r=I(o,s);O(r,["code","kind","name","description"],s,!0);let a=Ne(r.code,`${s}/code`,e.appCode);t.has(a)&&l("NATIVE_CAPABILITY_DUPLICATE",`${s}/code`),["backend","ui"].includes(r.kind)||l("NATIVE_CAPABILITY_KIND_INVALID",`${s}/kind`);let i={code:a,kind:r.kind,name:h(r.name,`${s}/name`,255),source:"explicit",...r.description===void 0?{}:{description:Yt(r.description,`${s}/description`,2e3)}};t.set(a,i)}for(let[n,o]of e.data.resources.entries()){let s=`/config/data/resources/${n}`,r=Ce(o,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 c=Ne(r.capabilities[i],`${s}/capabilities/${i}`,e.appCode);t.has(c)&&l("NATIVE_CAPABILITY_DUPLICATE",`${s}/capabilities/${i}`),t.set(c,{code:c,kind:"data",name:a[i],source:"data"})}for(let[i,c]of Object.entries(r.fieldPolicies)){if(Re(i))continue;let u=I(c,`${s}/fieldPolicies/${i}`);for(let E of["read","create","update"])if(Array.isArray(u[E]))for(let d of F(u[E],`${s}/fieldPolicies/${i}/${E}`,2e3))Ne(d,`${s}/fieldPolicies/${i}/${E}`,e.appCode),!t.has(d)&&t.set(d,{code:d,kind:"data",name:`${r.name}.${i}.${E}`,source:"data"})}}return[...t.values()]}function oi(e){let t=ii(e);return X(e.data.resources.map((n,o)=>{let s=Ce(n,`/config/data/resources/${o}`,e.appCode),r=t.get(s.code);return{code:s.code,schemaDigest:ee(s.schema),fields:X(s.schema.fields.map(a=>({code:a.code,type:a.type})),a=>a.code),...r?{detailRouteCode:r}:{}}}),n=>n.code)}function si(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let n=R(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",q.subjectReadSurfaces),o=new Set(t.map(a=>String(a.code))),s=new Map(e.data.resources.map((a,i)=>{let c=`/config/data/resources/${i}`,u=Ce(a,c,e.appCode);return[String(u.code),{resource:u,fields:new Map(R(I(u.schema,`${c}/schema`).fields,`${c}/schema/fields`,500).map(E=>{let d=I(E,`${c}/schema/fields`);return[String(d.code),d]}))}]})),r=new Set;return X(n.map((a,i)=>{let c=`/config/data/subjectReadSurfaces/${i}`,u=I(a,c);O(u,["code","name","capability","subject","relations"],c);let E=w(u.code,`${c}/code`);r.has(E)&&l("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${c}/code`),r.add(E);let d=Ne(u.capability,`${c}/capability`,e.appCode);o.has(d)||l("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${c}/capability`);let f=I(u.subject,`${c}/subject`);O(f,["resourceCode","fields"],`${c}/subject`);let p=z(f.resourceCode,`${c}/subject/resourceCode`),_=s.get(p);_||l("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${c}/subject/resourceCode`);let A=F(f.fields,`${c}/subject/fields`,100).map(($,b)=>W($,`${c}/subject/fields/${b}`));A.length||l("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${c}/subject/fields`);for(let[$,b]of A.entries()){let g=_.fields.get(b);(!g||g.type==="subtable")&&l("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${c}/subject/fields/${$}`)}let N=R(u.relations,`${c}/relations`,8);N.length||l("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${c}/relations`);let m=new Set,T=0,C=X(N.map(($,b)=>{let g=`${c}/relations/${b}`,D=I($,g);O(D,["code","resourceCode","foreignKeyField","fields","limit"],g,["order"]);let V=w(D.code,`${g}/code`);m.has(V)&&l("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${g}/code`),m.add(V);let x=z(D.resourceCode,`${g}/resourceCode`),k=s.get(x);k||l("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${g}/resourceCode`);let Y=W(D.foreignKeyField,`${g}/foreignKeyField`),M=k.fields.get(Y),de=I(M?.source||{},`${g}/foreignKeyField/source`);(!M||!["uuid","resource-ref.single"].includes(String(M.type))||M.type==="resource-ref.single"&&(de.kind!=="resource"||de.resourceCode!==p))&&l("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${g}/foreignKeyField`);let le=F(D.fields,`${g}/fields`,100).map((se,y)=>W(se,`${g}/fields/${y}`));le.length||l("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${g}/fields`);for(let[se,y]of le.entries()){let U=k.fields.get(y);(!U||U.type==="subtable")&&l("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${g}/fields/${se}`)}let K=R(D.order||[],`${g}/order`,10).map((se,y)=>{let U=`${g}/order/${y}`,P=I(se,U);O(P,["field","direction"],U);let B=W(P.field,`${U}/field`),J=k.fields.get(B);return(!Wn.has(B)&&!J||J?.type==="subtable"||J&&!Se(J.type))&&l("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${U}/field`),["asc","desc"].includes(String(P.direction))||l("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${U}/direction`),{field:B,direction:P.direction}}),Ee=Z(D.limit,`${g}/limit`,1,100);return T+=Ee,{code:V,resourceCode:x,foreignKeyField:Y,fields:j(le),...K.length?{order:K}:{},limit:Ee}}),$=>$.code);return T>400&&l("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${c}/relations`),{code:E,name:h(u.name,`${c}/name`,255),capability:d,subject:{resourceCode:p,fields:j(A)},relations:C}}),a=>a.code)}function ii(e){let t=e.data.resourceDetailRoutes===void 0?[]:R(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),n=new Map(e.data.resources.map((r,a)=>{let i=`/config/data/resources/${a}`,c=Ce(r,i,e.appCode);return[c.code,c]})),o=new Map(ft(e).map(r=>[String(r.code),r])),s=new Map;for(let[r,a]of t.entries()){let i=`/config/data/resourceDetailRoutes/${r}`,c=I(a,i);O(c,["resourceCode","desktop","mobile"],i);let u=z(c.resourceCode,`${i}/resourceCode`);s.has(u)&&l("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${i}/resourceCode`);let E=n.get(u);E||l("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${i}/resourceCode`);let d=w(c.desktop,`${i}/desktop`),f=w(c.mobile,`${i}/mobile`);d===f&&l("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",i);let p=String(E.capabilities.read);for(let[_,A]of[["desktop",d],["mobile",f]]){let N=`${i}/${_}`,m=o.get(A);m||l("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",N),m.surface!=="user"&&l("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",N);let T=ce(m.path,`${N}/path`),C=[...T.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],$=_==="mobile"?!T.startsWith("/m/"):T==="/m"||T.startsWith("/m/");(T.includes("*")||T.includes("?")||T.includes("#")||T.split("/").includes("..")||C.length!==1||$)&&l("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",N);let b=Array.isArray(m.access?.allOf)?m.access.allOf:[];m.capability!==p&&!b.includes(p)&&l("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",N)}s.set(u,{desktop:d,mobile:f})}return s}function Yn(e){let t=new Map(e.data.resources.map((r,a)=>{let i=`/config/data/resources/${a}`,c=Ce(r,i,e.appCode);return[c.code,new Map(c.schema.fields.map(u=>[String(u.code),u]))]})),n=new Map(e.data.resources.map((r,a)=>{let i=`/config/data/resources/${a}`,c=Ce(r,i,e.appCode);return[c.code,new Map(c.schema.fields.map(u=>[String(u.code),String(u.type)]))]})),o=new Set(n.keys()),s=new Set(e.workflows.activations.map((r,a)=>Et(I(r,`/config/workflows/activations/${a}`).workflowCode,`/config/workflows/activations/${a}/workflowCode`)));return X(e.backend.operations.map((r,a)=>{let i=`/config/backend/operations/${a}`,c=I(r,i);O(c,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],i,!0);let u=h(c.method,`${i}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(u)||l("NATIVE_OPERATION_METHOD_INVALID",`${i}/method`);let E=w(c.code,`${i}/code`);di(c.ai,i,E,u,o);let d=ci(c.platformAccess,`${i}/platformAccess`,n,s,new Set(e.authz.roles.map(p=>String(p.code)))),f=ri(c.browser,`${i}/browser`,u,c.requestSchema,c.responseSchema,n,t,e.data.subjectReadSurfaces||[]);return{code:E,method:u,path:ce(c.path,`${i}/path`),requiredCapability:Ne(c.capability,`${i}/capability`,e.appCode),requestSchemaDigest:ee(I(c.requestSchema,`${i}/requestSchema`)),responseSchemaDigest:ee(I(c.responseSchema,`${i}/responseSchema`)),...c.description===void 0?{}:{description:Yt(c.description,`${i}/description`,2e3)},...d?{platformAccess:d}:{},...f?{browser:f}:{}}}),r=>r.code)}function ri(e,t,n,o,s,r,a,i){if(e===void 0)return null;let c=I(e,t);O(c,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),v(c.exposure,"authenticated",`${t}/exposure`);let u=h(c.behavior,`${t}/behavior`,32);["read","controlled"].includes(u)||l("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let E=h(c.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(E)||u==="controlled"&&E!=="required"||u==="read"&&E!=="none")&&l("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let d=I(c.subject,`${t}/subject`);O(d,["resourceCode","inputField"],`${t}/subject`);let f=z(d.resourceCode,`${t}/subject/resourceCode`);r.has(f)||l("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let p=W(d.inputField,`${t}/subject/inputField`),_=I(o,`${t}/requestSchema`),A=I(s,`${t}/responseSchema`);(_.type!=="object"||_.additionalProperties!==!1||A.type!=="object"||A.additionalProperties!==!1)&&l("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let N=I(_.properties,`${t}/requestSchema/properties`),m=new Set(_.required===void 0?[]:F(_.required,`${t}/requestSchema/required`,200));(!(p in N)||!m.has(p))&&l("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let T=I(N[p],`${t}/requestSchema/properties/${p}`);(T.type!=="string"||T.format!=="uuid")&&l("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let C=new Map((Array.isArray(i)?i:[]).map((V,x)=>{let k=I(V,`/config/data/subjectReadSurfaces/${x}`);return[String(k.code),String(I(k.subject,`/config/data/subjectReadSurfaces/${x}/subject`).resourceCode)]})),$=c.refreshTargets===void 0?[]:R(c.refreshTargets,`${t}/refreshTargets`,16),b=new Set,g=X($.map((V,x)=>{let k=`${t}/refreshTargets/${x}`,Y=I(V,k);O(Y,["kind","code"],k),v(Y.kind,"subject-surface",`${k}/kind`);let M=w(Y.code,`${k}/code`);return(b.has(M)||!C.has(M)||C.get(M)!==f)&&l("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${k}/code`),b.add(M),{kind:"subject-surface",code:M}}),V=>`${V.kind}:${V.code}`),D=ai(c.fileIntent,`${t}/fileIntent`,n,u,E,f,N,m,a);return{exposure:"authenticated",behavior:u,idempotency:E,subject:{resourceCode:f,inputField:p},...g.length?{refreshTargets:g}:{},...D?{fileIntent:D}:{}}}function ai(e,t,n,o,s,r,a,i,c){if(e===void 0)return null;let u=I(e,t);O(u,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(n!=="GET"||o!=="read"||s!=="none")&&l("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let E=z(u.recordResourceCode,`${t}/recordResourceCode`),d=c.get(E);d||l("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let f=W(u.recordIdInputField,`${t}/recordIdInputField`),p=I(a[f],`${t}/recordIdInputField`);(!i.has(f)||p.type!=="string"||p.format!=="uuid")&&l("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let _=W(u.relationField,`${t}/relationField`),A=d.get(_);(!A||!["uuid","resource-ref.single"].includes(String(A.type))||String(A.type)==="resource-ref.single"&&(String(I(A.source,`${t}/relationField`).kind||"")!=="resource"||String(I(A.source,`${t}/relationField`).resourceCode||"")!==r))&&l("NATIVE_OPERATION_FILE_INTENT_RELATION_INVALID",`${t}/relationField`);let N=[["fileNameField",["text.short","text.long"]],["contentTypeField",["text.short","text.long"]],["sizeField",["number.integer"]]],m={};for(let[b,g]of N){let D=W(u[b],`${t}/${b}`);g.includes(String(d.get(D)?.type))||l("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${b}`),m[b]=D}let T=X(F(u.purposes,`${t}/purposes`,2),b=>b);(!T.length||T.some(b=>!["preview","download"].includes(b)))&&l("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let C=Number(u.maxTtlSeconds);(!Number.isSafeInteger(C)||C<1||C>300)&&l("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let $=Number(u.maxBytes);return(!Number.isSafeInteger($)||$<1||$>104857600)&&l("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:E,recordIdInputField:f,relationField:_,fileNameField:m.fileNameField,contentTypeField:m.contentTypeField,sizeField:m.sizeField,purposes:T,maxTtlSeconds:C,maxBytes:$}}function ci(e,t,n,o,s){if(e===void 0)return null;let r=I(e,t);O(r,["directory","managedFiles","managedFileCopies","notification","workflow","roleAssertions"],t,!0),Object.keys(r).length===0&&l("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let a={};if(r.roleAssertions!==void 0){let i=I(r.roleAssertions,`${t}/roleAssertions`);O(i,["roleCodes"],`${t}/roleAssertions`);let c=F(i.roleCodes,`${t}/roleAssertions/roleCodes`,20);c.length||l("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),c.forEach((u,E)=>{s.has(u)||l("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${E}`)}),a.roleAssertions={roleCodes:j(c)}}if(r.directory!==void 0){let i=I(r.directory,`${t}/directory`);O(i,["mode","fields"],`${t}/directory`),i.mode!=="current-initiator"&&l("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let c=new Set(["displayName","employeeNumber","primaryDepartment","departments"]),u=F(i.fields,`${t}/directory/fields`,4);(!u.length||u.some(E=>!c.has(E)))&&l("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),a.directory={mode:"current-initiator",fields:j(u)}}if(r.managedFiles!==void 0){let i=R(r.managedFiles,`${t}/managedFiles`,16);i.length||l("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let c=new Set;a.managedFiles=X(i.map((u,E)=>{let d=`${t}/managedFiles/${E}`,f=I(u,d);O(f,["resourceCode","fieldCodes","intents"],d);let p=z(f.resourceCode,`${d}/resourceCode`);(c.has(p)||!n.has(p))&&l("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${d}/resourceCode`),c.add(p);let _=F(f.fieldCodes,`${d}/fieldCodes`,16);(!_.length||_.some(N=>!["file","image","signature"].includes(String(n.get(p)?.get(N)||""))))&&l("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${d}/fieldCodes`);let A=F(f.intents,`${d}/intents`,2);return(!A.length||A.some(N=>!["create","update"].includes(N)))&&l("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${d}/intents`),{resourceCode:p,fieldCodes:j(_),intents:j(A)}}),u=>u.resourceCode)}if(r.managedFileCopies!==void 0){let i=R(r.managedFileCopies,`${t}/managedFileCopies`,16);i.length||l("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let c=new Set;a.managedFileCopies=X(i.map((u,E)=>{let d=`${t}/managedFileCopies/${E}`,f=I(u,d);O(f,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],d),v(f.mode,"copy",`${d}/mode`);let p=z(f.sourceResourceCode,`${d}/sourceResourceCode`),_=z(f.targetResourceCode,`${d}/targetResourceCode`),A=n.get(p),N=n.get(_);(!A||!N)&&l("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",d);let m=F(f.sourceFieldCodes,`${d}/sourceFieldCodes`,16),T=F(f.targetFieldCodes,`${d}/targetFieldCodes`,16);(!m.length||m.length!==T.length)&&l("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",d),m.forEach(($,b)=>{let g=A.get($),D=N.get(T[b]);(!["file","image"].includes(String(g))||g!==D)&&l("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${d}/sourceFieldCodes/${b}`)});let C=`${p}:${m.join(",")}=>${_}:${T.join(",")}`;return c.has(C)&&l("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",d),c.add(C),{mode:"copy",sourceResourceCode:p,sourceFieldCodes:j(m),targetResourceCode:_,targetFieldCodes:j(T)}}),u=>`${u.sourceResourceCode}:${u.sourceFieldCodes.join(",")}=>${u.targetResourceCode}:${u.targetFieldCodes.join(",")}`)}if(r.notification!==void 0){let i=I(r.notification,`${t}/notification`);O(i,["mode"],`${t}/notification`),i.mode!=="business-standard"&&l("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`);O(i,["codes"],`${t}/workflow`);let c=F(i.codes,`${t}/workflow/codes`,16);(!c.length||c.some(u=>!o.has(u)))&&l("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`),a.workflow={codes:j(c)}}return a}function di(e,t,n,o,s){if(e===void 0)return;let r=`${t}/ai`,a=I(e,r);ys.test(n)||l("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),O(a,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],r,!0),h(a.name,`${r}/name`,jt),h(a.description,`${r}/description`,jt);let i=h(a.risk,`${r}/risk`,16);["read","write","destructive","external"].includes(i)||l("NATIVE_OPERATION_AI_RISK_INVALID",`${r}/risk`),i==="read"!=(o==="GET")&&l("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`),o==="DELETE"&&!["destructive","external"].includes(i)&&l("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`);let c=F(a.resources,`${r}/resources`,16);c.length===0&&l("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${r}/resources`),c.forEach((E,d)=>{let f=z(E,`${r}/resources/${d}`);s.has(f)||l("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${r}/resources/${d}`)});let u=F(a.sideEffects,`${r}/sideEffects`,20);(i==="read"&&u.length!==0||i!=="read"&&u.length===0)&&l("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${r}/sideEffects`),a.concurrency!==void 0&&!["none","revision"].includes(h(a.concurrency,`${r}/concurrency`,16))&&l("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${r}/concurrency`),a.timeoutMs!==void 0&&Z(a.timeoutMs,`${r}/timeoutMs`,100,3e4)}function dt(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(n=>n.startsWith(":")?":":n.includes("*")?"*":n).join("/")}function li(e,t){let n=I(e,t),o=h(n.type,`${t}/type`,32),s=["code","type","label","presentation","required"],r=o==="sso"?[...s,"provider"]:o==="dingtalk"?[...s,"flow"]:s;O(n,r,t);let a=w(n.code,`${t}/code`),i=h(n.label,`${t}/label`,255),c=h(n.presentation,`${t}/presentation`,16);["primary","secondary"].includes(c)||l("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let u=Pe(n.required,`${t}/required`);return["sso","password","dingtalk"].includes(o)||l("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),o==="sso"&&n.provider!=="tenant-default"&&l("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),o==="dingtalk"&&!["auto","jsapi","oauth"].includes(h(n.flow,`${t}/flow`,16))&&l("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:a,type:o,label:i,presentation:c,required:u,...o==="sso"?{provider:"tenant-default"}:{},...o==="dingtalk"?{flow:n.flow}:{}}}function Sn(e,t,n){let o=I(e,n);O(o,["routeCode","path","defaultRouteCode"],n);let s=w(o.routeCode,`${n}/routeCode`),r=ce(o.path,`${n}/path`),a=t==="desktop"?"/login":"/m/login";return(r!==a||/[:*?#\\]/.test(r))&&l("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${n}/path`,{device:t,expectedPath:a}),{routeCode:s,path:r,defaultRouteCode:w(o.defaultRouteCode,`${n}/defaultRouteCode`)}}function qn(e,t,n,o){if(e===null)return;let s=I(e,o);O(s,["accountMode","registration","methods","surfaces"],o),v(s.accountMode,"existing-platform-users-only",`${o}/accountMode`);let r=I(s.registration,`${o}/registration`);O(r,["mode"],`${o}/registration`),v(r.mode,"reject",`${o}/registration/mode`);let a=R(s.methods,`${o}/methods`,8);a.length===0&&l("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${o}/methods`);let i=a.map((m,T)=>li(m,`${o}/methods/${T}`)),c=new Set,u=new Set;for(let[m,T]of i.entries())c.has(T.code)&&l("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${o}/methods/${m}/code`),u.has(T.type)&&l("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${o}/methods/${m}/type`),c.add(T.code),u.add(T.type);i.filter(m=>m.presentation==="primary").length!==1&&l("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${o}/methods`);let E=I(s.surfaces,`${o}/surfaces`);O(E,["desktop","mobile"],`${o}/surfaces`);let d=Sn(E.desktop,"desktop",`${o}/surfaces/desktop`),f=Sn(E.mobile,"mobile",`${o}/surfaces/mobile`);d.routeCode===f.routeCode&&l("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${o}/surfaces/mobile/routeCode`);let p=R(t,"/config/frontend/routes",500),_=new Map;for(let[m,T]of p.entries()){let C=I(T,`/config/frontend/routes/${m}`);_.set(String(C.code||""),C)}let A=new Set((Array.isArray(n.data?.resources)?n.data.resources:[]).map(m=>String(m.code||"")).filter(m=>/^[a-z][a-z0-9-]{0,62}$/.test(m)));for(let[m,T]of[["desktop",d],["mobile",f]]){_.has(T.routeCode)&&l("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${o}/surfaces/${m}/routeCode`);let C=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(T.defaultRouteCode||"")),$=_.get(T.defaultRouteCode),b=String($?.path||"");if(C&&A.has(C[1])){let D=C[2]==="records"?`/my/${C[1]}`:`/my/${C[1]}/submit`;$={surface:"user",path:m==="mobile"?`/m${D}`:D},b=String($.path)}let g=m==="desktop"?b==="/m"||b.startsWith("/m/"):!(b==="/m"||b.startsWith("/m/"));(!$||$.surface!=="user"||/[:*]/.test(b)||g)&&l("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${o}/surfaces/${m}/defaultRouteCode`)}let N=Kn(n).filter(m=>!m.owner.startsWith("authentication:"));for(let[m,T]of[["desktop",d],["mobile",f]]){let C=N.find($=>dt($.path)===dt(T.path));C&&l("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${o}/surfaces/${m}/path`,{owner:C.owner})}}function ui(e,t){if(e===null)return;let n={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}},o=I(e,t),s=I(o.surfaces,`${t}/surfaces`),r={...o,surfaces:{...s,desktop:{...I(s.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...I(s.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};qn(r,n.frontend.routes,{...n,frontend:{...n.frontend,authentication:r}},t)}function fi(e){let t=e.frontend.authentication;return t===null?null:{accountMode:t.accountMode,registration:{mode:t.registration.mode},methods:t.methods.map(n=>({...n})),surfaces:{desktop:{...t.surfaces.desktop},mobile:{...t.surfaces.mobile}}}}var _i=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function Ei(e,t,n){let o=I(e,n);O(o,["policies"],n);let s=R(o.policies,`${n}/policies`,16);s.length<1&&l("NATIVE_PUBLIC_POLICY_REQUIRED",n);let r=new Map(t.frontend.routes.map(u=>[u.code,u])),a=new Map(t.data.resources.map(u=>[u.code,u])),i=new Set,c=new Set(s.map(u=>String(u?.code||"")));s.forEach((u,E)=>{let d=`${n}/policies/${E}`,f=I(u,d);O(f,["code","routeCode","mode","resourceCode","operations","fields"],d,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let p=w(f.code,`${d}/code`);i.has(p)&&l("NATIVE_PUBLIC_POLICY_DUPLICATE",`${d}/code`);let _=w(f.routeCode,`${d}/routeCode`),A=r.get(_);(!A||A.surface!=="user"||A.capability!==void 0||A.access!==void 0||/[:*]/.test(String(A.path)))&&l("NATIVE_PUBLIC_ROUTE_INVALID",`${d}/routeCode`),v(f.mode,"anonymous",`${d}/mode`);let N=z(f.resourceCode,`${d}/resourceCode`),m=a.get(N);m||l("NATIVE_PUBLIC_RESOURCE_MISSING",`${d}/resourceCode`);let T=new Map(m.schema.fields.map(y=>[String(y.code),String(y.type)])),C=F(f.operations,`${d}/operations`,8);(C.length<1||C.some(y=>!_i.has(y)))&&l("NATIVE_PUBLIC_OPERATION_INVALID",`${d}/operations`),C.includes("draft.read")!==C.includes("draft.update")&&l("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${d}/operations`);let $=F(f.fields,`${d}/fields`,64);($.length<1||$.some(y=>!T.has(y)))&&l("NATIVE_PUBLIC_FIELD_INVALID",`${d}/fields`);for(let y of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(f,y))continue;F(f[y],`${d}/${y}`,64).some(P=>!$.includes(P))&&l("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${d}/${y}`)}let b=Object.prototype.hasOwnProperty.call(f,"serverGeneratedFields")?R(f.serverGeneratedFields,`${d}/serverGeneratedFields`,16):[],g=new Set;b.forEach((y,U)=>{let P=`${d}/serverGeneratedFields/${U}`,B=I(y,P);O(B,["field","kind"],P);let J=W(B.field,`${P}/field`);(g.has(J)||!T.has(J)||$.includes(J)||T.get(J)!=="text.short"&&T.get(J)!=="text.long")&&l("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${P}/field`),v(B.kind,"random-token",`${P}/kind`),g.add(J)});let D=Object.prototype.hasOwnProperty.call(f,"schedule")?I(f.schedule,`${d}/schedule`):null;if(D){let y=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];O(D,y,`${d}/schedule`);for(let U of["campusPolicyCode","rulePolicyCode"])w(D[U],`${d}/schedule/${U}`);for(let U of y.filter(P=>!["campusPolicyCode","rulePolicyCode"].includes(P)))W(D[U],`${d}/schedule/${U}`);for(let U of[D.campusField,D.dateField,D.timeField])$.includes(String(U))||l("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${d}/schedule`);(!c.has(String(D.campusPolicyCode))||!c.has(String(D.rulePolicyCode)))&&l("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${d}/schedule`)}let V=Object.prototype.hasOwnProperty.call(f,"publicFilters")?R(f.publicFilters,`${d}/publicFilters`,16):[],x=new Set;V.forEach((y,U)=>{let P=`${d}/publicFilters/${U}`,B=I(y,P);O(B,["field","operator","value"],P);let J=W(B.field,`${P}/field`);x.has(J)&&l("NATIVE_PUBLIC_FILTER_DUPLICATE",`${P}/field`),$.includes(J)||l("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${P}/field`),v(B.operator,"eq",`${P}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(T.get(J)||"")||l("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${P}/field`),B.value!==null&&typeof B.value!="string"&&typeof B.value!="number"&&typeof B.value!="boolean"&&l("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${P}/value`),x.add(J)});let k=Object.prototype.hasOwnProperty.call(f,"publicSubtableFields")?I(f.publicSubtableFields,`${d}/publicSubtableFields`):null;if(k){Object.keys(k).length>64&&l("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields`);for(let[y,U]of Object.entries(k)){let P=m.schema.fields.find(H=>String(H.code)===y),B=String(P?.subtable?.resourceCode||""),J=a.get(B),pe=new Map((J?.schema?.fields||[]).map(H=>[String(H.code),String(H.type)])),G=F(U,`${d}/publicSubtableFields/${y}`,64);(!$.includes(y)||T.get(y)!=="subtable"||!J||G.length<1||G.some(H=>!pe.has(H))||G.some(H=>pe.get(H)==="subtable")||G.some(H=>pe.get(H)==="signature"))&&l("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields/${y}`)}}if(C.some(y=>y.startsWith("public."))){Object.prototype.hasOwnProperty.call(f,"publicRecordFields")||l("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${d}/publicRecordFields`);let y=F(f.publicRecordFields,`${d}/publicRecordFields`,64);(y.length<1||y.some(U=>!$.includes(U))||y.some(U=>T.get(U)==="signature"||T.get(U)==="subtable"&&!k?.[U]))&&l("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${d}/publicRecordFields`)}let Y=Object.prototype.hasOwnProperty.call(f,"requiredFields")?F(f.requiredFields,`${d}/requiredFields`,64):[],M=m.surface||{},de=M.fields||{},le=String(M.mutationOwner||"native")==="native"&&M.generated?.create!==!1,K=m.schema.fields.filter(y=>ve(y,de[y.code])).map(y=>String(y.code));if(C.includes("create")&&!le&&l("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/fields`),C.includes("create")&&!Object.prototype.hasOwnProperty.call(f,"draft")&&l("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`),C.includes("create"))for(let y of K){let U=$.includes(y)?Y.includes(y)?null:"requiredFields":"fields";U&&l("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/${U}`,{resourceCode:z,fieldCode:y})}if(Object.prototype.hasOwnProperty.call(f,"draft")){let y=I(f.draft,`${d}/draft`);O(y,["enabled","inactivityTtlSeconds","maxBytes"],`${d}/draft`),v(y.enabled,!0,`${d}/draft/enabled`),Z(y.inactivityTtlSeconds,`${d}/draft/inactivityTtlSeconds`,3600,7776e3),Z(y.maxBytes,`${d}/draft/maxBytes`,4096,262144)}else C.includes("draft.read")&&l("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`);let Ee=Object.prototype.hasOwnProperty.call(f,"validations")?R(f.validations,`${d}/validations`,16):[],se=new Set;Ee.forEach((y,U)=>{let P=`${d}/validations/${U}`,B=I(y,P);O(B,["code","kind","fields","result"],P);let J=w(B.code,`${P}/code`);se.has(J)&&l("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${P}/code`),v(B.kind,"duplicate",`${P}/kind`),v(B.result,"availability",`${P}/result`);let pe=F(B.fields,`${P}/fields`,8);(pe.length<1||pe.some(G=>!$.includes(G))||pe.some(G=>["file","subtable"].includes(T.get(G)||"")))&&l("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${P}/fields`),se.add(J)}),i.add(p)})}function pi(e,t){let n=I(e,t);O(n,["policies"],t),R(n.policies,`${t}/policies`,16).length<1&&l("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function Ai(e){return{policies:X(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:j(t.operations),fields:j(t.fields),...t.requiredFields?{requiredFields:j(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:j(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:j(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(n=>({field:n.field,operator:n.operator,value:n.value})).sort((n,o)=>re(n.field,o.field))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>[n,j(Array.isArray(o)?o.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(n=>({field:n.field,kind:n.kind})).sort((n,o)=>re(n.field,o.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:X(t.validations.map(n=>({code:n.code,kind:n.kind,fields:j(n.fields),result:n.result})),n=>n.code)}:{}})),t=>t.code)}}function Kn(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 n of e.data.resources){let o=Hn(n),s=`/admin/resources/${n.code}`,r=[["list",s],["detail",`${s}/:id`],["create",`${s}/new`],["update",`${s}/:id/edit`]];for(let[a,i]of r)o[a]&&t.push({owner:`resource:${n.code}:${a}`,path:i},{owner:`resource:${n.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 n=!1;for(let o of e.workflows.definitions)["standalone","hidden-handoff"].includes(o.launch.mode)&&(n=!0);n&&t.push({owner:"workflow:launch",path:"/workflows/:workflowCode/start"},{owner:"workflow:launch:mobile",path:"/m/workflows/:workflowCode/start"})}return t}function ft(e){let t=new Map(Kn(e).map(n=>[dt(n.path),n]));return X(e.frontend.routes.map((n,o)=>{let s=`/config/frontend/routes/${o}`,r=I(n,s);O(r,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],s,!0),["admin","user"].includes(r.surface)||l("NATIVE_ROUTE_SURFACE_INVALID",`${s}/surface`);let a=ce(r.path,`${s}/path`);r.surface==="admin"&&a!=="/admin"&&!a.startsWith("/admin/")&&l("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${s}/path`),r.surface==="user"&&(a==="/admin"||a.startsWith("/admin/"))&&l("NATIVE_USER_ROUTE_PATH_RESERVED",`${s}/path`);let i=dt(a),c=t.get(i);c&&l("NATIVE_ROUTE_PATH_CONFLICT",`${s}/path`,{path:a,owner:c.owner}),t.set(i,{owner:`frontend:${String(r.code||o)}`,path:a});let u=/[:*]/.test(a),E=zt(r,s,e.appCode),d=r.pinned===void 0?void 0:Pe(r.pinned,`${s}/pinned`),f=r.tabPersistence===void 0?u?"none":"session":h(r.tabPersistence,`${s}/tabPersistence`,16),p=r.keepAlive===void 0?"none":h(r.keepAlive,`${s}/keepAlive`,16);return["session","none"].includes(f)||l("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${s}/tabPersistence`),["none","memory"].includes(p)||l("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${s}/keepAlive`),u&&d===!0&&l("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${s}/pinned`),u&&f==="session"&&l("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${s}/tabPersistence`),u&&p==="memory"&&l("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${s}/keepAlive`),{code:w(r.code,`${s}/code`),path:a,label:h(r.label,`${s}/label`,255),surface:r.surface,...r.parentCode===void 0?{}:{parentCode:w(r.parentCode,`${s}/parentCode`)},...E,...d===void 0?{}:{pinned:d},tabPersistence:f,keepAlive:p}}),n=>n.code)}function Hn(e){let t=e.surface===void 0?{}:I(e.surface,"/surface"),n=t.mutationOwner||"native",o=t.generated===void 0?{}:I(t.generated,"/surface/generated"),s=n==="native";return{list:o.list??!0,detail:o.detail??!0,create:o.create??s,update:o.update??s,delete:o.delete??s}}function Xn(e){let t=[];for(let n of X(e.data.resources,o=>o.code).flatMap(o=>[{resource:o,viewCode:void 0},...(o.surface?.views||[]).map(s=>({viewCode:s.code,resource:{...o,name:s.name,surface:et(o.surface,s.code)}}))])){let{resource:o,viewCode:s}=n,r=`/admin/resources/${o.code}${s?`/views/${s}`:""}`,a=Hn(o),i=[{operation:"list",kind:"resource-list",path:`${r}`,label:o.name,capability:o.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${r}/:id`,label:`${o.name}\u8BE6\u60C5`,capability:o.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${r}/new`,label:`\u65B0\u589E${o.name}`,capability:o.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${r}/:id/edit`,label:`\u7F16\u8F91${o.name}`,capability:o.capabilities.update,navigationEligible:!1}];for(let c of i)a[c.operation]&&t.push({code:`resource:${o.code}${s?`:view:${s}`:""}:${c.operation}`,kind:c.kind,path:c.path,label:c.label,navigationEligible:c.navigationEligible,capability:c.capability,resourceCode:o.code,...s?{viewCode:s}:{}})}for(let n of ft(e))n.surface==="admin"&&t.push({code:`operation:${n.code}`,kind:"operation",path:n.path,label:n.label,navigationEligible:!/[:*]/.test(n.path),routeCode:n.code});return t.sort((n,o)=>re(n.code,o.code))}function Qn(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function Ii(e){return e.frontend.admin.navigation.map((t,n)=>({code:t.code,label:t.label,...t.icon===void 0?{}:{icon:t.icon},order:t.order??n,items:t.items.map((o,s)=>({pageCode:Qn(o.page),...o.label===void 0?{}:{label:o.label},...o.icon===void 0?{}:{icon:o.icon},order:o.order??s})).sort((o,s)=>o.order-s.order||re(o.pageCode,s.pageCode))})).sort((t,n)=>t.order-n.order||re(t.code,n.code))}function mi(e,t){let n=R(e,t,q.adminNavigationGroups),o=0;n.forEach((s,r)=>{let a=`${t}/${r}`,i=I(s,a);O(i,["code","label","icon","order","items"],a,!0),w(i.code,`${a}/code`),h(i.label,`${a}/label`,255),lt(i.icon,`${a}/icon`),Fn(i.order,`${a}/order`);let c=R(i.items,`${a}/items`,500);c.length===0&&l("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),o+=c.length,o>q.adminNavigationItems&&l("NATIVE_ARRAY_LIMIT_EXCEEDED",t),c.forEach((u,E)=>{let d=`${a}/items/${E}`,f=I(u,d);O(f,["page","label","icon","order"],d,!0),Ni(f.page,`${d}/page`),f.label!==void 0&&h(f.label,`${d}/label`,255),lt(f.icon,`${d}/icon`),Fn(f.order,`${d}/order`)})})}function Ni(e,t){let n=I(e,t),o=h(n.kind,`${t}/kind`,64);if(o==="resource"){O(n,["kind","resourceCode"],t,["viewCode"]),n.viewCode!==void 0&&w(n.viewCode,`${t}/viewCode`),z(n.resourceCode,`${t}/resourceCode`);return}if(o==="operation"){O(n,["kind","routeCode"],t),w(n.routeCode,`${t}/routeCode`);return}l("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function Ti(e){let t=new Map(Xn(e).map(s=>[String(s.code),s])),n=new Set,o=new Set;e.frontend.admin.navigation.forEach((s,r)=>{let a=`/config/frontend/admin/navigation/${r}`;n.has(s.code)&&l("NATIVE_ADMIN_GROUP_DUPLICATE",`${a}/code`),n.add(s.code),s.label===s.code&&l("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${a}/label`),s.items.forEach((i,c)=>{let u=`${a}/items/${c}`,E=Qn(i.page),d=t.get(E);(!d||d.navigationEligible!==!0)&&l("NATIVE_ADMIN_PAGE_NOT_FOUND",`${u}/page`),o.has(E)&&l("NATIVE_ADMIN_PAGE_DUPLICATE",`${u}/page`),o.add(E);let f=i.page.resourceCode||i.page.routeCode||i.page.workflowCode||E,p=i.label||d.label;(!p||p===f||p===E)&&l("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${u}/label`)})})}function gi(e,t){let n=R(e,t,q.adminPages),o=new Set;n.forEach((s,r)=>{let a=`${t}/${r}`,i=I(s,a);O(i,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],a,!0);let c=h(i.code,`${a}/code`,255);o.has(c)&&l("NATIVE_ADMIN_PAGE_DUPLICATE",`${a}/code`),o.add(c);let u=h(i.kind,`${a}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(u)||l("NATIVE_ADMIN_PAGE_KIND_INVALID",`${a}/kind`),ce(i.path,`${a}/path`),h(i.label,`${a}/label`,255),Pe(i.navigationEligible,`${a}/navigationEligible`),i.capability!==void 0&&i.access!==void 0&&l("NATIVE_ROUTE_ACCESS_CONFLICT",`${a}/access`),i.capability!==void 0&&h(i.capability,`${a}/capability`,255),i.access!==void 0){let E=I(i.access,`${a}/access`);O(E,["allOf","anyOf"],`${a}/access`,!0);for(let d of["allOf","anyOf"])E[d]!==void 0&&F(E[d],`${a}/access/${d}`,50)}for(let E of["resourceCode","viewCode","routeCode"])i[E]!==void 0&&w(i[E],`${a}/${E}`)})}function bi(e,t){let n=R(e,t,q.adminNavigationGroups),o=0;n.forEach((s,r)=>{let a=`${t}/${r}`,i=I(s,a);O(i,["code","label","icon","order","items"],a,!0),w(i.code,`${a}/code`),h(i.label,`${a}/label`,255),lt(i.icon,`${a}/icon`),Z(i.order,`${a}/order`,-1e4,1e4);let c=R(i.items,`${a}/items`,500);c.length===0&&l("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),o+=c.length,o>q.adminNavigationItems&&l("NATIVE_ARRAY_LIMIT_EXCEEDED",t),c.forEach((u,E)=>{let d=`${a}/items/${E}`,f=I(u,d);O(f,["pageCode","label","icon","order"],d,!0),h(f.pageCode,`${d}/pageCode`,255),f.label!==void 0&&h(f.label,`${d}/label`,255),lt(f.icon,`${d}/icon`),Z(f.order,`${d}/order`,-1e4,1e4)})})}var Ci=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function Oi(e,t,n){let o=I(e,t);O(o,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),v(o.schemaVersion,Jn,`${t}/schemaVersion`),v(o.appCode,n,`${t}/appCode`),Gt(o.devicePolicy,`${t}/devicePolicy`),$i(o.rootEntry,`${t}/rootEntry`),Ri(o.authentication,`${t}/authentication`),Jt(o.digest,`${t}/digest`);let s=R(o.routes,`${t}/routes`,q.routes),r=new Set;s.forEach((a,i)=>{let c=`${t}/routes/${i}`,u=I(a,c),E=u.kind==="resource-records"||u.kind==="resource-submit";O(u,["code","kind","desktop","mobile"],c,["workflowCode",...E?["resourceCode"]:[]]);let d=h(u.code,`${c}/code`,255);r.has(d)&&l("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${c}/code`),r.add(d);let f=h(u.kind,`${c}/kind`,64);if(Ci.has(f)||l("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${c}/kind`),u.workflowCode!==void 0&&w(u.workflowCode,`${c}/workflowCode`),E){let A=z(u.resourceCode,`${c}/resourceCode`);v(d,`user.${A}.${u.kind==="resource-records"?"records":"submit"}`,`${c}/code`)}else u.resourceCode!==void 0&&l("NATIVE_PROPERTY_UNKNOWN",`${c}/resourceCode`);let p=yn(u.desktop,`${c}/desktop`,n),_=yn(u.mobile,`${c}/mobile`,n);p.surface!=="user"&&l("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${c}/desktop/surface`),_.surface!=="user"&&l("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${c}/mobile/surface`),p.routeCode===_.routeCode&&l("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",c)}),v(o.digest,ee({schemaVersion:o.schemaVersion,appCode:o.appCode,devicePolicy:o.devicePolicy,rootEntry:o.rootEntry,authentication:o.authentication,routes:o.routes}),`${t}/digest`)}function Gt(e,t){let n=I(e,t);O(n,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),v(n.kind,"viewport-family",`${t}/kind`);let o=Z(n.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),s=Z(n.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return s!==o+1&&l("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:o,desktopMinWidthPx:s}}function $i(e,t){let n=I(e,t);O(n,["code","desktop","mobile"],t);let o=w(n.code,`${t}/code`),s=Bt(n.desktop,`${t}/desktop`),r=Bt(n.mobile,`${t}/mobile`);return(s===r||r==="/"||!r.startsWith("/m/"))&&l("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),s.startsWith("/m/")&&l("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:o,desktop:s,mobile:r}}function Ri(e,t){let n=I(e,t);O(n,["desktop","mobile"],t);let o=Dn(n.desktop,`${t}/desktop`,!1),s=Dn(n.mobile,`${t}/mobile`,!0);return(o.routeCode===s.routeCode||o.path===s.path)&&l("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:o,mobile:s}}function Dn(e,t,n){let o=I(e,t);O(o,["routeCode","path"],t);let s=w(o.routeCode,`${t}/routeCode`),r=Bt(o.path,`${t}/path`);return(n?!r.startsWith("/m/"):r.startsWith("/m/"))&&l("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:s,path:r}}function Bt(e,t){let n=ce(e,t);return/[:*?#\\\\]/.test(n)&&l("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),n}function yn(e,t,n){let o=I(e,t);O(o,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),w(o.routeCode,`${t}/routeCode`);let s=ce(o.path,`${t}/path`),r=h(o.surface,`${t}/surface`,16);["admin","user"].includes(r)||l("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let a=F(o.pathParams,`${t}/pathParams`,8);return a.forEach((i,c)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(i)||i.length>64)&&l("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${c}`)}),Q(a)!==Q(Zn(s))&&l("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),zt(o,t,n),o.requiresAuthentication!==!0&&l("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),o}function Zn(e){return j([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function Vn(e,t,n,o){return{routeCode:e,path:t,surface:n,pathParams:Zn(t),...o?.capability?{capability:o.capability}:{},...o?.access?{access:o.access}:{},requiresAuthentication:!0}}function wn(e,t,n,o){return e==="workflow-launch"?`workflow.${n}.launch.${t}`:e==="application-todo-center"?`application.todo-center.${t}`:e==="resource-records"?`user.${o}.records.${t}`:e==="resource-submit"?`user.${o}.submit.${t}`:`${e.replace(/-/g,".")}.${t}`}function hi(e){let t=e.appCode,n=[],o=(p,_,A,N,m,T,C)=>{n.push({code:p,kind:_,...m?{workflowCode:m}:{},...C?{resourceCode:C}:{},desktop:Vn(wn(_,"desktop",m,C),A,"user",T),mobile:Vn(wn(_,"mobile",m,C),N,"user",T)})};e.frontend.user.applicationTodoCenter===!0&&o("application:todo-center","application-todo-center","/todos","/m/todos");let s=eo(e);s.length>0&&(o("workflow:work-center","workflow-work-center","/work-center","/m/work-center"),o("workflow:task","workflow-task","/tasks/:taskId","/m/tasks/:taskId"),o("workflow:instance","workflow-instance","/workflows/:instanceId","/m/workflows/:instanceId"));for(let p of s){if(!["standalone","hidden-handoff"].includes(p.launch.mode))continue;let _=j([p.launch.submission?.create?.requiredCapability,p.launch.submission?.existing?.requiredCapability].filter(A=>!!A));o(`workflow:${p.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",p.code,_.length===1?{capability:_[0]}:_.length>1?{access:{anyOf:_}}:void 0)}let r=n.sort((p,_)=>re(String(p.code),String(_.code))),a=ft(e),i=p=>{let _=p==="mobile"?"/m/":"/",A=a.filter(m=>m.surface==="user"&&!/[:*?#\\\\]/.test(m.path)&&m.path===_).sort((m,T)=>re(m.code,T.code))[0];if(A)return{code:A.code,path:A.path};let N=a.filter(m=>m.surface==="user"&&!/[:*?#\\\\]/.test(m.path)&&(p==="mobile"?m.path.startsWith("/m/"):!m.path.startsWith("/m/"))).sort((m,T)=>re(m.code,T.code))[0];return N?{code:N.code,path:N.path}:{code:p==="mobile"?"application-root-mobile":"application-root",path:_}},c=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"}},u=Gt(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),E=i("desktop"),d=i("mobile"),f={schemaVersion:Jn,appCode:t,devicePolicy:u,rootEntry:{code:E.code,desktop:E.path,mobile:d.path},authentication:c,routes:r};return{...f,digest:ee(f)}}function lt(e,t){if(e===void 0)return;let n=h(e,t,32);js.has(n)||l("NATIVE_ADMIN_ICON_INVALID",t)}function Fn(e,t){e!==void 0&&Z(e,t,-1e4,1e4)}function zt(e,t,n){return e.capability!==void 0&&e.access!==void 0&&l("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:Ne(e.capability,`${t}/capability`,n)}:e.access===void 0?{}:{access:_t(e.access,`${t}/access`,n)}}function _t(e,t,n){let o=I(e,t);O(o,["allOf","anyOf"],t,!0);let s=o.allOf===void 0?void 0:j(F(o.allOf,`${t}/allOf`,50).map((a,i)=>Ne(a,`${t}/allOf/${i}`,n))),r=o.anyOf===void 0?void 0:j(F(o.anyOf,`${t}/anyOf`,50).map((a,i)=>Ne(a,`${t}/anyOf/${i}`,n)));return(s?.length||0)+(r?.length||0)===0&&l("NATIVE_ROUTE_ACCESS_EMPTY",t),{...s===void 0?{}:{allOf:s},...r===void 0?{}:{anyOf:r}}}function eo(e){let t=new Map(Yn(e).map(s=>[String(s.code),s])),n=e.workflows.definitions.map((s,r)=>{let a=`/config/workflows/definitions/${r}`,i=I(s,a);O(i,["version","definition","launch"],a,["detailRouteCode"]);let c=I(i.definition,`${a}/definition`),u=i.detailRouteCode===void 0?void 0:no(i.detailRouteCode,`${a}/detailRouteCode`);return{code:w(c.code,`${a}/definition/code`),title:h(c.title,`${a}/definition/title`,255),version:Fe(i.version,`${a}/version`),launch:Si(e,c,i.launch,`${a}/launch`,t),...u?{detailRouteCode:u}:{},definition:c}});return j(n.map(s=>s.code)).map(s=>{let r=n.filter(u=>u.code===s),a=e.workflows.activations.find(u=>u.workflowCode===s)?.definitionVersion,i=r.find(u=>u.version===a)||[...r].sort((u,E)=>E.version-u.version)[0],c=new Set;for(let u of r){let E=I(u.definition.nodes,"/config/workflows/definitions/nodes");for(let d of Object.values(E)){let f=I(d,"/config/workflows/definitions/nodes/*");if(f.kind==="approval")for(let p of F(f.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))c.add(p)}}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:jn(r.map(u=>u.version)),bindingVersions:jn(e.workflows.bindings.map((u,E)=>{let d=`/config/workflows/bindings/${E}`,f=I(u,d),p=I(f.binding,`${d}/binding`);return{code:w(p.workflowCode,`${d}/binding/workflowCode`),version:Fe(f.version,`${d}/version`)}}).filter(u=>u.code===s).map(u=>u.version)),providerCodes:j(e.workflows.providers.map((u,E)=>w(I(u,`/config/workflows/providers/${E}`).code,`/config/workflows/providers/${E}/code`))),allowedOperations:[...c].sort(re),editableParameterCodes:j(e.workflows.editableParameters.map((u,E)=>{let d=`/config/workflows/editableParameters/${E}`,f=I(u,d);return{code:w(f.code,`${d}/code`),workflowCode:w(f.workflowCode,`${d}/workflowCode`)}}).filter(u=>u.workflowCode===s).map(u=>u.code))}})}function to(e,t){let n=I(e,t);O(n,["mode"],t,["submission"]);let o=h(n.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(o)||l("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:o,...n.submission===void 0?{}:{submission:I(n.submission,`${t}/submission`)}}}function Si(e,t,n,o,s){let r=to(n,o);if(!r.submission)return{mode:r.mode};["standalone","hidden-handoff"].includes(r.mode)||l("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${o}/submission`);let a=I(r.submission,`${o}/submission`);O(a,["kind"],`${o}/submission`,["create","existing","context"]),v(a.kind,"named-operation",`${o}/submission/kind`);let i=o.endsWith("/launch")?o.slice(0,-7):o,c=I(t.subject,`${i}/definition/subject`),u=z(c.resourceCode,`${i}/definition/subject/resourceCode`),E=e.data.resources.findIndex(g=>g.code===u),d=e.data.resources[E];(E<0||!d)&&l("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${i}/definition/subject/resourceCode`);let f=new Set(I(d.schema,`/config/data/resources/${E}/schema`).fields.map(g=>String(g.code))),p=new Map(e.backend.operations.map(g=>[String(g.code),g])),_=(g,D)=>{let V=`${o}/submission/${D}`,x=I(g,V);O(x,["operationCode","inputs","output"],V);let k=w(x.operationCode,`${V}/operationCode`),Y=p.get(k),M=s.get(k),de=M?.platformAccess?.workflow?.codes;(!Y||!M||M.method!=="POST"||!Array.isArray(de)||!de.includes(t.code))&&l("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",V);let le=I(Y.requestSchema,`${V}/operation/requestSchema`),K=I(le.properties,`${V}/operation/requestSchema/properties`),Ee=new Set(le.required===void 0?[]:F(le.required,`${V}/operation/requestSchema/required`,64)),se=I(x.inputs,`${V}/inputs`),y=Object.entries(se);(!y.length||y.length>64)&&l("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${V}/inputs`);let U=new Set,P=new Map,B={};for(let[G,H]of y){(!Rn.test(G)||!Object.prototype.hasOwnProperty.call(K,G))&&l("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${V}/inputs/${G}`);let Oe=`${V}/inputs/${G}`,pt=I(H,Oe),be=h(pt.source,`${Oe}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(be)||l("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",Oe),O(pt,["source"],Oe,be==="field"?["fieldCode"]:!1),P.set(be,(P.get(be)||0)+1),be==="field"){let Je=W(pt.fieldCode,`${Oe}/fieldCode`);(U.has(Je)||!f.has(Je))&&l("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${Oe}/fieldCode`),U.add(Je),B[G]={source:be,fieldCode:Je}}else B[G]={source:be}}([...Ee].some(G=>!(G in se))||(P.get("idempotency-key")||0)!==1||!y.some(([G,H])=>I(H,`${V}/inputs/${G}`).source==="idempotency-key"&&Ee.has(G))||D==="create"&&((P.get("subject-id")||0)>0||(P.get("subject-revision")||0)>0)||D==="existing"&&((P.get("subject-id")||0)!==1||(P.get("subject-revision")||0)!==1))&&l("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${V}/inputs`);let J=I(x.output,`${V}/output`);O(J,["subjectId"],`${V}/output`,["subjectRevision","processCommand"]);let pe=I(I(Y.responseSchema,`${V}/operation/responseSchema`).properties,`${V}/operation/responseSchema/properties`);for(let G of["subjectId","subjectRevision","processCommand"]){if(J[G]===void 0)continue;let H=h(J[G],`${V}/output/${G}`,128);(!Rn.test(H)||!Object.prototype.hasOwnProperty.call(pe,H))&&l("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${V}/output/${G}`)}return{operationCode:k,method:"POST",path:M.path,requiredCapability:M.requiredCapability,requestSchemaDigest:M.requestSchemaDigest,responseSchemaDigest:M.responseSchemaDigest,inputs:B,output:{...J},fieldCodes:U}},A=a.create===void 0?void 0:_(a.create,"create"),N=a.existing===void 0?void 0:_(a.existing,"existing");!A&&!N&&l("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${o}/submission`);let m=new Set([...A?.fieldCodes||[],...N?.fieldCodes||[]]),T=a.context===void 0?[]:R(a.context,`${o}/submission/context`,16),C=new Set,$=T.map((g,D)=>{let V=`${o}/submission/context/${D}`,x=I(g,V);O(x,["queryParameter","fieldCode"],V);let k=h(x.queryParameter,`${V}/queryParameter`,64),Y=W(x.fieldCode,`${V}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(k)||C.has(k)||!m.has(Y))&&l("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",V),C.add(k),{queryParameter:k,fieldCode:Y}}),b=g=>{let{fieldCodes:D,...V}=g;return V};return{mode:r.mode,submission:{kind:"named-operation",...A?{create:b(A)}:{},...N?{existing:b(N)}:{},context:$}}}function no(e,t){let n=I(e,t);O(n,["desktop","mobile"],t);let o=w(n.desktop,`${t}/desktop`),s=w(n.mobile,`${t}/mobile`);return o===s&&l("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:o,mobile:s}}function Di(e,t){let n=new Set(t.map(E=>E.code)),o=new Map;e.data.resources.forEach((E,d)=>{let f=`/config/data/resources/${d}`,p=I(E,f);for(let[N,m]of Object.entries(p.fieldPolicies||{})){if(!Re(N))continue;let T=`${f}/fieldPolicies/${N}/read`,C=I(m,`${f}/fieldPolicies/${N}`);for(let $ of F(C.read||[],T,2e3))n.has($)||l("NATIVE_CAPABILITY_REFERENCE_MISSING",T)}if(((p.surface===void 0?{}:I(p.surface,`${f}/surface`)).mutationOwner||"native")==="native")return;let A=I(p.capabilities,`${f}/capabilities`);for(let N of["create","update","delete"])o.set(String(A[N]),N)});let s=new Set;for(let[E,d]of e.authz.roles.entries()){let f=`/config/authz/roles/${E}`,p=I(d,f);O(p,["code","name","description","capabilities"],f,!0);let _=w(p.code,`${f}/code`);s.has(_)&&l("NATIVE_ROLE_DUPLICATE",`${f}/code`),s.add(_),h(p.name,`${f}/name`,255);let A=F(p.capabilities,`${f}/capabilities`,2e3);for(let[N,m]of A.entries())o.has(m)&&l("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${f}/capabilities/${N}`,{operation:o.get(m)}),n.has(m)||l("NATIVE_CAPABILITY_REFERENCE_MISSING",`${f}/capabilities`)}let r=e.authz.authenticatedUserRoleCode===void 0?"":w(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");r&&!s.has(r)&&l("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let a=new Set,i=0;for(let[E,d]of e.perspectives.entries()){let f=`/config/perspectives/${E}`,p=I(d,f);O(p,["code","name","description","roleCodes","capabilityCodes","default"],f,!0);let _=w(p.code,`${f}/code`);a.has(_)&&l("NATIVE_PERSPECTIVE_DUPLICATE",`${f}/code`),a.add(_),h(p.name,`${f}/name`,255);let A=F(p.roleCodes,`${f}/roleCodes`,20);A.length<1&&l("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${f}/roleCodes`),A.forEach((T,C)=>{s.has(T)||l("NATIVE_PERSPECTIVE_ROLE_MISSING",`${f}/roleCodes/${C}`)});let N=j(e.authz.roles.filter(T=>A.includes(T.code)).flatMap(T=>T.capabilities)),m=F(p.capabilityCodes,`${f}/capabilityCodes`,2e3);Q(N)!==Q(m)&&l("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${f}/capabilityCodes`),p.default===!0?i+=1:p.default!==void 0&&l("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${f}/default`)}i>1&&l("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[E,d]of e.backend.operations.entries()){let f=I(d,`/config/backend/operations/${E}`);n.has(f.capability)||l("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${E}/capability`)}let c=new Set,u=new Set;for(let[E,d]of e.frontend.routes.entries()){let f=`/config/frontend/routes/${E}`,p=I(d,f),_=w(p.code,`${f}/code`);c.has(_)&&l("NATIVE_ROUTE_DUPLICATE",`${f}/code`),c.add(_);let A=ce(p.path,`${f}/path`);u.has(A)&&l("NATIVE_ROUTE_PATH_DUPLICATE",`${f}/path`),u.add(A);let N=zt(p,f,e.appCode);N.capability&&!n.has(N.capability)&&l("NATIVE_CAPABILITY_REFERENCE_MISSING",`${f}/capability`);let m=p.access===void 0?void 0:I(p.access,`${f}/access`);for(let T of["allOf","anyOf"]){let C=m?.[T]===void 0?[]:R(m[T],`${f}/access/${T}`,50);for(let[$,b]of C.entries()){let g=Ne(b,`${f}/access/${T}/${$}`,e.appCode);n.has(g)||l("NATIVE_CAPABILITY_REFERENCE_MISSING",`${f}/access/${T}/${$}`)}}}if(e.frontend.admin.access!==void 0){let E=_t(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let d of["allOf","anyOf"])for(let[f,p]of(E[d]||[]).entries())n.has(p)||l("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${d}/${f}`)}for(let[E,d]of e.frontend.routes.entries()){let f=I(d,`/config/frontend/routes/${E}`);f.parentCode&&!c.has(f.parentCode)&&l("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${E}/parentCode`)}}function yi(e){let t=new Set(e.authz.roles.map(u=>String(u.code))),n=e.authz.authenticatedUserRoleCode===void 0?"":w(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),o=new Map(e.authz.scopeDimensions.map(u=>[String(u.code),{valueType:u.valueType==="uuid"?"uuid":"string",...u.valueSource?.resourceCode?{valueSourceResourceCode:String(u.valueSource.resourceCode)}:{}}])),s=new Set(o.keys()),r=new Map(e.data.resources.map((u,E)=>{let d=Ce(u,`/config/data/resources/${E}`,e.appCode);return[d.code,new Map(d.schema.fields.map(f=>[String(f.code),f]))]}));for(let[u,E]of e.authz.scopeDimensions.entries()){let d=`/config/authz/scopeDimensions/${u}`,f=I(E,d);if(O(f,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],d,!0),f.valueSource===void 0)continue;let p=I(f.valueSource,`${d}/valueSource`);O(p,["kind","resourceCode","labelField","enabledField"],`${d}/valueSource`,!0),p.kind!=="native_resource"&&l("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${d}/valueSource/kind`),f.valueType!=="uuid"&&l("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${d}/valueType`);let _=z(p.resourceCode,`${d}/valueSource/resourceCode`),A=r.get(_);A||l("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${d}/valueSource/resourceCode`);let N=W(p.labelField,`${d}/valueSource/labelField`);if(["text.short","text.long"].includes(String(A.get(N)?.type||""))||l("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${d}/valueSource/labelField`),p.enabledField!==void 0){let m=W(p.enabledField,`${d}/valueSource/enabledField`);A.get(m)?.type!=="boolean"&&l("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${d}/valueSource/enabledField`)}}let a=new Set,i=new Set;for(let[u,E]of e.authz.scopeSources.entries()){let d=`/config/authz/scopeSources/${u}`,f=I(E,d);O(f,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],d,!0);let p=w(f.code,`${d}/code`);a.has(p)&&l("NATIVE_SCOPE_SOURCE_DUPLICATE",`${d}/code`),a.add(p),h(f.name,`${d}/name`,255);let _=z(f.resourceCode,`${d}/resourceCode`),A=r.get(_);A||l("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${d}/resourceCode`);let N=I(f.subject,`${d}/subject`),m=h(N.type,`${d}/subject/type`,32);O(N,m==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${d}/subject`),["user","role_membership"].includes(m)||l("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${d}/subject/type`);let T=ye(N.userIdField,A);st(T)||l("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${d}/subject/userIdField`),m==="role_membership"&&!t.has(String(N.roleCode))&&l("NATIVE_ROLE_REFERENCE_MISSING",`${d}/subject/roleCode`);let C=new Set;for(let[$,b]of R(f.grants,`${d}/grants`,100).entries()){let g=`${d}/grants/${$}`,D=I(b,g);O(D,["dimensionCode","valueField","parentValueField"],g,!0);let V=w(D.dimensionCode,`${g}/dimensionCode`);(!s.has(V)||C.has(V))&&l("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${g}/dimensionCode`),C.add(V),f.failureMode==="last_known_good"&&i.add(V);for(let x of["valueField","parentValueField"]){if(D[x]===void 0)continue;let k=ye(D[x],A);Pt(k,o.get(V),r)||l("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${g}/${x}`)}}C.size===0&&l("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${d}/grants`),["strict","last_known_good"].includes(f.failureMode)||l("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${d}/failureMode`);for(let $ of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(f[$]===void 0)continue;let b=W(f[$],`${d}/${$}`);A.has(b)||l("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${d}/${$}`)}}wi(e,t,r,n);let c=new Set;for(let[u,E]of e.authz.dataPolicies.entries()){let d=`/config/authz/dataPolicies/${u}`,f=I(E,d);O(f,["code","name","resourceCode","unrestrictedRoleCodes","operations","matchMode","rules","readExpression","writeBoundary"],d,!0);let p=w(f.code,`${d}/code`);c.has(p)&&l("NATIVE_DATA_POLICY_DUPLICATE",`${d}/code`),c.add(p);let _=f.readExpression!==void 0,A=F(f.operations||[],`${d}/operations`,4);f.operations!==void 0&&(A.length===0||A.some(b=>!["read","create","update","delete"].includes(b)))&&l("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${d}/operations`),["AND","OR"].includes(f.matchMode)||l("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${d}/matchMode`),_&&f.operations!==void 0&&l("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${d}/operations`);let N=e.data.resources.find(b=>b.dataPolicyCode===p),m=f.resourceCode||N?.code,T=m?r.get(z(m,`${d}/resourceCode`)):void 0;_&&!T&&l("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${d}/resourceCode`);let C=F(f.unrestrictedRoleCodes||[],`${d}/unrestrictedRoleCodes`,100);f.unrestrictedRoleCodes!==void 0&&C.length===0&&l("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${d}/unrestrictedRoleCodes`);for(let b of C)t.has(b)||l("NATIVE_ROLE_REFERENCE_MISSING",`${d}/unrestrictedRoleCodes`);let $;try{let b=R(f.rules,`${d}/rules`,100).map((g,D)=>({rule:I(g,`${d}/rules/${D}`),pointer:`${d}/rules/${D}`}));b.length===0?(!_||f.matchMode!=="AND"||f.writeBoundary!=="capability_only")&&l("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",d):f.writeBoundary!==void 0&&l("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${d}/writeBoundary`),$=[...b],_&&($.push(...Me(f.readExpression,`${d}/readExpression`)),xt(f.readExpression,`${d}/readExpression`))}catch(b){throw b instanceof Ve&&l(b.code,b.pointer),b}for(let{rule:b,pointer:g}of $){O(b,["subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],g,!0);let D=W(b.field,`${g}/field`),V=T?.get(D);_&&!V&&l("NATIVE_DATA_POLICY_FIELD_MISSING",`${g}/field`);for(let K of F(b.roleCodes||[],`${g}/roleCodes`,100))t.has(K)||l("NATIVE_ROLE_REFERENCE_MISSING",`${g}/roleCodes`);let x=String(b.operator||""),k=b.operand==="db_now",Y=["is_null","is_not_null"].includes(x),M=["eq","not_eq","in","not_in"].includes(x),de=!k&&(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":"",de?"constant":"",k?"db_now":""].filter(Boolean).length!==1&&l("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",g),b.subject!==void 0&&b.subject!=="current_user"&&l("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${g}/subject`),de){if(!M&&!Y&&l("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${g}/operator`),["in","not_in"].includes(x)){let K=R(b.value,`${g}/value`,100).map((Ee,se)=>h(Ee,`${g}/value/${se}`,2048));(K.length===0||new Set(K).size!==K.length)&&l("NATIVE_DATA_POLICY_VALUE_INVALID",`${g}/value`)}else["eq","not_eq"].includes(x)?h(b.value,`${g}/value`,2048):(b.value!==void 0||b.operand!==void 0)&&l("NATIVE_DATA_POLICY_VALUE_INVALID",`${g}/value`);for(let K of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])b[K]!==void 0&&l("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${g}/${K}`)}if(k){(!["lt","lte","gt","gte"].includes(x)||b.value!==void 0||V?.type!=="datetime")&&l("NATIVE_DATA_POLICY_DB_NOW_INVALID",g);for(let K of["operation","valuePath","emptyMatchesAll","resourceCode","value"])b[K]!==void 0&&l("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${g}/${K}`)}b.dimensionCode&&!s.has(b.dimensionCode)&&l("NATIVE_SCOPE_DIMENSION_MISSING",`${g}/dimensionCode`),i.has(String(b.dimensionCode||""))&&b.operation!=="read"&&l("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${g}/operation`)}}for(let[u,E]of e.data.resources.entries()){let d=I(E,`/config/data/resources/${u}`);d.dataPolicyCode&&!c.has(d.dataPolicyCode)&&l("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${u}/dataPolicyCode`)}}function Vi(e){try{Nt(e.data.resources,"/config/data/resources")}catch(t){throw t instanceof ae&&l(t.code,t.pointer),t}}function wi(e,t,n,o){let s=new Set;for(let[r,a]of e.authz.roleMembershipSources.entries()){let i=`/config/authz/roleMembershipSources/${r}`,c=I(a,i);O(c,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],i,!0);let u=w(c.code,`${i}/code`);u.length>100&&l("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${i}/code`),s.has(u)&&l("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${i}/code`),s.add(u),h(c.name,`${i}/name`,255);let E=Pn(c.resourceCode,`${i}/resourceCode`,n);Ln(c.userIdField,`${i}/userIdField`,E),t.has(String(c.roleCode||""))||l("NATIVE_ROLE_REFERENCE_MISSING",`${i}/roleCode`),o&&c.roleCode===o&&l("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${i}/roleCode`),vn(c,i,E)}for(let[r,a]of e.authz.relationshipGrantSources.entries()){let i=`/config/authz/relationshipGrantSources/${r}`,c=I(a,i);O(c,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],i,!0);let u=w(c.code,`${i}/code`);u.length>100&&l("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${i}/code`),s.has(u)&&l("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${i}/code`),s.add(u),h(c.name,`${i}/name`,255);let E=Pn(c.resourceCode,`${i}/resourceCode`,n),d=I(c.subject,`${i}/subject`),f=h(d.type,`${i}/subject/type`,32);O(d,f==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${i}/subject`),["user","role_membership"].includes(f)||l("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${i}/subject/type`),Ln(d.userIdField,`${i}/subject/userIdField`,E),f==="role_membership"&&!t.has(String(d.roleCode||""))&&l("NATIVE_ROLE_REFERENCE_MISSING",`${i}/subject/roleCode`),w(c.relationCode,`${i}/relationCode`);let p=z(c.targetResourceCode,`${i}/targetResourceCode`);n.has(p)||l("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${i}/targetResourceCode`);let _=ye(c.resourceIdField,E),A=_?.field.type==="resource-ref.single"&&_.valuePath==="value"&&_.field.source?.resourceCode===p;(c.resourceIdField==="id"?p!==String(c.resourceCode):!A)&&l("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${i}/resourceIdField`);let N=F(c.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)))&&l("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${i}/operations`),vn(c,i,E)}}function Pn(e,t,n){let o=z(e,t),s=n.get(o);return s||l("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),s}function Ln(e,t,n){let o=ye(e,n);st(o)||l("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function vn(e,t,n){if(e.failureMode!=="strict"&&l("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let o=W(e.enabledField,`${t}/enabledField`);n.get(o)?.type!=="boolean"&&l("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let o of["effectiveFromField","effectiveToField"]){if(e[o]===void 0)continue;let s=W(e[o],`${t}/${o}`);["date","datetime"].includes(String(n.get(s)?.type))||l("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${o}`)}}function Fi(e){let t=new Set,n=new Set;e.forEach((o,s)=>{let r=`/config/backend/secrets/${s}`,a=I(o,r);O(a,["name","env","description","required","exposure"],r,!0);let i=h(a.name,`${r}/name`,128),c=h(a.env,`${r}/env`,128);Fs.test(i)||l("NATIVE_SECRET_NAME_INVALID",`${r}/name`),(!Ps.test(c)||c.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(c))&&l("NATIVE_SECRET_ENV_INVALID",`${r}/env`),t.has(i)&&l("NATIVE_SECRET_NAME_DUPLICATE",`${r}/name`),n.has(c)&&l("NATIVE_SECRET_ENV_DUPLICATE",`${r}/env`),t.add(i),n.add(c),v(a.exposure,"active_only",`${r}/exposure`),a.required!==void 0&&Pe(a.required,`${r}/required`),a.description!==void 0&&Yt(a.description,`${r}/description`,2e3)})}function Pi(e){let t=new Set,n=new Map,o=new Map(e.data.resources.map(f=>[String(f.code),f])),s=new Map(e.frontend.routes.map((f,p)=>{let _=I(f,`/config/frontend/routes/${p}`);return[w(_.code,`/config/frontend/routes/${p}/code`),_]}));for(let[f,p]of e.workflows.definitions.entries()){let _=`/config/workflows/definitions/${f}`,A=I(p,_);if(O(A,["version","definition","launch"],_,["detailRouteCode"]),to(A.launch,`${_}/launch`),A.detailRouteCode!==void 0){let C=no(A.detailRouteCode,`${_}/detailRouteCode`);for(let[$,b,g]of[["desktop",C.desktop,"admin"],["mobile",C.mobile,"user"]]){let D=`${_}/detailRouteCode/${$}`,V=s.get(b);V||l("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",D),V.surface!==g&&l("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",D);let x=ce(V.path,D),k=[...x.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(Y=>Y[1]);(x.includes("*")||k.length!==1||k[0]!=="instanceId")&&l("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",D)}}let N=I(A.definition,`${_}/definition`),m=`${N.code}:${Fe(A.version,`${_}/version`)}`;t.has(m)&&l("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",_),t.add(m),vi(N,`${_}/definition`),Li(N.subject,o,`${_}/definition/subject`);let T=kt(N,{appCode:e.appCode,capabilities:e.authz.capabilities.map(C=>C.code),fields:new Map((o.get(N.subject.resourceCode)?.schema.fields||[]).map(C=>[C.code,C]))});T.length&&l("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${_}/definition/instanceCommands`,{errors:T}),N.title===N.code&&l("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${_}/definition/title`),n.set(m,N)}let r=new Set,a=new Map;for(let[f,p]of e.workflows.bindings.entries()){let _=I(p,`/config/workflows/bindings/${f}`),A=I(_.binding,`/config/workflows/bindings/${f}/binding`),N=`${A.workflowCode}:${Fe(_.version,`/config/workflows/bindings/${f}/version`)}`;r.has(N)&&l("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${f}`),r.add(N),ki(A,`/config/workflows/bindings/${f}/binding`),a.set(N,A)}let i=new Set,c=new Map;for(let[f,p]of e.workflows.activations.entries()){let _=`/config/workflows/activations/${f}`,A=I(p,_);O(A,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],_,["environmentKey"]);let N=w(A.workflowCode,`${_}/workflowCode`);i.has(N)&&l("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",_),i.add(N);let m=`${N}:${Fe(A.definitionVersion,`${_}/definitionVersion`)}`,T=`${N}:${Fe(A.bindingVersion,`${_}/bindingVersion`)}`;t.has(m)||l("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${_}/definitionVersion`),r.has(T)||l("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${_}/bindingVersion`);let C=n.get(m),$=a.get(T);(!["finish-pinned","cancel-on-deactivate"].includes(A.acceptedCommandDeactivationPolicy)||A.acceptedCommandDeactivationPolicy!==C.acceptedCommandDeactivationPolicy)&&l("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${_}/acceptedCommandDeactivationPolicy`),Ui(C,$,`/config/workflows/activations/${f}`),c.set(N,$)}let u=new Set;e.workflows.providers.forEach((f,p)=>{let _=`/config/workflows/providers/${p}`,A=I(f,_);O(A,["code","endpointPath","timeoutMs"],_,!0);let N=w(A.code,`${_}/code`);u.has(N)&&l("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${_}/code`),u.add(N),ce(A.endpointPath,`${_}/endpointPath`),A.timeoutMs!==void 0&&Z(A.timeoutMs,`${_}/timeoutMs`,100,1e4)});for(let[f,p]of c.entries())for(let[_,A]of Object.entries(I(p.bindings,"/config/workflows/bindings/*/binding/bindings"))){let N=I(A,`/config/workflows/${f}/bindings/${_}`);N.provider==="application_provider"&&!u.has(N.providerCode)&&l("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${f}/bindings/${_}/providerCode`)}let E=new Set(e.authz.roles.map(f=>f.code)),d=new Set;e.workflows.editableParameters.forEach((f,p)=>{let _=`/config/workflows/editableParameters/${p}`,A=I(f,_);O(A,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],_,!0);let N=w(A.code,`${_}/code`);d.has(N)&&l("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${_}/code`),d.add(N);let m=Et(A.workflowCode,`${_}/workflowCode`),T=qt(A.bindingKey,`${_}/bindingKey`),C=c.get(m);(!C||!I(C.bindings,`${_}/bindingKey`)[T])&&l("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${_}/bindingKey`),h(A.label,`${_}/label`,255),["role_code","user_ids","provider_code"].includes(A.valueType)||l("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${_}/valueType`);for(let $ of F(A.allowedRoleCodes||[],`${_}/allowedRoleCodes`,100))E.has($)||l("NATIVE_ROLE_REFERENCE_MISSING",`${_}/allowedRoleCodes`);for(let $ of F(A.allowedProviderCodes||[],`${_}/allowedProviderCodes`,100))u.has($)||l("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${_}/allowedProviderCodes`);A.required!==void 0&&Pe(A.required,`${_}/required`),A.maxItems!==void 0&&Z(A.maxItems,`${_}/maxItems`,1,200)})}function Li(e,t,n){let o=I(e,n);O(o,["resourceCode","factProjection"],n,["summaryFields"]);let s=z(o.resourceCode,`${n}/resourceCode`),r=t.get(s);r||l("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${n}/resourceCode`);let a=new Set(R(I(r.schema,`${n}/resourceCode`).fields,`${n}/resourceCode`,500).map((u,E)=>W(I(u,`${n}/resourceCode/${E}`).code,`${n}/resourceCode/${E}`))),i=I(o.factProjection,`${n}/factProjection`),c=Object.entries(i);(c.length<1||c.length>64)&&l("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${n}/factProjection`);for(let[u,E]of c){ks.test(u)||l("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${n}/factProjection/${u}`);let d=W(E,`${n}/factProjection/${u}`);a.has(d)||l("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${n}/factProjection/${u}`)}if(o.summaryFields!==void 0){let u=F(o.summaryFields,`${n}/summaryFields`,Us).map((_,A)=>W(_,`${n}/summaryFields/${A}`)),E=t.get(s),d=E.surface&&typeof E.surface=="object"&&!Array.isArray(E.surface)?E.surface:{},f=d.fields&&typeof d.fields=="object"&&!Array.isArray(d.fields)?d.fields:{},p=new Map(R(I(E.schema,`${n}/resourceCode`).fields,`${n}/resourceCode`,500).map((_,A)=>{let N=I(_,`${n}/resourceCode/${A}`);return[String(N.code),N]}));for(let[_,A]of u.entries()){let N=p.get(A),m=f[A],T=String(N?.type||""),C=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(A)||!Ms.has(T)||T==="text.long"&&typeof C=="number"&&Number.isFinite(C)&&C>xs)&&l("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${n}/summaryFields/${_}`)}}}function vi(e,t){O(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands"]),v(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),Et(e.code,`${t}/code`),h(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||l("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let n=I(e.nodes,`${t}/nodes`),o=Object.keys(n);(o.length===0||o.length>200)&&l("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let s=h(e.startAt,`${t}/startAt`,128);n[s]||l("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let r=new Map;for(let[u,E]of Object.entries(n)){let d=`${t}/nodes/${u}`,f=I(E,d);v(f.id,u,`${d}/id`),["approval","condition","end"].includes(f.kind)||l("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${d}/kind`);let p=[];if(f.kind==="approval"){h(f.title,`${d}/title`,255),qt(f.binding,`${d}/binding`),["single","any","all","sequence"].includes(f.mode)||l("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${d}/mode`),p.push(h(f.onApprove,`${d}/onApprove`,128),h(f.onReject,`${d}/onReject`,128));for(let _ of F(f.returnTargets||[],`${d}/returnTargets`,200))n[_]||l("NATIVE_WORKFLOW_TARGET_MISSING",`${d}/returnTargets`);for(let _ of F(f.allowedOperations||[],`${d}/allowedOperations`,20))Bs.has(_)||l("NATIVE_WORKFLOW_OPERATION_INVALID",`${d}/allowedOperations`)}else if(f.kind==="condition"){let _=R(f.branches,`${d}/branches`,100);_.length===0&&l("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${d}/branches`),_.forEach((A,N)=>{let m=I(A,`${d}/branches/${N}`);je(m.when,`${d}/branches/${N}/when`,0),p.push(h(m.target,`${d}/branches/${N}/target`,128))}),p.push(h(f.otherwise,`${d}/otherwise`,128))}else h(f.title,`${d}/title`,255),h(f.outcome,`${d}/outcome`,128);for(let _ of p)n[_]||l("NATIVE_WORKFLOW_TARGET_MISSING",d);r.set(u,p)}let a=new Set,i=new Set,c=u=>{if(i.has(u)&&l("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${u}`),!a.has(u)){a.add(u),i.add(u);for(let E of r.get(u)||[])c(E);i.delete(u)}};c(s),a.size!==o.length&&l("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function je(e,t,n){n>20&&l("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let o=I(e,t),s=h(o.op,`${t}/op`,16);if(s!=="literal"){if(s==="path"){let r=h(o.path,`${t}/path`,255);/^[A-Za-z][A-Za-z0-9_.]{0,254}$/.test(r)||l("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(s)){je(o.left,`${t}/left`,n+1),je(o.right,`${t}/right`,n+1);return}if(["and","or"].includes(s)){let r=R(o.values,`${t}/values`,100);r.length===0&&l("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),r.forEach((a,i)=>je(a,`${t}/values/${i}`,n+1));return}if(["not","exists"].includes(s)){je(o.value,`${t}/value`,n+1);return}l("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function ki(e,t){v(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),Et(e.workflowCode,`${t}/workflowCode`);let n=I(e.bindings,`${t}/bindings`);Object.keys(n).length>200&&l("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[o,s]of Object.entries(n)){qt(o,`${t}/bindings/${o}`);let r=I(s,`${t}/bindings/${o}`),a=h(r.provider,`${t}/bindings/${o}/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)||l("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${o}/provider`),a==="fixed_users"&&R(r.users,`${t}/bindings/${o}/users`,200).length===0&&l("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${o}/users`),["input_users","form_field_users"].includes(a)&&h(r.inputPath,`${t}/bindings/${o}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(a)&&w(r.roleCode,`${t}/bindings/${o}/roleCode`),a==="department_supervisor"&&h(r.departmentIdFrom,`${t}/bindings/${o}/departmentIdFrom`,255),a==="application_provider"&&w(r.providerCode,`${t}/bindings/${o}/providerCode`)}}function Ui(e,t,n){v(t.workflowCode,e.code,`${n}/workflowCode`);let o=I(t.bindings,`${n}/bindings`);for(let[s,r]of Object.entries(I(e.nodes,`${n}/nodes`))){let a=I(r,`${n}/nodes/${s}`);a.kind==="approval"&&!o[a.binding]&&l("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${n}/nodes/${s}/binding`)}}function xi(e,t,n){let o=I(t.routeManifest,"/contracts/routeManifest"),s=I(e.routeManifest,"/contracts/routeManifest"),r=new Map;for(let E of R(n.data?.resources,"/config/data/resources",100)){let d=I(E,"/config/data/resources");r.set(String(d.code||""),d)}let a=new Set(R(s.routes,"/contracts/routeManifest/routes",1e3).map(E=>String(I(E,"/contracts/routeManifest/routes").code||""))),i=[];for(let E of R(o.routes,"/contracts/routeManifest/routes",1e3)){let d=I(E,"/contracts/routeManifest/routes"),f=String(d.kind||"");if(f!=="resource-records"&&f!=="resource-submit")continue;let p=String(d.resourceCode||""),_=r.get(p);_||l("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let N=`user.${p}.${f==="resource-records"?"records":"submit"}`;v(String(d.code||""),N,"/contracts/routeManifest/routes/code");let m=f==="resource-records"?"read":"create",T=String(I(_.capabilities,"/config/data/resources/capabilities")[m]||"");for(let C of["desktop","mobile"]){let $=I(d[C],`/contracts/routeManifest/routes/${C}`),b=C==="mobile"?"/m/my/":"/my/",g=f==="resource-records"?`${b}${p}`:`${b}${p}/submit`;v(String($.path||""),g,`/contracts/routeManifest/routes/${C}/path`),v(String($.capability||""),T,`/contracts/routeManifest/routes/${C}/capability`),v(String($.routeCode||""),`${N}.${C}`,`/contracts/routeManifest/routes/${C}/routeCode`)}(a.has(N)||i.some(C=>String(C.code)===N))&&l("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),i.push(d)}if(!i.length)return;s.routes=R([...s.routes,...i],"/contracts/routeManifest/routes",1e3).sort((E,d)=>re(String(I(E,"x").code||""),String(I(d,"x").code||"")));let c=String(I(o.rootEntry,"x").code||"");if(i.find(E=>String(E.code)===c&&E.kind==="resource-records")){let E=I(o.rootEntry,"x");s.rootEntry={code:c,desktop:String(E.desktop||""),mobile:String(E.mobile||"")}}s.digest=ee({schemaVersion:s.schemaVersion,appCode:s.appCode,devicePolicy:s.devicePolicy,rootEntry:s.rootEntry,authentication:s.authentication,routes:s.routes})}function Ce(e,t,n){let o=I(e,t);O(o,["schemaVersion","appCode","code","name","schema","surface","invariants","capabilities","dataPolicyCode","fieldPolicies"],t,!0),v(o.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),v(o.appCode,n,`${t}/appCode`);let s=z(o.code,`${t}/code`),r=h(o.name,`${t}/name`,255),a=I(o.schema,`${t}/schema`);O(a,["fields"],`${t}/schema`);let i,c;try{i=qe(a.fields,`${t}/schema/fields`),c=Tt(o.invariants,i,`${t}/invariants`),Ze(o.surface,i,`${t}/surface`)}catch(f){throw f instanceof ae&&l(f.code,f.pointer),f}let u=new Set(i.map(f=>f.code)),E=I(o.capabilities,`${t}/capabilities`);O(E,["read","create","update","delete"],`${t}/capabilities`);let d=I(o.fieldPolicies,`${t}/fieldPolicies`);for(let[f,p]of Object.entries(d)){!u.has(f)&&!Re(f)&&l("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${f}`);let _=`${t}/fieldPolicies/${f}`,A=I(p,_);Re(f)&&(O(A,["read"],_,!0),(!Array.isArray(A.read)||A.read.length>20||A.read.some(N=>typeof N!="string"||!N.trim())||new Set(A.read).size!==A.read.length)&&l("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${_}/read`)),O(A,["read","create","update","mask"],_,!0),A.mask!==void 0&&!["omit","null"].includes(A.mask)&&l("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${_}/mask`)}return{...o,code:s,name:r,schema:{fields:i},...o.invariants===void 0?{}:{invariants:c},capabilities:E,fieldPolicies:d}}function oo(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,n])=>({code:t,kind:"platform",name:n,source:"platform"}))]}function kn(e,t,n,o){let s=e.toString("utf8"),r;try{r=JSON.parse(s)}catch{l(n,t)}let a=I(r,t);return Q(a)!==s&&l(o,t),a}function Un(e,t){let n=0,o=(s,r,a)=>{if(n+=1,n>zs&&l("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",r),a>Gs&&l("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",r),typeof s=="string"){Buffer.byteLength(s)>jt&&l("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",r);return}if(Array.isArray(s)){s.forEach((i,c)=>o(i,`${r}/${c}`,a+1));return}if(!(!s||typeof s!="object"))for(let[i,c]of Object.entries(s))["__proto__","prototype","constructor"].includes(i)&&l("NATIVE_ARTIFACT_DANGEROUS_KEY",`${r}/${i}`),Mi(i)&&l("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${r}/${i}`),o(c,`${r}/${i}`,a+1)};o(e,t,0)}function Mi(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function we(e){return{value:e,digest:ee(e)}}function xn(e,t,n,o){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&l("NATIVE_ARTIFACT_BYTES_REQUIRED",n);let s=Buffer.isBuffer(e)?e:Buffer.from(e);return s.byteLength===0&&l("NATIVE_ARTIFACT_EMPTY",n),s.byteLength>t&&l(o,n),s}function Mn(e,t,n,o){let s=ut.createHash("sha256").update(e).digest("hex");ut.timingSafeEqual(Buffer.from(s),Buffer.from(t))||l(o,n)}function I(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&l("NATIVE_OBJECT_REQUIRED",t),e}function R(e,t,n){return Array.isArray(e)||l("NATIVE_ARRAY_REQUIRED",t),e.length>n&&l("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function F(e,t,n){let o=R(e,t,n).map((s,r)=>h(s,`${t}/${r}`,255));return new Set(o).size!==o.length&&l("NATIVE_ARRAY_DUPLICATE",t),o}function h(e,t,n){return(typeof e!="string"||e.length===0||e.length>n)&&l("NATIVE_STRING_INVALID",t),e}function Yt(e,t,n){return(typeof e!="string"||e.length>n)&&l("NATIVE_STRING_INVALID",t),e}function w(e,t){let n=h(e,t,128);return Ds.test(n)||l("NATIVE_CODE_INVALID",t),n}function z(e,t){let n=h(e,t,64);return Vs.test(n)||l("NATIVE_RESOURCE_CODE_INVALID",t),n}function W(e,t){let n=h(e,t,63);return ws.test(n)||l("NATIVE_FIELD_CODE_INVALID",t),n}function Et(e,t){let n=h(e,t,128);return Ls.test(n)||l("NATIVE_WORKFLOW_CODE_INVALID",t),n}function qt(e,t){let n=h(e,t,128);return vs.test(n)||l("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),n}function Ne(e,t,n){let o=h(e,t,255);return Ss.test(o)||l("NATIVE_CAPABILITY_CODE_INVALID",t),!o.startsWith(`app:${n}:`)&&!oo(n).some(s=>s.code===o)&&l("NATIVE_CAPABILITY_APP_MISMATCH",t),o}function ce(e,t){let n=h(e,t,2048);return(!n.startsWith("/")||n.startsWith("//")||n.includes("..")||n.includes("?")||n.includes("#"))&&l("NATIVE_ABSOLUTE_PATH_INVALID",t),n}function Fe(e,t){return(!Number.isInteger(e)||Number(e)<1)&&l("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function Z(e,t,n,o){return(!Number.isInteger(e)||Number(e)<n||Number(e)>o)&&l("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function Pe(e,t){return typeof e!="boolean"&&l("NATIVE_BOOLEAN_REQUIRED",t),e}function Jt(e,t){let n=h(e,t,64).toLowerCase();return Rs.test(n)||l("NATIVE_DIGEST_INVALID",t),n}function v(e,t,n){e!==t&&l("NATIVE_VALUE_MISMATCH",n)}function O(e,t,n,o=!1){let s=new Set([...t,...Array.isArray(o)?o:[]]);for(let r of Object.keys(e))s.has(r)||l("NATIVE_PROPERTY_UNKNOWN",`${n}/${r}`);if(o!==!0)for(let r of t)Object.prototype.hasOwnProperty.call(e,r)||l("NATIVE_PROPERTY_REQUIRED",`${n}/${r}`)}function X(e,t){return[...e].sort((n,o)=>re(t(n),t(o)))}function j(e){return[...new Set(e)].sort(re)}function jn(e){return[...new Set(e)].sort((t,n)=>t-n)}function re(e,t){return e===t?0:e<t?-1:1}function so(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>so(t))),e}function Wt(e,t,n){if(Mt(e,t))return n;if(Array.isArray(e)&&Array.isArray(t)){let o=Math.max(e.length,t.length);for(let s=0;s<o;s+=1)if(!Mt(e[s],t[s]))return Wt(e[s],t[s],`${n}/${s}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let o=j([...Object.keys(e),...Object.keys(t)]);for(let s of o){let r=e[s],a=t[s];if(!Mt(r,a))return Wt(r,a,`${n}/${s}`)}}return n}function Mt(e,t){return e===void 0||t===void 0?e===t:Q(e)===Q(t)}function l(e,t,n={}){throw new ct(e,t,n)}var ji="adb8c53a2ce31e6c6d5c4cb9626c45f5fc072bd360b51b259faa543edf8fcbb3";0&&(module.exports={DATA_AUDIT_METADATA_FIELDS,DATA_EVENT_TYPES_V2,DATA_SYSTEM_SORT_FIELD_CODES,NATIVE_CONFIGURATION_VALIDATOR_DIGEST,NATIVE_CONTRACT_CAPACITY_V2,NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,NATIVE_DATA_QUERY_OPERATORS_V2,NativeConfigurationCompilerError,NativeDataFieldContractV2Error,NativeDataPolicyExpressionV2Error,NativeEventActionContractError,NativeScopeSourceFieldPathV2Error,OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2,OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,WORKFLOW_EVENT_TYPES_V2,compileNativeApplicationConfiguration,compileNativeEventAction,compileNativeEventCapturePlansV2,compileRequiredPlatformCapabilitiesV3,hasDataAuditReadPolicy,isDataAuditMetadataField,isDataSystemSortField,isNativeDataQueryOperatorV2,isNativeMultiValueFieldV2,materializeNativeDataQueryPathTypesV2,nativeDataPolicyExpressionLeavesV2,nativeDataPolicyExpressionToCnfV2,nativeDataQueryPathPlanV2,nativeFieldAggregatePlanV2,nativeFieldColumnDefinitionV2,nativeFieldDefaultSqlV2,nativeFieldHasDefaultV2,nativeFieldIndexStatementsV2,nativeFieldRequiresCreateInputV2,nativeFieldSequenceGrantStatementsV2,nativeFieldSequenceOwnershipStatementsV2,nativeFieldSequenceStatementsV2,nativeFieldSupportsFilterV2,nativeFieldSupportsOperatorV2,nativeFieldSupportsSearchV2,nativeFieldSupportsSortV2,nativeOperatorsForFieldV2,nativePhysicalFieldV2,nativePhysicalFieldsV2,nativePhysicalObjectNameV2,nativeScopeSourceFieldValueV2,nativeScopeSourceGrantPathSupportedV2,nativeScopeSourceSubjectPathSupportedV2,nativeSubtableConstraintStatementsV2,parseNativeDataFieldsV2,parseNativeDataResourceInvariantsV2,projectNativeDataResourceViewV2,quoteNativeIdentifierV2,resolveNativeScopeSourceFieldPathV2,validateNativeDataDraftStateV2,validateNativeDataResourceReferencesV2,validateNativeDataResourceSurfaceV2,validateWorkflowInstanceCommandPolicies,workflowInstanceCommandDeadlineError,workflowInstanceTerminateCapabilityAllowed,workflowPolicyTimestamp});
|